1.查看模塊幫助
~]# man-ansible-doc(查看Ansible自帶的模塊文檔信息)
~]# ansible-doc -l(列出支持的所有模塊)
~]# ansible-doc -s MODULE_NAME(查看模塊支持的配置指令)
2.使用語法
ansible <host-pattern> [-m module_name] [-a args] [options]
OPTIONS
host-pattern:對哪些主機生效,支持組名
-f:啓動併發線程數,指定一批處理主機數量
-m:使用模塊
-a:模塊特有的參數
3.常見模塊
command(命令模塊,默認模塊,用於在遠程執行命令)
cron(任務計劃)
~]# ansible websrvs -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state=present' #默認state=present(安裝),可省略不寫 ~]# ansible websrvs -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state=absent' #state=absent(移除) ~]# ansible websrvs -a 'crontab -l' #查看任務列表
user(用戶賬號管理)
~]# ansible all -m user -a 'name=user1'
group(組管理)
~]# ansible websrvs -m group -a 'name=mysql gid=306 system=yes' ~]# ansible websrvs -m user -a 'name=mysql uid=306 system=yes group=mysql' #定義爲system用戶,則shell爲nologin,無需再額外指定
copy
~]# ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640' ~]# ansible all -m copy -a 'content="Hello World\nHello China\n" dest=/tmp/test.ansible'
OPTIONS
src:本地源文件路徑,支持相對路徑和絕對路徑,如果指定目錄,則複製目錄下所有文件
dest:遠端目標文件路徑,僅支持絕對路徑
owner:屬主
group:屬組,不指定默認與owner一致
mode:權限
content:取代src,直接生成目標文件內容,兩者不能同時使用
file(設置文件屬性)
~]# ansible all -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.ansible' #path:指定文件路徑,可以使用name或dest來替換
~]# ansible all -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ansible state=link' #創建符號鏈接,指定link模式
OPTIONS
src:源文件
path:符號鏈接文件路徑
ping(測試遠程主機連通性)
~]# ansible all -m ping
service(指定運行狀態)
~]# ansible websrvs -a 'service httpd status' ~]# ansible websrvs -a 'chkconfig --list httpd' ~]# ansible websrvs -m service -a 'enabled=true name=httpd state=started'
OPTIONS
enabled:true/false,定義是否開機啓動
name:服務名
state:started/stoped/restarted
shell(類似command,用到管道等複雜命令建議使用)
~]# ansible all -m shell -a 'echo test | passwd --stdin user1' ~]# ansible all -m command -a 'echo test | passwd --stdin user1' #command命令無法傳遞,上述命令執行後無法設定密碼
script(將本地腳本複製到遠程主機,並運行,腳本僅支持相對路徑)
~]# vim test.sh #編輯腳本
#!/bin/bash echo "hello world" > /tmp/script.ansible #腳本內容
~]# chomd +x test.sh #加入執行權限 ~]# ansible all -m script -a 'test.sh' #腳本僅支持相對路徑
yum
~]# ansible all -m yum -a 'name=httpd' #默認安裝,可不指定state=present ~]# ansible all -m yum -a 'name=httpd state=absent'
OPTIONS
name:指明安裝程序包及版本,不指定版本則安裝最新版本
state:present(安裝)\latest(安裝最新版)\absent(卸載)
setup(收集遠程主機的facts)
每個被管理節點在接受並運行管理命令之前,會將自己主機相關信息,如OS版本、IP等報告給遠程的ansible主機
~]# ansible all -m setup
#默認顯示全部信息