我们可以在同一任务中使用多个with_items
吗?在本例中,我使用两个with_items
,第一个是存储类似net.ipv6.conf.all.disable_ipv6 = 1
的值,第二个是获取寄存器变量中捕获的数据data_capture
用这种方式我会有冲突。
- 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模块,而不是像那样处理它。
这将做你想做的事:
- 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控制器上运行ansible-galaxy collection install ansible.posix
(在其中运行ansible
或ansible-playbook
命令(。
附加说明:
- 不鼓励使用
with_*
,而应使用loop
(请参阅文档( - 看看lineinfile模块,如果
sysctl
模块不存在,它会满足您的需求 assert
上的with_item
在您的情况下是完全多余的,因为您在任务中没有使用{{ item }}