Playbook核心元素
Hosts:执行的远程主机列表
Tasks:任务集
Varniables:内置变量或自定义变量在playbook中调用
Templates:模板,可替换模板文件中的变量并实现一些简单逻辑的文件
Handlers:和notity结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行
tags:标签,指定某条任务执行,用于选择运行playbook中的部分代码 ansible-playbook -t tagsname useradd.yml
Playbook参数
-k(–ask-pass) 用来交互输入ssh密码
-K(-ask-become-pass) 用来交互输入sudo密码
-u 指定用户
--syntax-check 检查yaml文件的语法是否正确
--list-task 检查tasks任务
--list-hosts 检查生效的主机
--start-at-task='system restart' 指定从某个task开始运行
warm.yml示例
[root@ansible tmp]# pwd
/var/tmp
[root@ansible tmp]# cat warm.yml
---
# warm yml file ###注释
- hosts: webs ###远程主机列表
remote_user: root ###远程用户
tasks: ###任务
- name: shutdown warming ###任务名
command: wall "This server will be shutdown after 1 min" ###执行模块
- name: create file
file: state=touch name=/root/f1.txt
- name: copy file
copy: src=111.txt dest=/root/111.txt ###相对路径
注意:一个name,只能使用一个模块
相对路径指的是,playbook脚本所在目录
ignore_errors
如果剧本命令有错误,将不会往下执行
可以用如下方式跳过:
taks:
- name: skip errors
shell: /usr/bin/somecommand || /bin/true
或
tasks:
- name: skip errors
shell: /usr/bin/somecommand
ignore_errors: Ture
Handlers和Notify
Handlers是task列表,这些task与前述的task并没有本质上的不同,用于当关注的资源发生变化是,才会采取一定的操作。
Notify此action可用于在每个play的最后被触发,这样可避免多次有改变发生时每次都执行指定的操作,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作
---
- hosts: all
remote_user: root
tasks:
- name: install
yum: name=httpd
- name: copy conf file
copy: src=file/httpd.conf dest=/etc/httpd/conf backup=yes
notify:
- restart service ####当上述执行产生改变后,执行notify操作
- check
- name: start service
service: name=httpd state=started enable=yes
handlers:
- name: restart service ####notify名字
service: name=httpd state=restarted ####notify的操作内容
- name: check
shell: command
Tags
可以两个操作共用一个tags
ansible-playbook -t abc httpd.yml
---
- hosts: all
remote_user: root
tasks:
- name: install
yum: name=httpd
tags: abc #####把上述操作打标签
- name: copy conf file
copy: src=/root/httpd.conf dest=/etc/httpd/conf backup=yes
notify: restart service
- name: start service
service: name=httpd state=started enable=yes
handlers:
- name: restart service
service: name=httpd state=restarted