【问题标题】:ansible loop over list and dictionary at the same timeansible同时循环列表和字典
【发布时间】:2015-06-14 08:30:12
【问题描述】:

我正在编写一个确保节点出现在/etc/fstab 中的剧本。

我使用循环来防止代码重复。

逻辑是首先使用 grep 检查该行是否出现(使用 perl 正则表达式,因为它是多行)并将结果存储在寄存器中。

然后我只想添加不在 fstab 文件中的行。为此,我需要遍历列表(带有 grep 返回代码的寄存器)和字典(包含 fstab 条目)。

并行循环出现错误。我尝试按照these 的步骤进行操作。

One or more undefined variables: 'str object' has no attribute 'item'

tasks/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”。但是我仍在寻找解决此问题的方法,因为以后可能会再次需要它。

【问题讨论】:

    标签: loops ansible


    【解决方案1】:

    对于您最初的方法失败的原因,我有几个想法,但让我们暂时搁置一下。看起来你让事情变得过于复杂了——为什么不使用复杂的列表变量将它们联系在一起,并将正则表达式参数用于 lineinfile 模块而不是单独的正则表达式任务? (尽管即使没有 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
    

    fstab:
      - path: /mnt/a
        regex: '\n# \(a\)\nfoo1'
        entry: "\n# (a)\nfoo1"
      - path: /mnt/b
        regex: '\n# \(b\)\nfoo2'
        entry: '\n# (b)\nfoo2'
    

    【讨论】:

    • 您的解决方案适用于一个班轮。 lineinfile 正则表达式不适用于多行模式。这就是我进行分离的原因。
    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多