TExcelTAD
Home › Configuration Management: Ansible › Mini Project: A Hardening Role Tested with Molecule

Mini Project: A Hardening Role Tested with Molecule

In the linux-admin Mini Project you hardened a server by hand: SSH with keys only and no root login, a narrow sudo rule, kernel settings, fail2ban, a login banner. Now turn that work into a role that does it on every server, the same way, every time, and prove it with ansible-lint and a Molecule test.

The plan

# Piece Lessons
1 role skeleton, defaults, argument specs Roles, Role Defaults & Argument Specs
2 sshd drop-in from a template, validated Jinja2 Templates, Hardening the SSH Server
3 sudoers drop-in, validated with visudo sudo & sudoers
4 sysctl settings from a dictionary Loops
5 fail2ban jail and login banner fail2ban
6 handlers that reload services only when needed Handlers
7 lint, then Molecule: converge, idempotence, verify ansible-lint, Molecule

One design decision: a configurable root

On a real server the role writes to /etc as root and reloads services. The test in this sandbox has neither root nor systemd, so the role takes two inputs that make it testable anywhere:

Variable Real server Molecule test here
hardening_root / (default) /home/learner/target, a scratch folder
hardening_manage_services true: reload sshd, restart fail2ban, apply sysctl false
hardening_validate true: sshd -t, visudo -c on every rendered file false (the sandbox has neither binary)

The same idea is how many real roles are tested in containers: the parts that need a full machine are switched off by a variable, and covered by a separate VM-based scenario in CI.

The whole project in one session

The session writes the role and its Molecule scenario, lints the role, and runs molecule test:

bash · try it yourself
set -e
mkdir -p roles/hardening/{defaults,meta,tasks,handlers,templates,molecule/default}
cd roles/hardening

# --- defaults: every tunable, prefixed --------------------------------------------
cat > defaults/main.yml <<'YML'
---
hardening_root: /
hardening_manage_services: true
hardening_validate: true
hardening_ssh_port: 22
hardening_ssh_allow_groups: [ssh-users]
hardening_ssh_max_auth_tries: 3
hardening_sudo_group: ops
hardening_sudo_commands:
  - /usr/bin/systemctl restart linkly
  - /usr/bin/journalctl -u linkly
hardening_sysctl:
  net.ipv4.conf.all.rp_filter: 1
  net.ipv4.conf.all.accept_redirects: 0
  net.ipv4.conf.all.send_redirects: 0
  kernel.kptr_restrict: 2
  fs.protected_symlinks: 1
hardening_fail2ban_bantime: 1h
hardening_fail2ban_maxretry: 5
hardening_banner: "Authorized use only. Activity is logged."
YML

# --- argument specs: validated before any task runs -------------------------------
cat > meta/argument_specs.yml <<'YML'
---
argument_specs:
  main:
    short_description: Baseline SSH, sudo, sysctl and fail2ban hardening
    options:
      hardening_root: {type: path, default: /, description: Prefix for all managed files (tests only).}
      hardening_manage_services: {type: bool, default: true, description: Reload services and apply sysctl.}
      hardening_validate: {type: bool, default: true, description: Validate sshd and sudoers files before writing.}
      hardening_ssh_port: {type: int, default: 22, description: SSH port.}
      hardening_ssh_allow_groups: {type: list, elements: str, default: [ssh-users], description: Groups allowed to log in.}
      hardening_ssh_max_auth_tries: {type: int, default: 3, description: MaxAuthTries.}
      hardening_sudo_group: {type: str, default: ops, description: Group that gets the sudo rule.}
      hardening_sudo_commands: {type: list, elements: str, default: [], description: Commands the group may run as root.}
      hardening_sysctl: {type: dict, default: {}, description: Kernel parameters.}
      hardening_fail2ban_bantime: {type: str, default: 1h, description: fail2ban bantime.}
      hardening_fail2ban_maxretry: {type: int, default: 5, description: fail2ban maxretry.}
      hardening_banner: {type: str, default: "Authorized use only.", description: Login banner text.}
YML
cat > meta/main.yml <<'YML'
---
galaxy_info:
  namespace: acme
  role_name: hardening
  author: platform team
  description: Baseline server hardening
  license: MIT
  min_ansible_version: "2.18"
  platforms:
    - name: Ubuntu
      versions: [noble]
dependencies: []
YML

# --- templates ------------------------------------------------------------------------
cat > templates/10-hardening.conf.j2 <<'J2'
{{ ansible_managed | comment }}
Port {{ hardening_ssh_port }}
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries {{ hardening_ssh_max_auth_tries }}
AllowGroups {{ hardening_ssh_allow_groups | join(' ') }}
X11Forwarding no
Banner /etc/issue.net
J2
cat > templates/sudoers.j2 <<'J2'
{{ ansible_managed | comment }}
%{{ hardening_sudo_group }} ALL=(root) NOPASSWD: {{ hardening_sudo_commands | join(', ') }}
J2
cat > templates/jail.local.j2 <<'J2'
{{ ansible_managed | comment }}
[DEFAULT]
bantime = {{ hardening_fail2ban_bantime }}
maxretry = {{ hardening_fail2ban_maxretry }}

[sshd]
enabled = true
port = {{ hardening_ssh_port }}
J2

# --- tasks --------------------------------------------------------------------------
cat > tasks/main.yml <<'YML'
---
- name: Config directories exist
  ansible.builtin.file:
    path: "{{ hardening_root }}/etc/{{ item }}"
    state: directory
    mode: "0755"
  loop: [ssh/sshd_config.d, sudoers.d, sysctl.d, fail2ban]

- name: SSH hardening drop-in
  ansible.builtin.template:
    src: 10-hardening.conf.j2
    dest: "{{ hardening_root }}/etc/ssh/sshd_config.d/10-hardening.conf"
    mode: "0600"
    validate: "{{ '/usr/sbin/sshd -t -f %s' if hardening_validate else omit }}"
  notify: Reload sshd

- name: Sudo rule for the ops group
  ansible.builtin.template:
    src: sudoers.j2
    dest: "{{ hardening_root }}/etc/sudoers.d/50-{{ hardening_sudo_group }}"
    mode: "0440"
    validate: "{{ '/usr/sbin/visudo -cf %s' if hardening_validate else omit }}"

- name: Kernel parameters
  ansible.builtin.lineinfile:
    path: "{{ hardening_root }}/etc/sysctl.d/90-hardening.conf"
    regexp: "^{{ item.key | regex_escape }} ="
    line: "{{ item.key }} = {{ item.value }}"
    create: true
    mode: "0644"
  loop: "{{ hardening_sysctl | dict2items }}"
  loop_control:
    label: "{{ item.key }}"
  notify: Apply sysctl

- name: Fail2ban jail
  ansible.builtin.template:
    src: jail.local.j2
    dest: "{{ hardening_root }}/etc/fail2ban/jail.local"
    mode: "0644"
  notify: Restart fail2ban

- name: Login banner
  ansible.builtin.copy:
    dest: "{{ hardening_root }}/etc/issue.net"
    content: "{{ hardening_banner }}\n"
    mode: "0644"
YML

# --- handlers: only on real servers -------------------------------------------------
cat > handlers/main.yml <<'YML'
---
- name: Reload sshd
  ansible.builtin.systemd_service:
    name: ssh
    state: reloaded
  when: hardening_manage_services | bool

- name: Apply sysctl
  ansible.builtin.command: sysctl --system
  changed_when: true
  when: hardening_manage_services | bool

- name: Restart fail2ban
  ansible.builtin.systemd_service:
    name: fail2ban
    state: restarted
  when: hardening_manage_services | bool
YML

# --- Molecule scenario: delegated driver against localhost ---------------------------
cat > molecule/default/molecule.yml <<'YML'
---
driver:
  name: default
  options:
    managed: false
platforms:
  - name: instance
ansible:
  env:
    ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/..
  cfg:
    defaults:
      interpreter_python: auto_silent
  executor:
    args:
      ansible_playbook:
        - --inventory=${MOLECULE_SCENARIO_DIRECTORY}/inventory.yml
dependency:
  name: galaxy
  enabled: false
scenario:
  test_sequence: [syntax, converge, idempotence, verify]
YML
cat > molecule/default/inventory.yml <<'YML'
---
all:
  hosts:
    instance:
      ansible_connection: local
  vars:
    hardening_root: /home/learner/target
    hardening_manage_services: false
    hardening_validate: false
YML
cat > molecule/default/converge.yml <<'YML'
---
- name: Converge
  hosts: all
  gather_facts: false
  roles:
    - role: hardening
YML
cat > molecule/default/verify.yml <<'YML'
---
- name: Verify
  hosts: all
  gather_facts: false
  vars:
    etc: "{{ hardening_root }}/etc"
  tasks:
    - name: Read the sshd drop-in
      ansible.builtin.slurp:
        src: "{{ etc }}/ssh/sshd_config.d/10-hardening.conf"
      register: sshd

    - name: SSH accepts keys only, no root, limited groups
      ansible.builtin.assert:
        that:
          - "'PermitRootLogin no' in sshd_text"
          - "'PasswordAuthentication no' in sshd_text"
          - "'AllowGroups ssh-users' in sshd_text"
        quiet: true
      vars:
        sshd_text: "{{ sshd.content | b64decode }}"

    - name: Stat the sudoers drop-in
      ansible.builtin.stat:
        path: "{{ etc }}/sudoers.d/50-ops"
      register: sudoers

    - name: Sudoers file is 0440, as sudo requires
      ansible.builtin.assert:
        that: sudoers.stat.mode == "0440"
        quiet: true

    - name: Read the sysctl drop-in
      ansible.builtin.slurp:
        src: "{{ etc }}/sysctl.d/90-hardening.conf"
      register: sysctl

    - name: Redirects are off
      ansible.builtin.assert:
        that: "'net.ipv4.conf.all.accept_redirects = 0' in (sysctl.content | b64decode)"
        quiet: true
YML

# --- lint config: the strictest profile; Molecule's inventory is not a playbook ---------
cat > .ansible-lint <<'YML'
---
profile: production
exclude_paths:
  - molecule/default/inventory.yml
YML

echo "=== ansible-lint"
ANSIBLE_ROLES_PATH=.. ansible-lint >/dev/null 2>&1 && echo "lint: passed (production profile)"
echo "=== molecule test"
PY_COLORS=0 molecule test 2>&1 | grep -E '^(INFO|ERROR|CRITICAL) |^instance |^default '
echo "=== what the role wrote"
cd /home/learner/target && find . -type f | sort
cat etc/ssh/sshd_config.d/10-hardening.conf
=== ansible-lint
lint: passed (production profile)
=== molecule test
INFO     [default > discovery] scenario test matrix: syntax, converge, idempotence, verify
INFO     [default > prerun] Performing prerun with role_name_check=0...
INFO     [default > syntax] Executing
INFO     [default > syntax] Executed: Successful
INFO     [default > converge] Executing
instance                   : ok=7    changed=6    unreachable=0    failed=0    skipped=3    rescued=0    ignored=0
INFO     [default > converge] Executed: Successful
INFO     [default > idempotence] Executing
instance                   : ok=7    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
INFO     [default > idempotence] Executed: Successful
INFO     [default > verify] Executing
instance                   : ok=6    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
INFO     [default > verify] Executed: Successful
INFO     Molecule executed 1 scenario (1 successful)
default > syntax: Executed: Successful
default > converge: Executed: Successful
default > idempotence: Executed: Successful
default > verify: Executed: Successful
default                   : actions=4  successful=4  disabled=0  skipped=0  missing=0  failed=0
=== what the role wrote
./etc/fail2ban/jail.local
./etc/issue.net
./etc/ssh/sshd_config.d/10-hardening.conf
./etc/sudoers.d/50-ops
./etc/sysctl.d/90-hardening.conf
#
# Ansible managed
#
Port 22
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
AllowGroups ssh-users
X11Forwarding no
Banner /etc/issue.net

What the run proves:

  • ansible-lint passes at the strictest production profile: FQCNs, names, quoted modes, changed_when on the command handler.
  • converge wrote every file (changed=6: four directories as one looped task, five templates and edits; the three handlers were notified but skipped, because hardening_manage_services is false).
  • idempotence: the second converge changed nothing, so on a real server the handlers stay quiet on every later run.
  • verify: the assertions about the result hold.

On a real server

The playbook that uses the role in production (a sample session; it needs SSH, sudo and systemd):

yaml
# site.yml
- name: Harden all servers
  hosts: all
  become: true
  serial: "25%"
  max_fail_percentage: 0
  roles:
    - role: hardening
      vars:
        hardening_ssh_allow_groups: [ssh-users, ops]
bash
$ ansible-playbook -i inventories/staging site.yml --limit web1 --check --diff   # read the plan
$ ansible-playbook -i inventories/staging site.yml --limit web1                  # canary
$ ssh web1 sudo -l                                                              # new terminal: still in?
$ ansible-playbook -i inventories/staging site.yml                              # the rest, 25% at a time
...
RUNNING HANDLER [hardening : Reload sshd] **************************************
changed: [web2]
changed: [web3]
...
PLAY RECAP *********************************************************************
web1                       : ok=7    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=10   changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

With hardening_validate: true (the default), a typo in a variable that would break sshd_config or sudoers fails the task before the file is replaced, so the reload never runs on a broken config.

Extend it

  1. Add a second Molecule scenario molecule/vm/ that uses a Vagrant or cloud VM with hardening_root: /, services and validation on, and run it in CI nightly.
  2. Add the firewall from the linux-admin project with community.general.ufw (allow SSH from the admin network before setting the default policy to deny), behind hardening_manage_firewall.
  3. Install the packages (fail2ban, unattended-upgrades) in a task guarded by hardening_manage_services, and add a package_facts-based check to verify.
  4. Package the role in a collection (acme.platform.hardening) with a galaxy.yml and publish it to your private Automation Hub (Collections).

Test yourself

Why does the role take a hardening_root variable?

  1. To run on Windows
  2. So the same role can be tested without root by writing into a scratch folder
  3. To speed up runs
  4. Because /etc is read-only on Ubuntu

What would Molecule's idempotence stage catch in this role?

  1. A wrong sysctl value
  2. Any task that reports changed on the second converge, e.g. a command without changed_when
  3. Lint errors
  4. A missing SSH key

Why validate the sshd and sudoers templates on real servers?

  1. Ansible requires validate on templates
  2. A broken file is never installed, so a typo can't lock you out
  3. It speeds up the reload
  4. It encrypts the files