初學(xué)playbook
案例
playbook只有一個(gè)play
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers:
- name: restart apache
service: name=httpd state=restarted
指定主機(jī)和用戶
每一個(gè)play都可以指定主機(jī)和用戶去執(zhí)行task
- hosts: webservers
hosts 行的內(nèi)容是一個(gè)或多個(gè)組或主機(jī)的 patterns,以逗號(hào)為分隔符
remote_user: root
執(zhí)行用戶名
sudo命令
sudo: yes
支持sudo命令吼渡,可以放在task內(nèi),作為一個(gè)task使用sudo命令
name
task必須要有名字乓序,以便輸出日志中區(qū)分哪一個(gè)task
moudle格式
task:
- name: make sure apache is running
service: name=httpd state=running
service moudle 使用 key=value 格式的參數(shù)
command和shell格式
但是command 和 shell ,它們不使用 key=value 格式的參數(shù):
tasks:
- name: disable selinux
command: /sbin/setenforce 0
得到失敗shell結(jié)果
如果你想要shell執(zhí)行失敗的結(jié)果寺酪,可以使用||
:
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand || /bin/true
||
表示左邊shell命令執(zhí)行失敗后才會(huì)執(zhí)行右邊命令
具體可了解:https://blog.csdn.net/zxk364961978/article/details/54848773
或者使用:ignore_errors: True
,忽略錯(cuò)誤
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand
ignore_errors: True
變量
在action中可以使用變量,但需要在vars
那里先定義一個(gè)變量 :
tasks:
- name: create a virtual host file for {{ vhost }}
template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
handlers發(fā)生改變后執(zhí)行
當(dāng)遠(yuǎn)程主機(jī)發(fā)生改動(dòng)后替劈,在每一個(gè)task完成后寄雀,執(zhí)行notify
,且只會(huì)執(zhí)行一次
notify
下面列出的就是handlers
,得到notify
通知后執(zhí)行。且也只會(huì)執(zhí)行一次
- name: template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached
- restart apache
handlers:
- name: restart memcached
service: name=memcached state=restarted
- name: restart apache
service: name=apache state=restarted
Handlers 最佳的應(yīng)用場(chǎng)景是用來(lái)重啟服務(wù),或者觸發(fā)系統(tǒng)重啟操作.
執(zhí)行一個(gè)playbook
ansible-playbook playbook.yml -f 10
-f 10
: 并發(fā)數(shù)是10
查看這個(gè)playbook會(huì)影響到那些host
ansible-playbook playbook.yml --list-hosts
參考文檔:
ansible playbook指南:http://www.ansible.com.cn/docs/playbooks.html