Ansible:循环输出变量时迭代失败

Ansible:循环输出变量时迭代失败

以下是我从 ansible playbook 中得到的调试输出:

    "msg": {
        "changed": false, 
        "failed": false, 
        "instances": [
            {
                .........
                "private_dns_name": "ip-10-XXX-XXX-XX.ec2.internal", 
                "private_ip_address": "10.XXX.XXX.XX", 
                "product_codes": [], 
                "public_dns_name": "", 
                "root_device_name": "/dev/sda1", 
                "root_device_type": "ebs", 
                "security_groups": ["...."], 
                "source_dest_check": true, 
                ......
                "private_dns_name": "ip-10.XXX.XXX.XX.ec2.internal", 
                "private_ip_address": "10.XXX.XXX.XX", 
                "product_codes": [], 
                "public_dns_name": "", 
                "root_device_name": "/dev/sda1", 
                "root_device_type": "ebs", 
                "security_groups": ["...."], 
                "source_dest_check": true, 
            }
        ]
    }
}

我想对创建的 EC2 实例进行磁盘分区。output变量由 JSON 格式组成IP addresses,我想循环遍历每个 IP 地址并获取服务器的磁盘信息,然后我使用parted模块按照如下所示进行分区。

- name: Collect Disk Information 
      setup:
        gather_subset:
          - hardware
      delegate_to: "{{ output.instances[0].private_ip_address }}"
    
    - name: Print disks Details
      debug:
        var: hostvars[inventory_hostname].ansible_devices.keys()|list
     
    - name: Create Partition
      parted:
        device: "/dev/{{ item }}"
        number: 1
        part_type: 'primary'
        state: present
      delegate_to: "{{ output.instances[0].private_ip_address }}"
      with_items: "{{ hostvars[inventory_hostname].ansible_devices.keys() }}"

这个任务只能对数组进行分区instances[0],我想循环遍历private_ip_address输出变量中的所有内容。如何实现?

我也尝试过下面

尝试 1:

      delegate_to: "{{ item.private_ip_address }}"
      loop: "{{ output.instances }}"

答案1

例如

- hosts: localhost
  vars:
    output:
      instances: [
         {"name": "ip-10", "ip": "10.1.0.10"},
         {"name": "ip-20", "ip": "10.1.0.20"}]
  tasks:
    - debug:
        msg: "delegate_to: {{ item.ip }}"
      loop: "{{ output.instances }}"

给出

  msg: 'delegate_to: 10.1.0.10'
  msg: 'delegate_to: 10.1.0.20'

相关内容