Automate the process of granting / revoking SSH access to a group of servers
instances to a new developer
Automating the process of granting or revoking SSH access to a group of server instances for a new
developer can be streamlined using tools like Ansible, which is well-suited for managing
configurations across multiple servers. Below is an example approach to achieve this:
Prerequisites:
1. Ansible Installed: Make sure you have Ansible installed on your control machine.
2. SSH Access: Ensure that the control machine has SSH access to the servers where you need
to manage access.
3. Inventory File: Create an inventory file listing the group of servers.
4. Public SSH Key: You should have the new developer’s public SSH key.
Step-by-Step Automation with Ansible
1. Create an Ansible Inventory File
Create a file called hosts.ini:
[web_servers]
192.168.1.101
192.168.1.102
[db_servers]
192.168.1.201
192.168.1.202
This file lists all the servers where you want to manage SSH access. You can group them based on
roles like web_servers or db_servers.
2. Ansible Playbook for Granting SSH Access
Create a playbook called grant_ssh_access.yml:
---
- name: Grant SSH access to new developer
hosts: all
become: yes
vars:
developer_user: "new_developer"
developer_ssh_key: "ssh-rsa AAAAB3NzaC1yc2EAAAABIw..."
tasks:
- name: Create developer user if not exists
user:
name: "{{ developer_user }}"
state: present
shell: /bin/bash
create_home: yes
- name: Create .ssh directory
file:
path: "/home/{{ developer_user }}/.ssh"
state: directory
owner: "{{ developer_user }}"
mode: 0700
- name: Add developer's SSH key
authorized_key:
user: "{{ developer_user }}"
key: "{{ developer_ssh_key }}"
state: present
manage_dir: no
3. Run the Playbook
Use the following command to run the playbook and grant SSH access:
ansible-playbook -i hosts.ini grant_ssh_access.yml
Explanation of the Playbook:
1. User Module: Ensures the new developer's account is created.
2. File Module: Creates the .ssh directory with the correct permissions if it doesn’t exist.
3. Authorized Key Module: Adds the new developer’s public SSH key to
~/.ssh/authorized_keys.
4. Ansible Playbook for Revoking SSH Access
Create a playbook called revoke_ssh_access.yml:
---
- name: Revoke SSH access for developer
hosts: all
become: yes
vars:
developer_user: "new_developer"
developer_ssh_key: "ssh-rsa AAAAB3NzaC1yc2EAAAABIw..."
tasks:
- name: Remove developer's SSH key
authorized_key:
user: "{{ developer_user }}"
key: "{{ developer_ssh_key }}"
state: absent
manage_dir: no
- name: Remove developer user
user:
name: "{{ developer_user }}"
state: absent
remove: yes
5. Run the Revoke Playbook
To revoke SSH access and delete the user:
ansible-playbook -i hosts.ini revoke_ssh_access.yml
Explanation of the Revoke Playbook:
1. Authorized Key Module: Removes the specified SSH key from
~/.ssh/authorized_keys.
2. User Module: Deletes the user account, including the home directory, with the remove:
yes option.
k