ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
使用when关键字,当when后面指定的条件满足时,该tasks中指定的某个任务才会被执行 1)When语句 * 在when后面使用表达式,当表达式结果为True则执行 案例: ~~~ tasks: - name: "shut down Debian flavored systems" command: /sbin/shutdown -t now when: ansible_os_family == "Debian" (当操作系统为debian时就执行关机操作) --- - hosts: webserver user: admin become: yes vars: - username: user01 tasks: - name: create {{ username }} user user: name={{ username }} when: ansible_fqdn == "node2.51yuki.cn" (当主机名为node2.51yuki.cn就在该机器上创建用户user01) ~~~ ~~~ --- - hosts: webserver user: admin become: yes tasks: - name: host 192.168.20.138 run this task debug: msg="{{ansible_default_ipv4.address}}" when: ansible_default_ipv4.address == "192.168.20.138" - name: all host run this task shell: hostname register: info - name: hostname is node2 run this task debug: msg="{{ansible_fqdn}}" when: info['stdout']=="node2.51yuki.cn" ~~~ * 可以使用列表形式来表示,当多个条件同时满足才执行 ~~~ tasks: - name: "shut down CentOS 6 systems" command: /sbin/shutdown -t now when: - ansible_distribution == "CentOS" - ansible_distribution_major_version == "6" (只有当系统是centos,并且版本为6的机器上执行) ~~~ * 使用变量进行判断 ~~~ vars: epic: true tasks: - shell: echo "This certainly is epic!" when: epic ~~~ * 与循环一起使用 ~~~ tasks: - command: echo {{ item }} with_items: [ 0, 2, 4, 6, 8, 10 ] when: item > 5 ~~~ * 角色包含使用when ~~~ - include: tasks/sometasks.yml when: "'reticulating splines' in output" - hosts: webservers roles: - { role: debian_stock_config, when: ansible_os_family == 'Debian' } ~~~