-2

I'm creating an AWS instance and need to get the hostname, ip address in the same play. How to get the metadata. I tried 'ec2_instance_facts', 'ec2_metadata_facts', these are giving the host ansible playbook is running not the one just created.

I have tried using different modules '

- name: Debug
  ec2_metadata_facts:
- debug: var=ansible_ec2_hostname
- debug: var=ansible_ec2_public_ipv4
- debug: var=ansible_ec2_public_hostname


- ec2_instance_facts:
   region: "ap-southeast-2"
   filters:
      "tag:Name": A01NANISIM20

  register: ec2_metadata

These snippets are not giving the details of the insatnce created, instead they give the details of the instance where playbook is run.

DevOps Junky
  • 287
  • 1
  • 5
  • 22

2 Answers2

4
- ec2_instance_facts:
   region: "ap-southeast-2"
   filters:
      "tag:Name": A01NANISIM04

  register: ec2_metadata

- debug: msg="{{ ec2_metadata.instances }}"

- debug: msg="{{ ec2_metadata.instances[0].public_ip_address }}"

Finally I figured out myself. I didn't realize that ansible is an amalgamation of technologies. Just understood that the output is JSON data and all I need to form is the appropriate tags.

DevOps Junky
  • 287
  • 1
  • 5
  • 22
0

I've been using the ohai_ec2 fact run task based on the region or availability zone as ec2_instance_facts fails for me with a boto3 bug

using https://stackoverflow.com/a/51308298/4389552 let me see which facts I can use

e.g.

 {{ ohai_ec2.region }}

# find the region
  - name: get the region and availability zone
    debug:
      msg: "Region is {{ ohai_ec2.region }} and zone is {{ ohai_ec2.availability_zone }}"

Clyde Jones
  • 363
  • 3
  • 8