{"id":18947635,"url":"https://github.com/yousafkhamza/key-pair-rotation","last_synced_at":"2026-05-03T09:35:39.411Z","repository":{"id":195965550,"uuid":"375260326","full_name":"yousafkhamza/key-pair-rotation","owner":"yousafkhamza","description":"It's an ansible playbook for SSH-Keypair rotation. I write a short brief when we use this: if a customer using a key for which he used all instances in a single key pair. But he needs to change his key periodically with all the instances used in AWS (Also, change the key fingerprint in AWS Console).","archived":false,"fork":false,"pushed_at":"2021-07-11T09:08:59.000Z","size":23,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-01T01:19:58.188Z","etag":null,"topics":["ansible","aws","rotation","ssh"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yousafkhamza.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2021-06-09T07:09:37.000Z","updated_at":"2021-09-10T06:35:17.000Z","dependencies_parsed_at":"2023-09-20T20:13:39.516Z","dependency_job_id":null,"html_url":"https://github.com/yousafkhamza/key-pair-rotation","commit_stats":null,"previous_names":["yousafkhamza/key-pair-rotation"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2Fkey-pair-rotation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2Fkey-pair-rotation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2Fkey-pair-rotation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2Fkey-pair-rotation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yousafkhamza","download_url":"https://codeload.github.com/yousafkhamza/key-pair-rotation/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239946876,"owners_count":19723014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ansible","aws","rotation","ssh"],"created_at":"2024-11-08T13:10:49.066Z","updated_at":"2026-05-03T09:35:39.352Z","avatar_url":"https://github.com/yousafkhamza.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# SSH Key Rotation (AWS Cloud)\n[![Builds](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)\n\n---\n## Description \n\nIt's an ansible playbook for SSH-Keypair rotation. I write a short brief when we use this: if a customer using a key for which he used all instances in a single key pair. But he needs to change his key periodically with all the instances used in AWS (Also, change the key fingerprint in AWS Console).  \n\n---\n\n## Feature\n- Key pair Rotation easily applicable for multiple instances in single\n- Easy to configure and use.\n- No need to mention any hosts (Inventory) Because it's generated Dynamic Inventory appending your \u003cold_key.pem\u003e\n\n---\n## Pre-Requests \n- Install Ansible on your Master Machine (_localhost_)\n- Create an IAM user role under your AWS account and please enter the values once the playbook running time\n##### Installation\n[Ansible2](https://docs.ansible.com/ansible/2.3/index.html) (For your reference visit [How to install Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html))\n##### IAM Role Creation\n[IAM Role Creation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)\n##### Ansible Modules used\n- [ec2_instance_info](https://docs.ansible.com/ansible/latest/collections/community/aws/ec2_instance_info_module.html) \n- [ec2-key](https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_key_module.html)\n- [openssh_keypair](https://docs.ansible.com/ansible/latest/collections/community/crypto/openssh_keypair_module.html)\n- [authorized_key](https://docs.ansible.com/ansible/2.4/authorized_key_module.html)\n- [shell](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html)\n---\n\n# Architecture\n![alt text](https://i.ibb.co/4jPnV0C/rotation.jpg)\n\n---\n\n### How To Use\nAnsible Installation article is in the pre-request section so please check out the pre-request section.\n```sh\namazon-linux-extras install -y ansible2\nyum install git -y\ngit clone https://github.com/yousafkhamza/deploy-key.git\ncd deploy-key\n# --------------------------------------\n# --- Please-Change-Your-Credentials ---\n# --------------------------------------\nansible-playbook main.yml\n```\n---\n## Behind the Playbook.\nI just pasted the key.yml\n```sh\n- name: \"Generating Inventory Of Key To Be Rotated\"\n  hosts: localhost\n  vars_files:\n    - key.vars  \n  tasks:\n    \n    # ---------------------------------------------------------------\n    # Getting Information About Of Ec2's Which Need key To be Rotated\n    # ---------------------------------------------------------------\n    \n    - name: \"Fetching Detail About Ec2 Instance\"\n      ec2_instance_info:\n        aws_access_key: \"{{ access_key }}\"\n        aws_secret_key: \"{{ secret_key }}\"\n        region: \"ap-south-1\"\n        filters:\n          \"key-name\": \"{{ old_key }}\"\n          instance-state-name: [ \"running\"]\n      register: ec2\n    \n    \n    # ------------------------------------------------------------\n    # Creating Inventory Of Ec2  With Old Ssh-keyPair\n    # ------------------------------------------------------------    \n    - name: \"Creating Inventory \"\n      add_host:\n        name: \"{{ item.public_ip_address }}\"\n        groups: \"aws\"\n        ansible_host: \"{{ item.public_ip_address }}\"\n        ansible_port: 22\n        ansible_user: \"ec2-user\"\n        ansible_ssh_private_key_file: \"{{ old_key }}.pem\"\n        ansible_ssh_common_args: \"-o StrictHostKeyChecking=no\"\n      with_items:\n        - \"{{ ec2.instances }}\"\n      no_log: true     \n                             \n- name: \"Updating SshKey Meterial\"\n  hosts: aws\n  become: true\n  gather_facts: false\n  vars_files:\n    - key.vars\n  vars:\n    old_key: \"mumbai-production\"\n    tmp_key: \"keypair-tmp\"\n  tasks:\n    \n    - name: \"Creating New SSH-Kay Meterial\"\n      delegate_to: localhost\n      run_once: True\n      openssh_keypair:\n        path: \"{{ tmp_key }}\"\n        type: rsa\n        size: 4096\n        state: present\n        \n    - name: \"Adding New SshKey Meterial\"\n      authorized_key:\n       user: ec2-user\n       state: present\n       key: \"{{ lookup('file', '{{ tmp_key }}.pub')  }}\"\n        \n    - name: \"Creating Ssh Connection Command\"\n      set_fact:\n        ssh_connection: \"ssh -o StrictHostKeyChecking=no -i {{ tmp_key }} {{ansible_ssh_user}}@{{ ansible_ssh_host }} 'uptime'\" \n\n    - name: \"Checking Connectivity To Ec2 Using Newly Added Key\"\n      ignore_errors: true\n      delegate_to: localhost\n      shell: \"{{ ssh_connection }}\" \n    \n    - name: \"Removing Old KeyMeterial\"\n      authorized_key:\n       user: ec2-user\n       state: present\n       key: \"{{ lookup('file', '{{ tmp_key }}.pub')  }}\"\n       exclusive: true\n        \n    - name: \"Removing Old Ssh public From Aws Account \"\n      delegate_to: localhost\n      run_once: True\n      ec2_key:\n        aws_access_key: \"{{ access_key }}\"\n        aws_secret_key: \"{{ secret_key }}\"\n        region: \"{{ region }}\"\n        name: \"{{ old_key }}\"\n        key_material: \"{{ lookup('file', '{{ tmp_key }}.pub') }}\"\n        force: true\n        state: present\n            \n    - name: \"Renaming Local Pulbic Key\"\n      run_once: True\n      delegate_to: localhost\n      shell: \"mv {{  tmp_key }}.pub  {{ old_key }}.pub\"\n\n    - name: \"Renaming Local Private Key\" \n      run_once: True\n      delegate_to: localhost\n      shell: \"mv {{  tmp_key }}  {{ old_key }}.pem\"\n```\n\n\u003e key.vars are store variables actual values so Please change your values with the same and Please note that the key name doesn't need extension and please store the old key.pem file under the working directory\n\n```sh\naccess_key: \"Your access key\"\nsecret_key: \"\u003cYour secret key\u003e\"\nregion: \"\u003cregion which one you use\u003e\"       #----------\u003e Please let me know if you have using one key in multiple regions then I will help you to change the playbook. \nold_key: \"\u003cKeyName which you need to change\u003e\"   #----\u003e please past the old key name without pem extension and store private pem file on the same directory with 0400 permission\ntmp_key: \"keypair-tmp\"  \n```\n---\n\n# Conclusion\n\nIt's used for ssh key rotation on your AWS Cloud and which region and key you selected the playbook sort that key used instances and changed the SSH-Key inside the server and AWS Console at the same time\n\n\n### ⚙️ Connect with Me\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"mailto:yousaf.k.hamza@gmail.com\"\u003e\u003cimg src=\"https://img.shields.io/badge/Gmail-D14836?style=for-the-badge\u0026logo=gmail\u0026logoColor=white\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://www.linkedin.com/in/yousafkhamza\"\u003e\u003cimg src=\"https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge\u0026logo=linkedin\u0026logoColor=white\"/\u003e\u003c/a\u003e \n\u003ca href=\"https://www.instagram.com/yousafkhamza\"\u003e\u003cimg src=\"https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge\u0026logo=instagram\u0026logoColor=white\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://wa.me/%2B917736720639?text=This%20message%20from%20GitHub.\"\u003e\u003cimg src=\"https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge\u0026logo=whatsapp\u0026logoColor=white\"/\u003e\u003c/a\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousafkhamza%2Fkey-pair-rotation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyousafkhamza%2Fkey-pair-rotation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousafkhamza%2Fkey-pair-rotation/lists"}