上一章節(jié)介紹了ansible playbook的一些編寫(xiě)規(guī)范辰如,這一章節(jié)就來(lái)介紹一下ansible常用模塊饵隙。
- file 模塊
在目標(biāo)主機(jī)創(chuàng)建文件或目錄,并賦予其權(quán)限
- name: create a file
# 代表在目標(biāo)主機(jī)/root 下創(chuàng)建一個(gè) foo.txt 的文件歌粥,屬主屬組都為 foo, 權(quán)限為 0755
file: 'path=/root/foo.txt state=touch owner=foo group=foo mode=0755'
- copy 模塊
實(shí)現(xiàn) ansible服務(wù)端到被管理主機(jī)之間的文件傳送
"""
remote_src : src 在本地還是在遠(yuǎn)端(copy源也可以在遠(yuǎn)端)
False 本地, True 遠(yuǎn)端當(dāng)前
remote_src 還不支持遞歸 ,copy(Choices: True, False) [Default: no]
src: 源文件
dest: 目標(biāo)文件
mode: 權(quán)限
force: 如果內(nèi)容不同塌忽,是否啟用強(qiáng)制覆蓋 (Choices: yes, no) [Default: yes]
"""
- name: copy a file
copy: 'remote_src=no src=roles/testbox/files/foo.sh dest=/root/foo.sh mode=0644 force=no'
- stat 模塊
獲取遠(yuǎn)程文件的狀態(tài)信息
-name: check file exists
stat: '/root/foo.sh'
register: script_stat # 判斷 /root/foo.sh 是否存在,register 會(huì)把結(jié)果保存在 script_stat 這個(gè)變量中
- debug 模塊
打印語(yǔ)句到ansible執(zhí)行輸出
-debug: msg=foo.sh exists
when: script_stat.stat.exists
# 這兩句語(yǔ)句合起來(lái)的意思就代表失驶,當(dāng) foo.sh 存在的時(shí)候土居,就打印輸出 foo.sh exists
- command/shell 模塊
都是用來(lái)執(zhí)行命令主機(jī)命令行,不同之處在于shell 會(huì)調(diào)用 /bin/bahs 解釋器,所以可以使用 管道符,重定向等操作嬉探,而command則不能擦耀,所以這里推薦使用 shell 模塊
-name: run the foo.sh
command: "sh /root/foo.sh"
-name: run the foo.sh
shell: "echo 'test' > /root/test.txt "
- packaging
調(diào)用目標(biāo)主機(jī)的包管理工具進(jìn)行安裝(yum apt) centos 用yum, ubuntu用apt
- name: ensure nginx is at the latest version
yum: pkg=nginx state=latest # 使用yum安裝nginx最新版本
- name: ensure nginx is at the latest version
agt: pkg=nginx state=latest #
- service 模塊
管理目標(biāo)主機(jī)系統(tǒng)服務(wù)
-name: start nginx service
service: name=nginx state=started # 啟動(dòng)nginx服務(wù)
- template 模塊
實(shí)現(xiàn)ansible到目標(biāo)主機(jī) jinja2 模板傳輸
-name: write the nginx config file
template: src=roles/testbox/templates/nginx.conf.j2 dest=/etx/nginx/nginx.conf
- 總結(jié)
- name: print server name and user to remote testbox
shell: "echo 'current {{user}} is logging {{server_name}}' > {{output}}"
- name: create a file
file: 'path=/root/test.file state=touch mode=0755 owner=foo group=foo'
- name: copy a file
copy: 'remote_src=no src=/home/deploy/testplaybooks/roles/testbox/file/foo.sh dest=/root mode=0644 force=yes'
- name: check foo.sh exists
stat: 'path=/root/foo.sh'
register: script_stat
- debug: msg='foo.sh exists'
when: script_stat.stat.exists
- name: run foo.sh
command: 'sh /root/foo.sh'
- name: ensure nginx is at the latest version
yum: pkg=nginx state=latest
- name: write the nginx config file
template: src=/home/deploy/testplaybooks/roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: start nginx service
service: name=nginx state=started