Fetching a List of GitHub Users' SSH Keys and Adding Them to Authorized Hosts with Ansible

Fetching a List of GitHub Users' SSH Keys and Adding Them to Authorized Hosts with Ansible
Photo by Kyle Glenn / Unsplash

Introduction:

Automating the process of fetching a list of GitHub users' SSH keys and adding them to the authorized hosts file on your Linux servers can simplify user management.

In this tutorial, we will walk you through the steps to achieve this automation using Ansible.

Set Up Your Ansible Inventory

Ensure you have a working Ansible inventory file (inventory.ini) that lists the servers where you want to add the GitHub SSH keys. For example:

[web-servers]
server1 ansible_ssh_host=192.168.1.101 ansible_ssh_user=your_user ansible_ssh_private_key_file=/path/to/your/private/key
server2 ansible_ssh_host=192.168.1.102 ansible_ssh_user=your_user ansible_ssh_private_key_file=/path/to/your/private/key

Replace server1, server2, 192.168.1.101, 192.168.1.102, your_user, and /path/to/your/private/key with your server information.

Create an Ansible Playbook

Now, create an Ansible playbook to fetch GitHub SSH keys and add them to the authorized hosts file (~/.ssh/authorized_keys) for the specified users. Here's a sample playbook (github_ssh.yml):

---
- name: Fetch and Add GitHub Users' SSH Keys from a List
  hosts: web-servers
  tasks:
    - name: Fetch GitHub Users' SSH Keys
      uri:
        url: "https://api.github.com/{{ item }}.keys"
        method: GET
        return_content: yes
      with_items: "{{ github_usernames }}"
      register: github_keys

    - name: Add GitHub Users' SSH Keys to Authorized Hosts
      authorized_key:
        user: "{{ ansible_ssh_user }}"
        key: "{{ item.key }}"
      with_items: "{{ github_keys.results }}"

Create a Variable File

Create a variable file (e.g., github_users_vars.yml) to define the list of GitHub usernames you want to fetch SSH keys for:

---
github_usernames:
  - github_user1
  - github_user2
  - github_user3

Replace github_user1, github_user2, etc., with the GitHub usernames for which you want to fetch SSH keys.

Step 4: Run the Ansible Playbook

Execute the playbook to fetch SSH keys for the list of GitHub users and add them to the authorized hosts file on your target servers:

ansible-playbook -i inventory.ini github_users_list_ssh.yml -e "@github_users_vars.yml"

The -e flag specifies the variable file containing the list of GitHub usernames.

Conclusion:

By following this tutorial, you can automate the process of fetching SSH keys for a list of GitHub users and adding them to the authorized hosts of your Linux servers using Ansible.

This approach streamlines user management and ensures that multiple users can securely authenticate with your servers without manual intervention.

Remember to keep your GitHub token secure and follow best practices for managing access tokens.