推荐学习网站 www.ansible.com.cn
playbook核心元素
yaml语法中注意两个基本要素列表【以"-"开头】及字典【key:value】
hosts 远程主机列表
tasks 任务集
varniables 内置或自定义变量
templates
=================
handlers和notify结合使用,handler就是task列表当操作的资源产生变化时会采取一定操作,而notify的
action用于在每个play的最后被触发,这样可避免多次有改变发生时每次都执行指定的操作,仅在所有变化发
生完成后一次性执行指定操作。在notify中列出的操作被称为handler,也就是notify中调用handler中定义的操作
=================
tags 指定某条任务执行,用于选择运行playbook中的部分代码
普通playbook演示
#####file.yml
---
- hosts: a //a组中的目标机
remote_user: root //以远程root用户执行
tasks:
- name: hello //说明性这个task的描述
command: hostname //模块名: 命令
- name: touch file
file: name=/tmp/test.txt
- name: create user
user: name=test password=test system=yes shell=/sbin/nologin
- name: install package
yum: name=httpd
- name: copy conf
copy: src=/etc/httpd/httpd.conf dest=/tmp/
- name: start service
service: name=httpd state=started enabled=yes
handler和notify演示
###该例演示当《再次》执行playbook,第1,3动作未对目标机进行改变,而第2个动作进行了改变,此时执行notify调用的handler进行httpd服务重启
注意1,3中添加的tags标签,该操作可指定只执行play中标签对应的动作
操作tags标签的命令为ansible-playbook -t install-httpd,start-httpd httpd.yml
***允许多个动作使用同一个tags标签
============分隔符 httpd.yml================
---
- host: a
remote_user: root
task:
- name: install httpd
yum: name=httpd
tags: install-httpd
- name: copy config-file
copy: src=file/httpd.conf dest=/etc/httpd/conf/ backup=yes
notify:
-restart service handler
-echo
- name: start service
service: name=httpd state=started enabled=yes
tags: start-httpd
handler:
-name: restart service handler
service: name=httpd state=restarted
-name: echo
shell: echo 1
##执行这个playbook -C参数可以检查 并不在远程主机上真正做出任何改变
ansible-playbook -C file.yml
##真正执行
ansible-playbook file.yml
ansible-vault用于管理加密playbook的yml文件
加密playbook,执行后设立密码,若执行则需要解密
ansible-vault encrypt hello.yml
解密
ansible-vault decrypt hello.yml
查看加密的playbook
ansible-vault view hello.yml
编辑加密后的playbook
ansible-vault edit hello.yml
修改key
ansible-vault rekey hello.yml
ansible-console
ansible-console a
显示如下
root@a (2)[f:5]$
意为以root用户@读取/etc/ansible/hosts文件的a组下的主机(包含两台)[并发为5]
技巧:
若playbook中某条task中执行错误,正常情况不会继续执行下面的task,若想继续执行可按下面来做
方法1
task:
- name: run command
shell: /user/bin/xxx || /bin/true
方法2
task:
- name: run command
shell: /usr/bin/xxx
ignore_errors: True