Automate SSH Key Rotation With Ansible and Vault

Streamlining SSH Key Rotation with Ansible

Introduction:
SSH Key Rotation is a crucial security practice that involves managing Unix account private keys and passphrases. By regularly rotating SSH keys, you enhance your system’s security and protect against unauthorized access. This guide explores the use of Ansible, a powerful automation tool, to facilitate SSH Key Rotation for improved security and management.

Solution Overview:
Ansible provides a comprehensive set of features for managing SSH keys across multiple hosts. By leveraging Ansible’s authorized_key module, we can automate the process of generating new key pairs, distributing them to target hosts, and revoking old keys. This solution ensures seamless key rotation without disrupting system access.

Prerequisites:

  1. Preconfigured SSH keys on each target host.
  2. Ansible installed and running on your local machine.

Step-by-Step Guide:

  1. Prepare the Ansible Inventory:

    • Create an inventory file containing the target hosts’ details, including IP addresses and usernames.
    • Example inventory file:
      [centos]
      192.168.1.6 user=centos
      192.168.1.7 user=centos
      192.168.1.8 user=centos
      192.168.1.9 user=centos
      
  2. Generate a New SSH Key Pair:

    • Define an Ansible playbook to generate a new SSH key pair locally.
    • Execute the playbook to create the key pair.
    • Example playbook task:
      - name: Create new SSH key pair
        local_action: command ssh-keygen -t rsa -N "" -q -f ~/test/id_rsa
      
  3. Distribute the New Key to Target Hosts:

    • Configure an Ansible playbook task to push the newly generated public key to the target hosts.
    • Utilize the exclusive property to ensure the new key replaces the existing ones.
    • Execute the playbook to distribute the key.
    • Example playbook task:
      - name: Set up authorized_keys for the centos user
        authorized_key: user=centos key="{{ item }}" state=present exclusive=yes
        with_file:
          - ~/test/id_rsa.pub
      
  4. Archive the Old Key Pair:

    • Add playbook tasks to move the old key pair to a secure archive location.
    • Ensure the tasks are executed only once.
    • Example playbook tasks:
      - name: Move key pair
        local_action: command mv ~/test/id_rsa ~/test/id_rsa.bak
        run_once: true
      
      - name: Move key pair
        local_action: command mv ~/test/id_rsa.pub ~/test/id_rsa.pub.bak
        run_once: true
      

Conclusion:
By adopting Ansible for SSH Key Rotation, you can streamline the process of managing and updating SSH keys across multiple hosts. This automation-driven approach enhances security and simplifies key management, allowing for efficient and centralized control over SSH access.

Additional Resources:

GitLab Repository: https://gitlab.annexify.com/vmbs/ansible-lab
GitHub Repository: https://github.com/vmbs/Ansible-Lab