遍历ansible字典以分配字典值

时间:2020-07-14 17:50:46

标签: dictionary ansible yaml ansible-inventory

有没有办法遍历ansible字典来分配其他ansible字典值?

我的group_vars / all中包含以下内容:

domain_controllers:
  dc0:
    hostname: "dc0"
    ip_address: "192.168.1.0"
  dc1:
    hostname: "dc1"
    ip_address: "192.168.1.1"
  dc2:
    hostanme: "dc2"
    ip_address: "192.168.1.2"

我有一个通用的keepalived角色,该角色将keepalived配置为服务器角色用来为这些域控制器制作VIP。

以下是我的roles/servers/forward/vars.yml,keepalived角色用来构建keepalived.conf文件。

virtual_server:
  - virutal_server_ip: "192.168.1.10"
    virtual_server_port: 389
    ...
    real_servers:
      - real_ip: "192.168.1.0"
        real_port: 389
        description: "dc0"
        ...
      - real_ip: "192.168.1.1"
        real_port: 389
        description: "dc1"
        ...
      - real_ip: "192.168.1.2"
        real_port: 389
        description: "dc2"
        ...

  - virtual_server_ip: "192.168.1.10"
    virtual_server_port: 636
    ...
    real_servers:
      - real_ip: "192.168.1.0"
        real_port: 636
        description: "dc0"
        ...
      - real_ip: "192.168.1.1"
        real_port: 636
        description: "dc1"
        ...
      - real_ip: "192.168.1.2"
        real_port: 636
        description: "dc2"
        ...

我已经具有保持角色的jinja格式,可以根据这些变量构建/etc/keepalived.conf

我要做的是根据domain_controllers词典的内容分配这些变量。我该如何使用set_facts来分配像这样的大型嵌套字典?

我只想遍历domain_controllers,因为我想在升级和/或迁移到新的DC时更新group_vars/all,因为我也有其他使用此变量的剧本。 / p>

是否还可以在vars/main.yml中而不是通过set_facts任务来分配这些变量?

1 个答案:

答案 0 :(得分:0)

我通过以下方法解决了这个问题:

在group_vars / all中:

domain_controllers:
  - ip_address: "192.168.1.0"
    hostname: "dc0"
  - ip_address: "192.168.1.1"
    hostname: "dc1"
  - ip_address: "192.168.1.2"
    hostname: "dc2"

在我的vars文件中,我用以下命令调用了列表:

virtual_server:
  - virutal_server_ip: "192.168.1.10"
    virtual_server_port: 389
    ...
    real_servers:
      - real_ip: "{{ domain_controllers.0.ip_address }}"
        real_port: 389
        description: "{{ domain_controllers.0.hostname }}"
        ...
      - real_ip: "{{ domain_controllers.1.ip_address }}"
        real_port: 389
        description: "{{ domain_controllers.1.hostname }}"
        ...
      - real_ip: "{{ domain_controllers.2.ip_address }}"
        real_port: 389
        description: "{{ domain_controllers.2.hostname }}"
        ...

  - virtual_server_ip: "192.168.1.10"
    virtual_server_port: 636
    ...
    real_servers:
      - real_ip: "{{ domain_controllers.0.ip_address }}"
        real_port: 636
        description: "{{ domain_controllers.0.hostname }}"
        ...
      - real_ip: "{{ domain_controllers.1.ip_address }}"
        real_port: 636
        description: "{{ domain_controllers.1.hostname }}"
        ...
      - real_ip: "{{ domain_controllers.2.ip_address }}"
        real_port: 636
        description: "{{ domain_controllers.2.hostname }}"
        ...

不利的是,如果domain_controllers中至少有3个项目,则剧本会出错。我仍然想找到一种方法来遍历列表。