【问题标题】:In Ansible, is there a way to pass multiple dictionaries into a with_dict task loop?在 Ansible 中,有没有办法将多个字典传递到 with_dict 任务循环中?
【发布时间】:2016-03-10 03:49:07
【问题描述】:

我正在尝试在任务循环中将多个字典输入 with_dict。

vars/users.yml 文件

---
server_admins:
  admin1: comment="Dark Helmet" uid=10000 state=present
  admin2: comment="Princess Vespa" uid=10001 state=present

developers:
  dev1: comment="Prince Valium" uid=2000 state=present

group_vars/webservers.yml

---
ssh_users:
  - "{{ server_admins }}"
  - "{{ developers }}"

tasks/main.yml

---
- name: create users
  user: name={{ item.key }} {{ item.value }}
  with_dict: "{{ ssh_users }}"

如果我在 {{ ssh_users }} 中仅定义一个字典,则任务按预期运行。但是当我添加第二个字典时,我得到“with_dict 需要一个字典”。显然没想到他们两个!

到目前为止,我的解决方法是为每个用户组创建一个新角色,但这已经失控,而且似乎不是一个好的解决方案,因为我在每个用户组中都复制了相同的逻辑角色。

关于如何将多个字典传递或连接到 with_dict 或以任务循环可以处理的方式构造数据的任何想法;同时仍然保持单一角色?

【问题讨论】:

  • 您正在传递一个字典列表列表;一种解决方案是使用set_fact: ssh_users: "{{ developers + server_admins }}" 合并列表;另一个会将单个用户从 dict 转换为哈希 (name='admin1' comment=''...),然后使用 with_items。
  • 很遗憾,字典不支持“+”运算符。此外,我的用户和组比这里列出的要多得多。我刚刚写了一个简化版的角色来说明我想要完成的工作。

标签: python loops dictionary yaml ansible


【解决方案1】:

从 Ansible 2.0 开始,有一个 Jinja 过滤器,combine,用于此:

  ---
  - name: create users
    user: name={{ item.key }} {{ item.value }}
    with_dict: "{{ server_admins | combine(developers) }}"

【讨论】:

  • 感谢有关组合过滤器的示例。然而,这并不是我想要的。目的是使任务可重用,并且此解决方案假定我将始终使用相同的字典,或者始终要传递一定数量的字典。我将在 group_vars 中使用 combine() 进行试验,看看能否获得我正在寻找的行为。
猜你喜欢
  • 2015-01-23
  • 2019-08-20
  • 1970-01-01
  • 2021-02-05
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
相关资源
最近更新 更多