一,ansible的shell模塊和command模塊的區別?
shell模塊:在遠程主機上執行主控端發出的shell/python腳本
command模塊:不能調用shell指令,沒有bash的環境變量,也不能使用shell的一些操作,在遇到"<",">","|","&"將會終止。
它不支持變量、重定向、管道符等,這些操作需要用shell模塊執行.
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,shell模塊執行命令的例子:
1,進入指定的目錄后執行指令:
# chdir : 指定一個目錄,在執行對應的命令之前,會先進入到 chdir 參數指定的目錄下
[liuhongdi@centos8 ~]$ ansible yujian -m shell -a "chdir=/usr/local/soft pwd;" 121.122.123.47 | CHANGED | rc=0 >> /usr/local/soft
2,檢查nginx服務是否在進程中?
用shell可以使用管道符,比如查看遠程受控端nginx服務是否啟動
說明;用command模塊就會報錯,因為不支持管道。
這是shell模塊和command模塊的主要區別
#grep -v grep 不看包含有grep字符串的進程
[liuhongdi@centos8 ~]$ ansible yujian -m shell -a "ps auxfww | grep nginx: | grep -v grep" 121.122.123.47 | CHANGED | rc=0 >> root 7491 0.0 0.0 50412 3340 ? Ss Mar11 0:00 nginx: master process /usr/soft/openresty/nginx/sbin/nginx nginx 7492 0.0 0.0 82576 7756 ? S Mar11 0:12 \_ nginx: worker process nginx 7493 0.0 0.0 81892 5940 ? S Mar11 0:00 \_ nginx: worker process nginx 7494 0.0 0.0 81892 7184 ? S Mar11 0:00 \_ nginx: worker process nginx 7495 0.0 0.0 81892 5940 ? S Mar11 0:00 \_ nginx: worker process nginx 7496 0.0 0.0 81892 5940 ? S Mar11 0:00 \_ nginx: worker process nginx 7497 0.0 0.0 81892 7056 ? S Mar11 0:00 \_ nginx: worker process nginx 7498 0.0 0.0 81892 5940 ? S Mar11 0:00 \_ nginx: worker process nginx 7499 0.0 0.0 81892 5940 ? S Mar11 0:00 \_ nginx: worker process
3,把命令執行結果保存到重定向文件
說明:command模塊不支持重定向
[liuhongdi@centos8 ~]$ ansible yujian -m shell -a "chdir=/data/site/think_www git status >> /home/webop/work/gitstatus.txt" 121.122.123.47 | CHANGED | rc=0 >>
登錄到受控端,查看生成的結果文件
[root@blog ~]$ cd /home/webop/work [root@blog work]$ more gitstatus.txt On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
4,常用的一個例子:從受控端使用git發布代碼
#warn=no 不理會警告信息
[liuhongdi@centos8 ~]$ ansible yujian -m shell -a "chdir=/data/site/think_www warn=no git pull origin master" --become --become-method=sudo --become-user=root
5,常用的一個例子:查看服務器空間使用情況
[liuhongdi@centos8 work]$ ansible yujian -m shell -a "df -h | grep /dev/vd" 121.122.123.47 | CHANGED | rc=0 >> /dev/vda1 100G 14G 87G 14% / /dev/vdb1 500G 3.6G 497G 1% /databak
三,查看ansible的版本
[root@centos8 liuhongdi]# ansible --version ansible 2.9.5