I am not being able to ssh into EC2 after creation in ansible

I am new to ansible and trying to create EC2 and i have several other tasks to perform. here is the code,

`

  • name: Create a Dataloading environment
    hosts: localhost
    gather_facts: False

vars:
key_name: sims-admin
instance_type: t2.micro
image: ami-e86f35ff
region: us-east-1

tasks:

  • name: Provision EC2 instances
    ec2:
    key_name: “{{ key_name }}”
    instance_type: “{{ instance_type }}”
    image: “{{ image }}”
    wait: true
    exact_count: 1
    region: “{{ region }}”
    count_tag:
    Name: CounttagANSIBLEDataloading
    instance_tags:
    Name: ANSIBLEDataloading
    register: ec2

  • name: Add new instance to host group
    add_host: hostname={{ item.public_ip }} groupname=amazon_ec2
    with_items: ‘{{ec2.instances}}’

  • name: Wait for the instances to boot by checking the ssh port
    wait_for: host={{item.public_dns_name}} port=22 delay=60 timeout=320 state=started
    with_items: ‘{{ec2.instances}}’

  • name: Configure instance
    hosts: amazon_ec2
    become: True
    gather_facts: True

tasks:

  • name: Get the latest updates for instance
    apt:
    update_cache: yes
    upgrade: dist

`

It works until breathing room but fails in configure instance. I get the error saying

`

fatal: [54.145.185.81]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}

`

At first i was struggling to even ssh to come up to work. I finally got it work somehow but now the configure instance is not working. i am using ansible 2 on mac.

I am not sure why Configure instance fails? how am i supposed to login to ec2 in ansible? i have the key.pem in ~/.ssh/key.pem

Please help me with explanation and maybe links to relevant links. Alsthough i have been to several links and since my basic understanding on ansible is low i dont quite get it.