Ansible AWS create and manipulate EC2

Viewed 145

Hello i use this playbook for create EC2 instance i use this documentation to make my playbook: https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_module.html#parameter-instance_tags

###Example pour launch une instance###
###ansible-playbook --extra-vars "hosts=ansible-test"###
- hosts: localhost
##Init variable##
  vars:
    keypair: "AWS-KEYS-WEBSERVER001"
    instance_type: t2.micro
    hosts: "{{ hosts }}"
    groups: "Web"
    image: "ami-0ea4a063871686f37"

  tasks:

    - name: startup new instance
      community.aws.ec2_instance:
         key_name: "{{ keypair }}"
         security_group: "Web"
         instance_type: "{{ instance_type }}"
         name: "fermela"
         image_id: "{{ image }}"
         wait: true
         region: "eu-west-3"
         network:
           assign_public_ip: true
         vpc_subnet_id: "subnet-0c82e6027833af6cc"
      register: ec2

    - debug :
            var: ec2

my playbook works and the debug give me output like :

ok: [localhost] => {
    "ec2": {
        "changed": false,
        "changes": [],
        "failed": false,
        "instance_ids": [
            "i-0ecb077aafd7fda1c"
        ],
        "instances": [
            {
                "ami_launch_index": 0,
                "architecture": "x86_64",
                "block_device_mappings": [
                    {
                        "device_name": "/dev/xvda",
                        "ebs": {
                            "attach_time": "2021-02-23T00:34:53+00:00",
                            "delete_on_termination": true,
                            "status": "attached",
                            "volume_id": "vol-0ad6a503c6cfa7f97"
                        }
                    }
                ],

I would like manipulate this output for only dispaly ip_public

Can someone help me plz ?

I already try debug with var: ec2.public_ip but doesn't work

2 Answers

ec2_instance returns a list of instances, in this case you have just one instance. Try as below:

- debug :
    var: ec2.instacnes[0].public_ip_address

You can't do this as in your output there is no public ip address. Try this use ansible_facts to register

- debug :
    ansible_facts['ansible_ec2_public_ipv4']

Only those variables can be accessed that are shown in debug after registering.

Related