如何使用 Ansible 块模块使用多个 with_items

How to use multiple with_items using Ansible block module

我们可以在同一个任务中使用多个 with_items 吗,在这个例子中我使用了两个 with_items,第一个是存储像 net.ipv6.conf.all.disable_ipv6 = 1 这样的值,第二个是获取寄存器变量data_captured

中捕获的数据

我这样使用有冲突

- name: Test with with_items
  block:
    - name: Searching several string
      command: grep -w "{{item}}" /root/test/sysctl.conf
      register: data_captured
      with_items:
      - 'net.ipv6.conf.all.disable_ipv6 = 1'
      - 'net.ipv6.conf.default.disable_ipv6 = 1'
      - 'net.ipv6.conf.lo.disable_ipv6 = 1'
      - 'vm.swappiness = 1'
    - assert:
        that:
          - "'net.ipv6.conf.all.disable_ipv6 = 1' in item.stdout"
          - "'net.ipv6.conf.default.disable_ipv6 = 1' in item.stdout"
          - "'net.ipv6.conf.lo.disable_ipv6 = 1' in item.stdout"
          - "'vm.swappiness = 1' in item.stdout"  
        success_msg: "Protocols are  defined in the file"
      with_item: '{{ data_captured.results }}'
  rescue:
    - name: Insert/Update /root/test/sysctl.conf
      blockinfile:
        path: /root/test/sysctl.conf
        block: |
          net.ipv6.conf.all.disable_ipv6 = 1
          net.ipv6.conf.default.disable_ipv6 = 1
          net.ipv6.conf.lo.disable_ipv6 = 1
          vm.swappiness = 1

你应该使用 sysctl module 而不是那样解决它。

这会做你想做的事:

- name: ensure values are set correctly in sysctl
  ansible.posix.sysctl:
    name: '{{ item.name }}'
    value: '{{ item.value }}'
    state: present
    reload: yes
  loop:
    - name: 'net.ipv6.conf.all.disable_ipv6'
      value: '1'
    - name: 'net.ipv6.conf.default.disable_ipv6'
      value: '1'
    - name: 'net.ipv6.conf.lo.disable_ipv6'
      value: '1'
    - name: 'vm.swappiness'
      value: '1'

您可能需要 运行 ansible-galaxy collection install ansible.posix 在您的 ansible-controller 上(您 运行 ansibleansible-playbook 命令)在 运行编写剧本。

补充说明:

  • 不鼓励使用 with_*,应该使用 loop(参见 docs
  • 看看 lineinfile module,如果 sysctl 模块不存在,它会有你需要的东西
  • assert 上的 with_item 在你的情况下完全是多余的,因为你没有在任务
  • 中使用 {{ item }}