Skip to main content
Ansible Configuration
CHAPTER 10

User Management and Security Automation

Updated: May 15, 2026
30 min read

# CHAPTER 10

User Management and Security Automation

1. Introduction

A compromised server is the nightmare of every systems administrator. If you manually create user accounts, manage SSH keys, and configure firewalls across a fleet of 500 servers, you will inevitably leave a backdoor open. A former employee's SSH key might remain active on a forgotten database, or a test port might be left exposed to the internet. Automation is not just about deploying applications; it is about enforcing absolute, auditable security baselines. In this chapter, we will use Ansible to automate user lifecycles, enforce SSH key authentication, configure sudo privileges, and lock down network perimeters using firewall automation.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Automate the creation and deletion of Linux user accounts (user module).
  • Securely distribute and revoke SSH public keys (authorizedkey module).
  • Configure precise administrative privileges using the lineinfile module for sudoers.
  • Automate Linux firewall rules utilizing the ufw or firewalld modules.
  • Enforce a standardized security baseline across a heterogeneous fleet.

3. Beginner-Friendly Explanation

Imagine running a high-security office building.
  • User Module (The HR Department): When someone is hired, HR creates an ID badge for them. When they are fired, HR destroys the badge.
  • AuthorizedKey Module (The Security Desk): Security programs the electronic door locks to only accept specific ID badges.
  • Firewall Module (The Perimeter Fence): The physical fence outside the building that ensures people can only enter through the front door (Port 80/443), and permanently blocks the back alley entrance (Port 22 from the public internet).

Ansible allows the "CEO" to update the security protocols for all 500 offices worldwide with a single keystroke.

4. Managing Users and SSH Keys

Creating users and distributing SSH keys is the foundation of secure access management.
yaml
12345678910111213141516171819202122232425262728
- name: Security Baseline - User Management
  hosts: all
  become: yes

  tasks:
    # 1. Create a new developer account
    - name: Ensure developer user exists
      user:
        name: jdoe
        state: present
        shell: /bin/bash
        groups: sudo      # Add them to the admin group
        append: yes

    # 2. Deploy their SSH Public Key (Passwordless login)
    - name: Set authorized SSH key for jdoe
      authorized_key:
        user: jdoe
        state: present
        # We pass the actual public key string
        key: "ssh-rsa AAAAB3NzaC1yc... jdoe@laptop"

    # 3. Offboarding an ex-employee instantly
    - name: Remove terminated employee access
      user:
        name: msmith
        state: absent    # Deletes the user account!
        remove: yes      # Deletes their home directory and files

5. Automating the Firewall (UFW)

A server should only expose the ports strictly necessary for its function. For Ubuntu/Debian servers, the Uncomplicated Firewall (ufw) is standard.
yaml
123456789101112131415161718192021222324
- name: Security Baseline - Firewall Configuration
  hosts: webservers
  become: yes

  tasks:
    # 1. Allow HTTP traffic (Public)
    - name: Allow HTTP (Port 80)
      ufw:
        rule: allow
        port: '80'
        proto: tcp

    # 2. Restrict SSH traffic to a specific Corporate IP!
    - name: Restrict SSH to Corporate VPN
      ufw:
        rule: allow
        port: '22'
        src: '192.168.100.0/24' # Only allow logins from this specific network

    # 3. Turn the firewall ON and block everything else
    - name: Enable UFW and deny all other incoming traffic
      ufw:
        state: enabled
        default: deny

6. Mini Project: Secure Sudoers Configuration

Sometimes we need to edit a highly sensitive configuration file, like /etc/sudoers, to allow a user to run specific admin commands without a password. We use the surgical lineinfile module.

Step-by-Step Architecture Concept: Let's allow the deploy_bot user to restart the Nginx service without a password, but NOTHING ELSE.

yaml
1234567891011121314151617181920212223
---
- name: Configure Secure Deployment Bot
  hosts: webservers
  become: yes

  tasks:
    - name: Create the deploy_bot user
      user:
        name: deploy_bot
        state: present

    # The lineinfile module surgically adds or replaces a single line of text in a file
    - name: Allow deploy_bot to restart Nginx without sudo password
      lineinfile:
        path: /etc/sudoers.d/deploy_bot # Safest place to put sudo rules
        state: present
        create: yes
        mode: '0440'
        # The specific sudoers syntax
        line: 'deploy_bot ALL=(ALL) NOPASSWD: /usr/sbin/service nginx restart'
        # Validation is critical! Visudo checks for syntax errors BEFORE saving.
        # If there is a syntax error, Ansible halts to prevent locking you out of the server.
        validate: /usr/sbin/visudo -cf %s 

7. Real-World Scenarios

A large retail company suffered a data breach. An attacker found an abandoned test server that still had the default admin/admin SSH password enabled. The CISO mandated a Zero-Trust architecture. The DevOps team wrote a "Security Hardening" Ansible Role. This role deleted default accounts, deployed strict SSH keys, disabled SSH password authentication entirely in the sshdconfig file, and locked down the firewall. This Role was attached to every single playbook in the company. Now, it is physically impossible for any engineer to deploy a server without it automatically inheriting the absolute highest standard of security.

8. Best Practices

  • Never Use Passwords: The user module allows you to pass a password: argument. You should almost never use this. Modern Linux environments should rely 100% on SSH Key authentication via the authorizedkey module. Passwords can be brute-forced; cryptographic keys cannot.

9. Security Recommendations

  • The validate Parameter: Modifying security files like /etc/sudoers or /etc/ssh/sshdconfig is extremely dangerous. A single typo will lock you out of your server permanently, requiring physical console access to fix. Always use the validate parameter in the lineinfile or template modules when touching these files. Ansible will run the validation command on a temporary copy of the file; if the command fails, Ansible aborts the task and does not overwrite your live configuration file.

10. Troubleshooting Tips

  • UFW Lockout: If you run an Ansible playbook that enables UFW (default: deny) but you forget to add a task that explicitly allows Port 22 (SSH), the moment UFW turns on, it will sever the Ansible SSH connection and lock you out of the server forever. ALWAYS put the SSH allow rule *before* the UFW enable task.

11. Exercises

  1. 1. What is the danger of editing the /etc/sudoers file without using the validate: /usr/sbin/visudo -cf %s argument?
  1. 2. Write a task using the authorizedkey module to remove an ex-employee's SSH key from a server.

12. FAQs

Q: How do I manage 50 different employee SSH keys using Ansible? A: Store the keys as variables in a YAML list (or fetch them from GitHub's API). Then, use a loop in your playbook to iterate over the list and feed them into the authorizedkey module automatically. (We will cover Loops in Chapter 17).

13. Interview Questions

  • Q: Describe how Ansible enforces infrastructure security through the automated offboarding of terminated employees. Which specific modules and arguments achieve this?
  • Q: Explain the operational purpose of the lineinfile module. In what specific security scenario is this module heavily preferred over deploying a full file via the template module?

14. Summary

In Chapter 10, we transformed Ansible from a deployment tool into a rigorous DevSecOps enforcer. We automated the complete lifecycle of Identity and Access Management, seamlessly provisioning users and enforcing passwordless, cryptographic authentication via the authorized
key module. We established strict network perimeters by orchestrating OS-level firewalls, ensuring the concept of Default Deny. Most importantly, we mastered the surgical lineinfile module with pre-flight validation, allowing us to safely modify hyper-sensitive security configurations without risking catastrophic server lockouts.

15. Next Chapter Recommendation

Our servers are secure, but modern applications are rarely installed directly onto the host OS anymore. They are packaged in containers. Proceed to Chapter 11: Ansible and Docker.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·