使用 Ansible 使用 SecurityGroupIds 而不是 SecurityGroupNames 创建一个新数组

Create a new array with SecurityGroupIds instead of SecurityGroupNames with Ansible

我对 Ansible 比较陌生,我很难理解如何执行以下场景: 我有一个包含 AWS 安全组名称的数组,如下所示

['Security-Group-Name1', 'SecurityGroup-Name2', 'SecurityGroup-Name3']

但是,我想要的是有一个 SecurityGroupIds 数组。使用 Ansible,我将 ec2_group_info 作为一个选项来检索有关安全组的信息。到目前为止一切顺利...

我的问题来了。我需要使用 ec2_group_info 遍历上述数组,将我需要的安全组的名称和 return 检索到的 Id 设置到一个新数组中,所以在结束 我有这样的东西。

['Security-Group-Id1', 'SecurityGroup-Id2', 'SecurityGroup-Id3']

我知道我需要使用带有某种动态索引的循环。但是我不太清楚如何在 Ansible 中执行此操作。

我知道 Ansible Docs 的最新循环部分,我发现它们不仅令人困惑... https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html

编辑:

这是根据需要工作的当前代码:

- name: Installing pip if not existing on host
  pip:
    name: boto3

- name: Get SecurityGroupId information
  ec2_group_info:
    filters:
      group_name: ['SG-One', 'SG-Two']
      vpc_id: 'vpc-id'
  register: my_groups

- set_fact:
    my_group_ids: '{{ my_groups.security_groups | map(attribute="group_id") | list }}'

- debug:
    msg: "{{ my_groups }}"

- debug:
    msg: "{{ my_group_ids }}"

这是结果:

TASK [Gathering Facts] *************************************************** 
ok: [localhost]

TASK [machine-provisioning : Installing pip if not existing on host] ************
ok: [localhost]

TASK [machine-provisioning : Get SecurityGroupId information] ************************* 
ok: [localhost]

TASK [machine-provisioning : set_fact] *********************************
ok: [localhost]

TASK [machine-provisioning : debug] ***********************************************
ok: [localhost] => {
"msg": [
    "sg-00000000",
    "sg-11111111"
]

}

在有关循环的链接页面上,您将观察到 register:, which is how you'd capture the result of that ec2_group_info: lookup, then use the map jinja filter to extract map(attribute="group_id") from the resulting list of results; you have to feed the output of map into the list filter, because map and a few others are python generators, and thus need a terminal action to materialize their data. The set_fact: 的使用是 ansible 执行“赋值”的方式

- ec2_group_info:
    filters:
      group_name: '{{ the_group_names }}'
      vpc_id: '{{ my_vpc_id }}'
  register: my_groups
- set_fact:
    my_group_ids: '{{ my_groups.security_groups | map(attribute="group_id") | list }}'

产量:

ok: [localhost] => {"ansible_facts": {"my_group_ids": ["sg-0c5c277ed1edafb54", "sg-7597a123"]}, "changed": false}