NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
[TOC] `when` 语句用来判断哪些目标主机来执行当前 tasks `with_items` 语句来循环某一个变量列表,然后将每次循环的结果放进 `item` 中 示例: ### 使用 when 判断是否执行 ``` --- - hosts: k8s become: yes vars: old_gw: "192.168.222.1" new_gw: "192.168.222.3" tasks: - name: find netplan yaml file shell: find /tmp/ -name "00-installer-config.yaml" register: interface_name when: - ansible_distribution == "Ubuntu" - ansible_distribution_version == "20.04" - name: replace gateway replace: path: "{{ item }}" regexp: "{{ old_gw }}" replace: "{{ new_gw }}" with_items: - "{{ interface_name.stdout_lines }}" #循环interface_name输出的stdout_lines内容,然后放到 {{ item }}中 when: - ansible_distribution == "Ubuntu" - ansible_distribution_version == "20.04" - name: check shell: cat {{ item }} register: file_info with_items: "{{ interface_name.stdout_lines }}" when: - ansible_distribution == "Ubuntu" - ansible_distribution_version == "20.04" - name: debug debug: msg: "{{ file_info.results[0].stdout_lines }}" ``` ### 使用 when 判断 item 的个数 ``` tasks: - name: Run with items greater than 5 ansible.builtin.command: echo {{ item }} loop: [ 0, 2, 4, 6, 8, 10 ] when: item > 5 ```