title: Ansible AWS: Unable to connect to EC2 instance
body: <h1>What I want to achieve</h1>
  
  <p>I want to create an EC2 instance with LAMP stack installed using one Ansible playbook.</p>
  
  <h1>Problem</h1>
  
  <p>The instance creation works fine, and I can modify it in the EC2 Console, but the problem appears when trying to access the instance for example install apache or create keys.</p>
  
  <p>This is the error:</p>
  
  <blockquote>
    <p>fatal: [35.154.26.86]: UNREACHABLE! => {
        "changed": false, 
        "msg": "[Errno None] Unable to connect to port 22 on  or 35.154.26.86", 
        "unreachable": true
    }</p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/ziVVi.png" rel="nofollow noreferrer">Error Screenshot</a></p>
  
  <h1>Code</h1>
  
  <p>This is my playbook:</p>
  
  <pre><code>---
  - name: Power up an ec2 with LAMP stack installed
    hosts: localhost
    become: true
    become_user: root
    gather_facts: False
    vars:
      keypair: myKeyPair
      security_group: launch-wizard-1
      instance_type: t2.micro
      image: ami-47205e28
      region: x-x-x
    tasks:
      - name: Adding Python-pip
        apt: name=python-pip state=latest
  
      - name: Install Boto Library
        pip: name=boto
  
      - name: Launch instance (Amazon Linux)
        ec2:
           key_name: "{{ keypair }}"
           group: "{{ security_group }}"
           instance_type: "{{ instance_type }}"
           image: "{{ image }}"
           wait: true
           region: "{{ region }}"
           aws_access_key: "xxxxxxxxxxxxxxxxxxx"
           aws_secret_key: "Xxxxxxxxxxxxxxxxxxx"
        register: ec2
  
      - name: Print all ec2 variables
        debug: var=ec2
  
      - name: Add all instance public IPs to host group
        add_host: hostname={{ item.public_ip }} groups=ec2hosts
        with_items: "{{ ec2.instances }}"
  
  
  - hosts: ec2hosts
    remote_user: ec2-user
    become: true
    gather_facts: false
    tasks:
  #I need help here, don't know what to do.
      - name: Create an EC2 key
        ec2_key:
          name: "privateKey"
          region: "x-x-x"
          register: ec2_key
  
      - name: Save private key
        copy: content="{{ ec2_key.private_key }}" dest="./privateKey.pem" mode=0600
        when: ec2_key.changed
  
      # The Rest is installing LAMP
  </code></pre>
  
  <h1>Information:</h1>
  
  <p>1- My hosts file is default.</p>
  
  <p>2- I used this command to run the playbook:</p>
  
  <blockquote>
    <p>sudo ansible-playbook lamp.yml -vvv -c paramiko</p>
  </blockquote>
  
  <p>3- launch-wizard-1 has SSH.</p>
  
  <p>4- myKeyPair is a public key imported from my device to the console(don't know if this is ok)</p>
  
  <p>5- I am a big newbie</p>