第 8.1 章 Playbook流程控制--条件
第 8.1 章 Playbook流程控制
1.条件 更多详情请查看:https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html
2.循环
1.条件
条件判断使用关键词when ,同时使用and、or来作条件组合,when语句默认放在任务语句之后,用来判断当前条件为真时,才会执行上面的语句。
如下示例:
----------------------------------
这里仅基于 ansible_facts 的条件使用
----------------------------------
单个条件满足执行关机
tasks:
- name: Shut down Debian flavored systems
ansible.builtin.command: /sbin/shutdown -h now
when: ansible_facts['os_family'] == "Debian"
多个条件(满足其中一个):满足CentOS 6 或者 Debain 7执行关机
tasks:
- name: Shut down CentOS 6 and Debian 7 systems
ansible.builtin.command: /sbin/shutdown -h now
when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
(ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")
多个条件(需要全部满足):可写成列表形式
tasks:
- name: Shut down CentOS 6 systems
ansible.builtin.command: /sbin/shutdown -t now
when:
- ansible_facts['distribution'] == "CentOS"
- ansible_facts['distribution_major_version'] == "6"
如果事实或变量是字符串,并且您需要对其进行数学比较,请使用过滤器确保 Ansible 将值读取为整数:
tasks:
- ansible.builtin.shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release'] | int >= 6
在setup显示信息如下: "ansible_lsb": { "codename": "Core", "description": "CentOS Linux release 7.6.1810 (Core)", "id": "CentOS", "major_release": "7", "release": "7.6.1810" }, …… "ansible_os_family": "RedHat",
练习示例:
示例一:根据不同系统版本执行相关Apache安装命令:
# cat when.yml - hosts: web 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
示例二:判断IP为指定值执行相应IP输出操作:
# cat when1.yml --- - hosts: web gather_facts: yes remote_user: root tasks: - name: host 192.168.3.72 run this task debug: msg="{{ ansible_default_ipv4.address }} 执行任务中" when: ansible_default_ipv4.address == '192.168.3.72'
执行效果如下:
TASK [host 192.168.3.72 run this task] ******************************************************************************** skipping: [192.168.3.71] ok: [192.168.3.72] => { "msg": "192.168.3.72 执行任务中" } skipping: [192.168.3.73] skipping: [192.168.3.74]