条件&循环
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html
01.条件:when
1.1 when测试
1 2 3 4 5 6 7 8 9
| [root@k8s-node2 ~]# vim when.yaml --- - hosts: webservers gather_facts: yes
tasks: - name: test debug: msg={{ansible_default_ipv4.address}} when: ansible_default_ipv4.address=='192.168.56.65'
|
1 2 3 4 5 6 7 8 9
| [root@k8s-node2 ~]# ansible-playbook when.yaml TASK [test] ************************************************************************************************************************************************* ok: [192.168.56.65] => { "msg": "192.168.56.65" } skipping: [192.168.56.66] PLAY RECAP ************************************************************************************************************************************************** 192.168.56.65 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.56.66 : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
|
1.2 when安装httpd
- 管理工具是yum用yum安装,管理工具为apt,用apt安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| [root@k8s-node2 ~]# cat when2.html - hosts: webservers tasks: - name: Update apache version - yum yum: name=httpd state=present when: ansible_pkg_mgr == 'yum' notify: restart httpd
- name: Update apache version - apt apt: name=apache2 state=present update_cache=yes when: ansible_pkg_mgr == 'apt' notify: restart apache2
handlers: - name: restart httpd service: name=httpd state=restarted
- name: restart apache2 service: name=apache2 state=restarted
|
1
| [root@k8s-node2 ~]# ansible-playbook when2.html
|
02 循环
2.1 with_list
1 2 3 4 5 6 7 8 9 10 11 12
| [root@k8s-node2 ~]# vim with-list1.yaml
--- - hosts: 192.168.56.66 remote_user: root gather_facts: no tasks: - debug: msg: "{{item}}" with_list: - [1,2,3] - [a,b]
|
2.2 loop
1 2 3 4 5 6 7 8 9 10 11 12
| [root@k8s-node2 ~]# vim loop.yaml
--- - hosts: 192.168.56.66 remote_user: root gather_facts: no tasks: - debug: msg: "{{item}}" loop: - [1,2,3] - [a,b]
|
__END__