Add SSH Key to AWS EC2 Instance using Ansible Playbook

Add SSH Key to AWS EC2 Instance using Ansible Playbook

- hosts: ec2
  gather_facts: false
  tasks:

    -name: Add SSH key to EC2 instance
     ec2_key:
     name: my_key
     key_material: "{{ lookup('file', '/path/to/my_key.pem') }}"
     region: us-east-1
     state: present

To use this playbook, replace "my_key" with the desired name for the SSH key, and replace "/path/to/my_key.pem" with the path to the PEM file for the SSH key on your local machine. You will also need to replace "us-east-1" with the appropriate region code for your EC2 instance.

To run the playbook, use the following command:

ansible-playbook -i hosts add_ssh_key.yml

This will add the SSH key to the EC2 instance, allowing you to SSH into the instance using the key.