This article will show you how to establish SSH connection to an EC2 instance using Ansible. The playbook will run the command lsb_release -a on the EC2 instance and print the output. You must have a running EC2 instance with a key pair setup properly.
I extended the code from the Managing EC2 and VPC: AWS with Python and Boto3 Series video course by Niyazi Erdogan. You can download the source code from boto3 project. This does not have any error handling and it is not idempotent. For experimentation and learning purposes, this is good enough.
This will create a key pair called Boto3-KeyPair in your AWS account and save the private key to a file called Boto3-KeyPair.pem on your local machine. You will use this key in the Ansible playbook to connect to the EC2 instance.
In the project root directory, create the inventory.ini file:
Replace the IP 3.237.186.53 with your EC2 instance public IP. Replace the value for ansible_ssh_private_key_file with the path to your key pair file on your local machine.