FALVARIX
FALVARIX
devops --real --no-hype

Ansible hardening for 50 Linux servers

Ansible hardening for 50 Linux servers

Ansible hardening for 50 Linux servers

It’s 2:00 AM. A security audit demands that all 50 production Linux servers have passwordless SSH, an active firewall and a hardened kernel. Do it by hand and you’re looking at a week of connections, copied commands and the certainty that server 37 got left half-done. With Ansible it takes a single command, and every one of the 50 machines ends up identical.

This article walks through how to set up that workflow in a real environment: project structure, provisioning roles, layered hardening, secrets management and verification. No textbook theory, just what actually works when you’ve got more than a handful of servers.

Why Ansible to provision and harden servers

Ansible needs no agents: it connects over SSH, runs modules and walks away. That makes it ideal for mixed fleets, where installing an agent on every host is friction nobody wants to take on.

Three properties make it the natural tool for hardening:

  • Idempotency: running the playbook ten times leaves the system exactly as running it once does. Only what falls outside your policy changes.
  • Declarative and readable: the YAML doubles as living documentation of your security policy.
  • Horizontal scale: parallel execution lets you touch dozens of hosts in minutes.

The “single command” part is literal:

ansible-playbook -i inventories/prod/hosts.yml site.yml --ask-vault-pass

Everything else is what’s behind that line.

Project structure: inventory and roles

A project that scales is organized from day one. Here’s a proven layout:

ansible/
├── ansible.cfg
├── site.yml
├── inventories/
│   ├── prod/
│   │   ├── hosts.yml
│   │   └── group_vars/
│   └── staging/
└── roles/
    ├── base/
    ├── ssh_hardening/
    ├── firewall/
    ├── sysctl_hardening/
    └── auditing/

Group-based inventory

Group by function, not by name. That way you apply different policies to databases, load balancers and application servers without duplicating code:

all:
  children:
    web:
      hosts:
        web[01:20].example.com:
    db:
      hosts:
        db[01:10].example.com:
    workers:
      hosts:
        wrk[01:20].example.com:
  vars:
    ansible_user: deploy
    ansible_python_interpreter: /usr/bin/python3

With ranges like web[01:20] you declare 50 servers in four lines. If your infrastructure is born in Terraform, generate the inventory dynamically from state; in our guide to Terraform with secure remote state you’ll see how to keep that source of truth tidy for the whole team.

One role, one responsibility

Each role does one thing and does it well. A ssh_hardening role shouldn’t touch sysctl. That separation lets you test, reuse and review changes without surprises. The site.yml stays as a clean index:

- hosts: all
  become: true
  roles:
    - base
    - ssh_hardening
    - firewall
    - sysctl_hardening
    - auditing

Phase 1: base provisioning

Before hardening, you have to level the field. The base role guarantees every server starts from the same point: essential packages, timezone, time sync, operations users and pending updates.

- name: Instalar paquetes base
  ansible.builtin.package:
    name: [chrony, curl, vim, unattended-upgrades, auditd]
    state: present

- name: Crear usuario de operaciones
  ansible.builtin.user:
    name: ops
    groups: sudo
    shell: /bin/bash
    state: present

- name: Desplegar clave pública autorizada
  ansible.posix.authorized_key:
    user: ops
    key: "{{ lookup('file', 'files/ops.pub') }}"

This phase kills the classic “works on my server” problem by eliminating drift between machines right from the start. Time sync with chrony may seem minor, but without consistent clocks your audit logs are useless in a forensic investigation.

Phase 2: layered hardening

Hardening isn’t a single action, it’s defense in depth. We apply it in layers, from the most exposed to the most internal.

Harden SSH

SSH is the front door and the first target of any automated attack. Use lineinfile with validation so a syntax error doesn’t lock you out of the machine:

- name: Configurar sshd de forma segura
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: "^#?{{ item.key }}"
    line: "{{ item.key }} {{ item.value }}"
    validate: "sshd -t -f %s"
  loop:
    - { key: PermitRootLogin, value: "no" }
    - { key: PasswordAuthentication, value: "no" }
    - { key: MaxAuthTries, value: "3" }
    - { key: X11Forwarding, value: "no" }
    - { key: ClientAliveInterval, value: "300" }
  notify: Reiniciar sshd

The validate parameter is your safety net: if the resulting config isn’t valid, Ansible aborts the change before restarting the service. If you want to go further and ditch static keys, see how Teleport enables audited SSH access with short-lived certificates.

Firewall and brute-force protection

Default policy: deny everything and open only what’s needed.

- name: Denegar tráfico entrante por defecto
  community.general.ufw:
    state: enabled
    policy: deny
    direction: incoming

- name: Permitir SSH y HTTPS
  community.general.ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  loop: ["22", "443"]

Pair the firewall with intrusion detection. Deploying Fail2ban from an Ansible role is trivial, and if you’re after custom jails and recidivism rules, you’ll find the details in advanced Fail2ban configuration on Linux.

Kernel, network and updates

The third layer tunes kernel parameters that reduce the network attack surface:

- name: Aplicar parámetros sysctl de seguridad
  ansible.posix.sysctl:
    name: "{{ item.name }}"
    value: "{{ item.value }}"
    sysctl_set: true
    reload: true
  loop:
    - { name: net.ipv4.conf.all.rp_filter, value: 1 }
    - { name: net.ipv4.tcp_syncookies, value: 1 }
    - { name: net.ipv4.conf.all.accept_redirects, value: 0 }
    - { name: kernel.randomize_va_space, value: 2 }

Also enable automatic security updates with unattended-upgrades (Debian/Ubuntu) or dnf-automatic (Red Hat family). A critical patch waiting for the monthly window is an open invitation.

For reference standards, CIS benchmarks are the usual starting point, and distributions like Ubuntu or Red Hat publish hardening guides you can translate straight into Ansible tasks.

Secrets: no plaintext passwords

A playbook managing 50 servers inevitably touches credentials: service passwords, tokens, private keys. Ansible Vault encrypts variables inside the repository:

ansible-vault encrypt_string 'S3cr3t0!' --name 'db_password'

That’s enough for small teams. As the platform grows, it’s worth centralizing secrets in a dedicated manager and fetching them at runtime with a lookup. In secrets management with OpenBao we explain how to get .env out of Git and serve credentials on demand, a pattern that fits Ansible perfectly.

Golden rule: the repository can be public without that being an incident. If it can’t, there’s something in plaintext that shouldn’t be.

Running at scale without breaking production

Pushing a change to 50 machines at once is efficient and, at the same time, risky. Ansible offers controls to pace the risk.

Dry run. Before touching anything, run:

ansible-playbook site.yml --check --diff

You’ll see what would change on each host, file diffs included.

Batched execution. The serial directive applies the playbook in waves and stops everything if something fails:

- hosts: all
  become: true
  serial: "20%"
  max_fail_percentage: 10

With 50 servers, the first wave hits 10 hosts. If the failure rate exceeds 10%, the rest stay untouched. It’s the equivalent of a canary deployment applied to configuration.

Parallelism. Tune forks in ansible.cfg (the default is 5). Raising it to 25 or 50 drastically cuts total time, as long as the control node can handle the load.

[defaults]
forks = 25
pipelining = True
host_key_checking = True

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

pipelining and ControlPersist cut SSH connections per task and shave minutes off long runs.

Verify the hardening actually works

A playbook that ends green doesn’t prove the system is secure, only that the tasks ran. Verify at three levels:

  1. Role testing with Molecule. Spin up containers or ephemeral VMs, apply the role and check idempotency: the second run should return changed=0.
  2. Linting in CI. ansible-lint catches bad practices before they reach production. Wire it into the pipeline for every pull request.
  3. Post-audit. Tools like OpenSCAP or Lynis score the server’s state against a security profile. Schedule them with Ansible and keep the reports.

If you already work with declarative flows, you can go further and version your whole infrastructure following the GitOps in production with ArgoCD approach, where the repository rules and every change is traceable.

Common mistakes to avoid

  • Restarting sshd without validating config. You lock yourself out of 50 servers at once. Always use validate and keep a session open during the test.
  • Mixing logic and data. Variables go in group_vars; roles contain only behavior.
  • Ignoring drift. If someone edits a server by hand, your policy stops being real. Run the playbook periodically (cron, AWX or a scheduled pipeline) to correct it.
  • Using shell and command for convenience. They break idempotency. Always prefer the specific module.
  • Hardening production without staging. A test environment with the same inventory saves you nasty surprises during business hours.

Conclusion: from manual chore to executable policy

Provisioning and hardening 50 servers with a single command isn’t magic: it’s discipline. Grouped inventories, small roles, validation before every change, secrets out of plaintext and continuous verification. Once it’s set up, adding server 51 or 500 costs the same as adding the first, and every audit goes from a headache to a query against the repository.

Your next step is practical: take a single staging group, write the ssh_hardening role, run it with --check --diff and watch. In an afternoon you’ll have the foundation of a system that keeps itself secure.

Keep reading