Bootstrap FreeKB - Ansible - List Amazon Web Services (AWS) VPC Subnets using the ec2_vpc_subnet_info module
Ansible - List Amazon Web Services (AWS) VPC Subnets using the ec2_vpc_subnet_info module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

Prerequisites

ec2_vpc_subnet_info can be used to list your Amazon Web Services (AWS) Virtual Private Cloud (VPC) Subnets.

---
- name: main play
  hosts: localhost
  tasks:
  - name: list AWS VPC Subnets
    amazon.aws.ec2_vpc_subnet_info:
    register: aws_ec2_vpc_subnets

  - debug:
      var: aws_ec2_vpc_subnets
...

 

Something like this should be returned.

ok: [localhost] => {
    "aws_ec2_vpc_subnets": {
        "changed": false,
        "failed": false,
        "subnets": [
            {
                "assign_ipv6_address_on_creation": false,
                "availability_zone": "us-east-1d",
                "availability_zone_id": "use1-az6",
                "available_ip_address_count": 4091,
                "cidr_block": "172.31.32.0/20",
                "default_for_az": true,
                "enable_dns64": false,
                "id": "subnet-01234417780abcdbc",
                "ipv6_cidr_block_association_set": [],
                "ipv6_native": false,
                "map_customer_owned_ip_on_launch": false,
                "map_public_ip_on_launch": true,
                "owner_id": "713542074252",
                "private_dns_name_options_on_launch": {
                    "enable_resource_name_dns_a_record": false,
                    "enable_resource_name_dns_aaaa_record": false,
                    "hostname_type": "ip-name"
                },
                "state": "available",
                "subnet_arn": "arn:aws:ec2:us-east-1:72345207233:subnet/subnet-01234417780abcdbc",
                "subnet_id": "subnet-01234417780abcdbc",
                "tags": {},
                "vpc_id": "vpc-011234cfa335abcd1"
            }
        ]
    }
}

 

Almost always, I end up creating a list that contains each Subnet ID.

---
- name: main play
  hosts: localhost
  tasks:
  - name: amazon.aws.ec2_vpc_subnet_info
    amazon.aws.ec2_vpc_subnet_info:
    register: aws_ec2_vpc_subnets

  - name: append each Subnet ID to the subnet_ids list
    set_fact:
      subnet_ids: "{{ subnet_ids | default([]) + [ item.id ] }}"
    with_items: "{{ aws_ec2_vpc_subnets.subnets }}"

  - debug:
      var: subnet_ids
...

 

Which should return something like this.

ok: [localhost] => {
    "subnet_ids": [
        "subnet-03f11417780f61234",
        "subnet-09b70fa463fcd5678",
        "subnet-0f35c3586e5099012",
        "subnet-03c64e403dc5b3456",
        "subnet-0316e4d9fcd4e7890",
        "subnet-05727079637281234"
    ]
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter fdc05a in the box below so that we can be sure you are a human.