Ansible:从两个单独的词典列表中构建一个词典列表

时间:2018-10-17 21:40:02

标签: ansible yaml

我有两个变量文件,需要分别维护。第一个 internal_ips.yml 包含IP地址列表:

addresses:
  - ip: 172.1.2.3
    rule_desc: this is 1.2.3
  - ip: 173.1.2.4
    rule_desc: this is 1.2.4

第二个变量文件 port_rules.yml 包含规则列表(最终用于为应用程序构造安全组):

app_rules:
  - ports: 80
    proto: TCP
  - ports: 443
    proto: TCP

我想执行任务:

- name: example using security group rule descriptions
    ec2_group:
    name: some name
    description: sg with rule descriptions
    vpc_id: vpc-xxxxxxxx
    profile: aws profile
    region: us-east-1
    rules: "{{ rule_list }}"

其中 rule_list 是要构造的变量,其格式为:

rule_list:
  - proto: tcp
    ports: 80
    cidr_ip: 172.1.2.3/32
    rule_desc: this is 1.2.3
  - proto: tcp
    ports: 80
    cidr_ip: 172.1.2.4/32
    rule_desc: this is 1.2.4
  - proto: tcp
    ports: 443
    cidr_ip: 172.1.2.3/32
    rule_desc: this is 1.2.3
  - proto: tcp
    ports: 443
    cidr_ip: 172.1.2.4/32
    rule_desc: this is 1.2.4

构造变量 rule_list 的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这是您要查找的代码吗?

- set_fact:
    rules: "{{ rules + [ item.0 | combine(item.1)] }}"
  loop: "{{ app_rules | product(addresses) | list }}"