ansible 获取已存在的 aws ebs 卷 id

dsa*_*don 5 amazon-ec2 ansible ansible-2.x

我正在尝试使用 ansible 获取已存在并附加到 ec2 实例的 aws 卷 id。我有一个使用 ec2_remote_facts 模块的查找任务,该模块获取 ec2 实例的详细信息,包括卷 ID 详细信息:

- name: lookup ec2 virtual machines
  ec2_remote_facts:
    aws_access_key: "{{aws_access_key}}"
    aws_secret_key: "{{aws_secret_key}}"
    region: "{{ec2_region}}"
    filters:
      instance-state-name: running
      "tag:Name": "{{server_name}}"
      "tag:Environment": "{{environment_type}}"
      "tag:App": "{{app_name}}"
      "tag:Role": "{{role_type}}"
  register: ec2_info
Run Code Online (Sandbox Code Playgroud)

示例输出:

    "msg": [
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-01-12T17:24:17.000Z",
                    "delete_on_termination": true,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-123456789"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-123456789",
                    "name": "BE-VPC"
                }
            ],
..... and more
Run Code Online (Sandbox Code Playgroud)

现在我只需要获取块设备映射->volume_id,但我不知道如何只获取ID

我尝试了几个无法仅获取卷 ID 的任务,例如:

-  debug: msg="{{item | map(attribute='block_device_mapping') | map('regex_search','volume_id') | select('string') | list }}"
   with_items: "{{ec2_info.instances | from_json}}"
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

- name: get associated vols
  ec2_vol:
    aws_access_key: "{{aws_access_key}}"
    aws_secret_key: "{{aws_secret_key}}"
    region:  "{{ec2_region}}"
    instance: "{{ ec2_info.isntances.id }}"
    state: list
    region: "{{ region }}"
  register: ec2_vol_lookup


- name: tag the volumes
  ec2_tag:
    aws_access_key: "{{aws_access_key}}"
    aws_secret_key: "{{aws_secret_key}}"
    region:  "{{ec2_region}}"
    resource: "{{ item.id }}"
    region:  "{{ region }}"
    tags:
      Environment: "{{environment_type}}"
      Groups: "{{group_name}}"
      Name: "vol_{{server_name}}"
      Role: "{{role_type}}"
  with_items: "{{ ec2_vol_lookup.volumes | default([]) }}"
Run Code Online (Sandbox Code Playgroud)

任何想法?

版本:2.2.0.0

Kon*_*rov 4

如果您有单实例和单块设备,请使用:

- debug: msg="{{ ec2_info.instances[0].block_device_mapping[0].volume_id }}"
Run Code Online (Sandbox Code Playgroud)

如果您有很多实例和很多块设备:

- debug: msg="{{ item.block_device_mapping | map(attribute='volume_id') | list }}"
  with_items: "{{ ec2_info.instances }}"
Run Code Online (Sandbox Code Playgroud)

对于单实例和多设备的情况:

- debug: msg="{{ ec2_info.instances[0].block_device_mapping | map(attribute='volume_id') | list }}"
Run Code Online (Sandbox Code Playgroud)