Loops ansible循环同时覆盖列表和字典
我正在写一本剧本,确保节点出现在Loops ansible循环同时覆盖列表和字典,loops,ansible,Loops,Ansible,我正在写一本剧本,确保节点出现在/etc/fstab中 我使用循环来防止代码重复 逻辑是首先使用grep(使用perl regex,因为它是一个多行)检查该行是否出现,并将结果存储在寄存器中 然后我只想添加不在fstab文件中的行。为了实现这一点,我需要遍历列表(带有grep返回码的寄存器)和字典(包含fstab条目) 我的并行循环有错误。我试着按照步骤做 一个或多个未定义的变量:“str object”没有属性“item” 任务/fstab.yaml: --- - name: Make dir
/etc/fstab
中
我使用循环来防止代码重复
逻辑是首先使用grep(使用perl regex,因为它是一个多行)检查该行是否出现,并将结果存储在寄存器中
然后我只想添加不在fstab文件中的行。为了实现这一点,我需要遍历列表(带有grep返回码的寄存器)和字典(包含fstab条目)
我的并行循环有错误。我试着按照步骤做
一个或多个未定义的变量:“str object”没有属性“item”
任务/fstab.yaml:
---
- name: Make dirs
sudo: yes
file: path={{ item.value }} state=directory
with_dict:
"{{ fstab.paths }}"
- name: Check whether declared in fstab
sudo: no
command: grep -Pzq '{{ item.value }}' /etc/fstab
register: is_declared
with_dict:
"{{ fstab.regexs }}"
- name: Add the missing entries
sudo: yes
lineinfile: dest=/etc/fstab line="{{ item.1.item.value }}"
when: item.0.rc == 1
with_together:
- "{{ is_declared.results }}"
- "{{ fstab.entries }}"
vars/main.yml:
---
fstab:
paths:
a: "/mnt/a"
b: "/mnt/b"
regexs:
a: '\n# \(a\)\nfoo1'
b: '\n# \(b\)\nfoo2'
entries:
a: "\n# (a)\nfoo1"
b: "\n# (b)\nfoo2"
- 我不是故意使用模板的(我希望将条目添加到现有文件中,而不是过度写入它们)
更新:我看到ansible有一个处理fstab的模块“mount”。不过,我仍在寻找解决此问题的方法,因为以后可能会再次需要它。关于您最初的方法失败的原因,我有一些想法,但让我们先讨论一下。看起来你把事情复杂化了——为什么不使用一个复杂的列表变量将它们联系在一起,并将regexp arg用于lineinfle模块,而不是单独的regex任务呢?(尽管您的示例数据即使没有regexp参数也可以正常工作)如下所示:
---
- name: Make dirs
sudo: yes
file: path={{ item.path }} state=directory
with_items: fstab
- name: Add the missing entries
sudo: yes
lineinfile: dest=/etc/fstab line={{ item.entry }} regexp={{ item.regex }}
with_items: fstab
关于您最初的方法失败的原因,我有一些想法,但让我们先来讨论一下。看起来你把事情复杂化了——为什么不使用一个复杂的列表变量将它们联系在一起,并将regexp arg用于lineinfle模块,而不是单独的regex任务呢?(尽管您的示例数据即使没有regexp参数也可以正常工作)如下所示:
---
- name: Make dirs
sudo: yes
file: path={{ item.path }} state=directory
with_items: fstab
- name: Add the missing entries
sudo: yes
lineinfile: dest=/etc/fstab line={{ item.entry }} regexp={{ item.regex }}
with_items: fstab
你的解决方案只适用于一行。lineinfle regexp不适用于多个线型图案。这就是我做分离的原因。你的解决方案对一行程序很好。lineinfle regexp不适用于多个线型图案。这就是我做分离的原因。你的解决方案对一行程序很好。lineinfle regexp不适用于多个线型图案。这就是为什么我要分开。