Ansible 定义变量与条件判断
2019-04-23 by dongnan
目标
使用 ansible
判断目标服务器 /etc/hosts
文件是否存在指定的主机名,不存在则添加该主机名。
操作步骤
定义 playbook
cat copy_docker-config.yml
---
- hosts: node
remote_user: root
tasks:
- name: copy docker directory
copy:
src: "/root/.docker"
dest: "/root/"
owner: root
group: root
directory_mode: 0700
- name: 1 - update /etc/hosts
shell: grep 'hub.demo.com' /etc/hosts || echo 404
register: host_name
- name: 2 - update /etc/hosts
shell: echo "172.16.100.111 hub.demo.com" >> /etc/hosts
when: host_name.stdout == '404'
执行 playbook
ansible-playbook copy_docker-config.yml -v
Using /etc/ansible/ansible.cfg as config file
# ...省略
TASK [copy
docker directory]
**********************************************************************************************************************************************
changed:
[node3] => {"changed": true, "checksum":
"ab9e360b0374992885df5556232ac87c3192d4c5", "dest":
"/root/.docker/config.json", "gid": 0, "group": "root", "md5sum":
"8c6250f01bcaf61747b6922b98561a1b", "mode": "0644", "owner": "root",
"size": 165, "src":
"/root/.ansible/tmp/ansible-tmp-1555666013.67-8330150906498/source",
"state": "file", "uid": 0}
# ...省略
TASK [1 - update /etc/hosts]
**********************************************************************************************************************************************
changed:
[node3] => {"changed": true, "cmd": "grep 'hub.demo.com' /etc/hosts
|| echo 404", "delta": "0:00:00.020902", "end": "2019-04-19
17:26:54.661432", "rc": 0, "start": "2019-04-19 17:26:54.640530",
"stderr": "", "stderr_lines": [], "stdout": "404", "stdout_lines":
["404"]}
# ...省略
TASK [2 - update /etc/hosts]
**********************************************************************************************************************************************
skipping: [node1] => {"changed": false, "skip_reason": "Conditional result was False"}
# ...省略
changed:
[node3] => {"changed": true, "cmd": "echo \"172.16.100.111
hub.demo.com\" >> /etc/hosts", "delta": "0:00:00.019457", "end":
"2019-04-19 17:26:54.935612", "rc": 0, "start": "2019-04-19
17:26:54.916155", "stderr": "", "stderr_lines": [], "stdout": "",
"stdout_lines": []}
PLAY RECAP
**********************************************************************************************************************************************
node1 : ok=3 changed=1 unreachable=0 failed=0
node2 : ok=3 changed=2 unreachable=0 failed=0
node3 : ok=4 changed=3 unreachable=0 failed=0
结果
- node1 与 node2 的
/etc/hosts
文件包含hub.demo.com
这个域名跳过了后续的命令。 - node3
/etc/hosts
不含此域名,则执行echo shell
命令。
小结
register
语句注册变量,存储某个命令的输出结果在变量中,方便后续使用。例如host_name
变量的值是grep
命令的输出结果。when
语句做条件判断,When语句包含Jinja2
表达式,例如host_name.stdout == '404'
条件True则执行上面的 shell 命令,False则跳过。- 其中 host_name 变量是类似 python字典,例如
{"stdout": "172.16.100.111"}
,host_name.stdout
则获得其value 。