AWS EC2 Create & Remove Keypair Using Ansible Playbook
AWS EC2 Create & Remove Keypair using ansible playbook is possible. In last article i have shown you how to create EC2 instance using Ansible Playbook in this i am going to show you how to create keypair.
Generate RSA Keypair
[user@rhel7 .ssh]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again:
AWS EC2 Create & remove Keypair
---
- hosts: localhost
connection: local
gather_facts: false
vars:
region: 'us-east-1'
tasks:
- name: Create New Key Pair with specified Keyname
ec2_key:
name: sshkeypair
region: us-east-1
key_material: 'ssh-rsa AAAAB3N...... user@rhel7'
force: false
[root@rhel7 playbooks]# ansible-playbook createkeypair.yml PLAY [localhost] ********************************************************************************************************************* TASK [Create New Key Pair with specified Keyname] ************************************************************************************ changed: [localhost] PLAY RECAP *************************************************************************************************************************** localhost : ok=1 changed=1 unreachable=0 failed=0
Take above generate keypair content from ~/.ssh/id_rsa.pub and paste it in key_material value
Note: If you do not download a keypair immediate after creating you can’t retrieve after.
AWS EC2 Remove Keypair
---
- hosts: localhost
connection: local
gather_facts: false
vars:
region: 'us-east-1'
tasks:
- name: Remove Key Pair
local_action: ec2_key
region={{ region }}
name="sshkeypair"
state="absent"
Play Ansible playbook to remove the specified keypair from region
# ansible-playbook removekey.yml PLAY [localhost] ********** TASK [Remove Key Pair] ******* changed: [localhost -> localhost] PLAY RECAP ******** localhost : ok=1 changed=1 unreachable=0 failed=0
Related Articles
Download Plays from techtutorials GitHub
Automation make tech life easier
Thanks for Your Wonderful Support and Encouragement
More than 40,000 techies are part of our ARKIT community. Join us today and keep learning Linux, Cloud, Storage, DevOps, and IT technologies.