I created an ec2 instance with port 22 open and I am able to connect to this instance using the private key from my terminal, however, I am not able to connect it when I try ansible-playbook. I have been using dynamic inventory.
The command I use for SSH and which is successful too (I am running the below command where the private key is placed):
ssh -i "test-key.pem" ubuntu@ec2-x-x-x-x.eu-central-1.compute.amazonaws.com
Content for the playbook:
---
- name: Hello World example
hosts: all
become: true
tasks:
- name: Printing Hello World
debug:
msg: "Hello World"
The command I ran:
ansible-playbook -i ec2.py --private-key /home/testuser/.ssh/test-key.pem -l instance_id playbook-hello.yml
even I tried with:
ansible-playbook -i ec2.py --private-key /home/testuser/.ssh/test-key.pem -l instance_id -e 'ansible_ssh_user=ubuntu' playbook-hello.yml
Error:
fatal: [x.x.x.x]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host x.x.x.x port 22: Operation timed out\r\n", "unreachable": true}
Other details:
I am running ansible-playbooks on my MacBook Pro. The EC2 instance is running Ubuntu OS 18.04.
When I run ./ec2.py – I can see my instance is getting printed. AWS Keys are saved in home directory .aws/credentials folder.
P.S:
This question could be a duplicate of other questions available but I did not get any positive insight to match with my case.
Best Answer
It was my bad to understand that the ec2.py script, which was used, only returning instances with private IPs. And because of that, it was not able to connect to the instance on port 22.
However, when I was doing ssh, I was using a Public IP or a DNS name.
So instead of using ec2.py, I executed the script using the public IP:
a.b.c.d -- is a public IP of an instance.
If by any chance anyone gets a below error:
Please use the below command:
Just make sure, pythos3 is installed on the mentioned path of the instance, where you are trying to execute the playbook.