Ansible When有条件的运行任务

When 条件表达式

  •   ==  <  >  <=  >=  !=  or  and
  •   vars is defined      # 变量存在
  •   vars is not defined    # 变量不存在
  •   vars in list            # 变量在列表中

When 四种register结果判断

  •     when: result is failed      #执行失败
  •     when: result is success  #执行成功
  •     when: result is skipped  #被跳过执行
  •     when: result is changed #是否修改

 

示例1 bool判断

---
- name: when test
  hosts: dev
  vars:
    run_debug: true
  tasks:
    - name: debug
      debug:
        msg: "hello world"
      when: run_debug |bool

 

示例2 defined

---
- name: when test
  hosts: dev
  vars:
    run_service: firewalld
  tasks:
    - name: "{{ run_service}} service"
      service:
        name: "{{ run_service }}"
        state: started
      when: run_service is defined

 

示例3 in list

---
- name: when test
  hosts: dev
  vars:
    support_os:
    - RedHat
    - CentOS
  tasks:
    - name: "OS Type"
      debug:
              msg: "The os type is {{ ansible_distribution }}"
      when: ansible_distribution in support_os  # ansible_distribution是ansible_facts中的变量

 

示例4 when + register

---
- name: when test
  hosts: dev
  tasks:
    - name: start chronyd service
      service:
        name: chronyd
        state: started
      ignore_errors: true
      register: result- name: debug
      debug:
        msg: "{{ result.failed }}"
      when: result is success  # 也可以使用 result.failed == false

 

示例4 loop + when (将对Loop中每项都执行when)

---
- name: when test
  hosts: dev
  tasks:
    - name: debug
      debug:
          msg: "{{ item }}"
      loop: "{{ ansible_mounts }}"
      when: item.mount == "/" and item.size_available > 300000000

 

posted @ 2020-04-01 12:45  Vincen_shen  阅读(1140)  评论(0编辑  收藏  举报