You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible 2.9使用ec2_instance_info获取EC2挂载EBS卷信息用于打标签

解决方案

报错原因

你之前的遍历报错是因为属性名拼写错误,ec2_instance_info返回的实例块设备属性为block_device_mappings(末尾带s),而非你写的block_device_mapping,且卷ID存储在每个块设备的ebs子属性下,不能直接从item中读取volume_id。

实现方案

方案1:直接遍历块设备列表(推荐,适配任意数量卷)

不需要额外提取列表,直接遍历原生返回的块设备属性即可适配所有节点不同的卷数量:

- name: 遍历打印卷信息
  debug:
    msg: "{{ ansible_ec2_instance_id }}: {{ item.device_name }} {{ item.ebs.volume_id }}"
  loop: "{{ ec2_node_info.instances[0].block_device_mappings }}"

方案2:提取为独立列表按索引访问

如果需要按指定索引单独访问对应卷的信息,可以先将两个属性提取为独立列表:

- name: 提取设备名、卷ID为独立列表
  set_fact:
    dev_name_list: "{{ ec2_node_info | json_query('instances[*].block_device_mappings[*].device_name') | flatten }}"
    vol_id_list: "{{ ec2_node_info | json_query('instances[*].block_device_mappings[*].ebs.volume_id') | flatten }}"

# 索引从0开始计数,示例为打印第1、第2个卷的信息
- name: 打印第1个卷信息
  debug:
    msg: "{{ ansible_ec2_instance_id }}: {{ vol_id_list[0] }} {{ dev_name_list[0] }}"

- name: 打印第2个卷信息
  debug:
    msg: "{{ ansible_ec2_instance_id }}: {{ vol_id_list[1] }} {{ dev_name_list[1] }}"

完整打标签任务示例

直接使用遍历方式给所有EBS卷批量打标签:

- name: 给EBS卷打实例ID、设备名标签
  ec2_tag:
    region: "{{ lookup('env','AWS_DEFAULT_REGION') }}"
    aws_access_key: "{{ lookup('env','AWS_ACCESS_KEY_ID') }}"
    aws_secret_key: "{{ lookup('env','AWS_SECRET_ACCESS_KEY') }}"
    resource: "{{ item.ebs.volume_id }}"
    state: present
    tags:
      instance_id: "{{ ansible_ec2_instance_id }}"
      ebs_device_name: "{{ item.device_name }}"
  loop: "{{ ec2_node_info.instances[0].block_device_mappings }}"

内容的提问来源于stack exchange,提问作者Brandon DeYoung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:02