ansible 默認提供了很多模塊來供我們使用。在 Linux 中,我們可以通過 ansible-doc -l 命令查看到當前 ansible 都支持哪些模塊,通過 ansible-doc -s 模塊名 又可以查看該模塊有哪些參數可以使用。
我們常用的幾個模塊:
copy file cron group user yum service script ping command raw get_url synchronize
ansible '*' -m command -a 'uptime'
'*':自己定義的主機 -m command:命令
# 指定節點上的權限,屬主和數組為root
ansible '*' -m file -a "dest=/tmp/t.sh mode=755 owner=root group=root"
#指定節點上定義一個計划任務,每隔3分鍾到主控端更新一次時間
ansible '*' -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate 172.16.254.139"'
# 指定節點上創建一個組名為aaa,gid為2017的組
ansible all -m group -a 'gid=2017 name=a'
# 在節點上創建一個用戶aaa,組為aaa
ansible all -m user -a 'name=aaa groups=aaa state=present'
刪除用戶示例
ansible all -m user -a 'name=aaa groups=aaa remove=yes'
# 在節點上安裝httpd
ansible all -m yum -a "state=present name=httpd"
# 在節點上啟動服務,並開機自啟動
ansible all -m service -a 'name=httpd state=started enabled=yes'
# 檢查主機連接
ansible '*' -m ping
# 執行遠程命令
ansible '*' -m command -a 'uptime'
# 執行主控端腳本
ansible '*' -m script -a '/root/test.sh'
# 執行遠程主機的腳本
ansible '*' -m shell -a 'ps aux|grep zabbix'
# 類似shell
ansible '*' -m raw -a "ps aux|grep zabbix|awk '{print \$2}'"
# 創建軟鏈接
ansible '*' -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link"
# 刪除軟鏈接
ansible '*' -m file -a "path=/tmp/resolv.conf state=absent"
# 復制文件到遠程服務器
ansible '*' -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg owner=root group=root mode=0644"
# 在節點上運行hostname
nsible all -m raw -a 'hostname|tee'
# 將指定url上的文件下載到/tmp下
ansible all -m get_url -a 'url=http://10.1.1.116/favicon.ico dest=/tmp'
ynchronize模塊:
目的:將主控方/root/a目錄推送到指定節點的/tmp目錄下
命令:ansible all -m synchronize -a 'src=/root/a dest=/tmp/ compress=yes'
執行效果:
delete=yes 使兩邊的內容一樣(即以推送方為主)
compress=yes 開啟壓縮,默認為開啟
--exclude=.git 忽略同步.git結尾的文件
由於模塊,默認都是推送push。因此,如果你在使用拉取pull功能的時候,可以參考如下來實現
mode=pull 更改推送模式為拉取模式
目的:將10.1.1.113節點的/tmp/a目錄拉取到主控節點的/root目錄下
命令:ansible 10.1.1.113 -m synchronize -a 'mode=pull src=/tmp/a dest=/root/'
執行效果:
由於模塊默認啟用了archive參數,該參數默認開啟了recursive, links, perms, times, owner,group和-D參數。如果你將該參數設置為no,那么你將停止很多參數,比如會導致如下目的遞歸失敗,導致無法拉取
其它相關的參數解釋:
1
2
3
|
dest_port=22
# 指定目的主機的ssh端口,ansible配置文件中的 ansible_ssh_port 變量優先級高於該 dest_port 變量
rsync_path
# 指定 rsync 命令來在遠程服務器上運行。這個參考rsync命令的--rsync-path參數,--rsync-path=PATH # 指定遠程服務器上的rsync命令所在路徑信息
rsync_timeout
# 指定 rsync 操作的 IP 超時時間,和rsync命令的 --timeout 參數效果一樣
|