Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 29 ยท Projects

Project: Security Baseline Role

Write a reusable Ansible role that applies a security baseline: SSH settings, admin users and sudoers, unattended upgrades and auditing, with tags, check mode and defaults.

Every server you run should start from the same safe baseline: no password logins over SSH, no direct root login, named admin accounts, automatic security updates and an audit trail. Doing that by hand on each machine is slow and drifts over time. Doing it with a role means the baseline is written once, reviewed like code, and applied to every host the same way.

In this project you will build a role named baseline for Debian and Ubuntu servers. It uses variables with sensible defaults so teams can adjust it, tags so you can apply one part at a time, and check mode so you can see what would change first. You should know roles, handlers and tags and the hardening ideas from the security chapter. For the underlying Linux settings see Linux Hardening.

Hardening playbooks can lock you out of a server. Test on a disposable lab machine, keep a second SSH session open while you apply SSH changes, and make sure your key and user are in the allowed lists before turning password login off. The role below adds a safety check for that reason.

Ansible and real servers cannot run on this site, so the role files are read-only. The runnable examples are JavaScript stand-ins: one audits a configuration object against the baseline, the other models which tasks run for --tags and --skip-tags. They imitate the logic, not Ansible's code.

Role layout

TEXT
roles/baseline/
  defaults/main.yml
  handlers/main.yml
  tasks/main.yml
  tasks/ssh.yml
  tasks/users.yml
  tasks/updates.yml
  tasks/audit.yml
  templates/
    sshd_hardening.conf.j2
    audit.rules.j2
flowchart TD
  M["tasks/main.yml"] --> S["ssh.yml<br/>tags: ssh"]
  M --> U["users.yml<br/>tags: users"]
  M --> P["updates.yml<br/>tags: updates"]
  M --> A["audit.yml<br/>tags: audit"]
  D["defaults/main.yml<br/>(overridable settings)"] -.feeds.-> S
  D -.feeds.-> U
  D -.feeds.-> P
  D -.feeds.-> A

One role, four small task files, one set of defaults that callers can override from inventory.

Defaults: the knobs

Defaults rank lowest in variable precedence, so any playbook, group or host can override them. Name every variable with the role name as a prefix to avoid collisions with other roles.

YAML
# roles/baseline/defaults/main.yml
baseline_ssh_permit_root_login: "no"
baseline_ssh_password_authentication: "no"
baseline_ssh_max_auth_tries: 4
baseline_ssh_allow_users: []          # must be set by the caller
baseline_admin_users: []              # list of {name, ssh_key}
baseline_sudo_nopasswd: false
baseline_unattended_upgrades: true
baseline_audit_enabled: true
baseline_audit_watch_paths:
  - /etc/passwd
  - /etc/shadow
  - /etc/sudoers
  - /etc/ssh/sshd_config

Notice that baseline_ssh_allow_users defaults to an empty list. Forcing the caller to name the allowed users is safer than guessing.

The SSH part

A drop-in file is better than editing the main sshd_config with many lineinfile edits: it is one file you own completely. (On current Debian and Ubuntu releases the main file includes /etc/ssh/sshd_config.d/*.conf; check that yours does before relying on it.) Because the first value seen for a setting wins in sshd, drop-in files are read in alphabetical order, so a name that sorts early, such as 00-baseline.conf, is a good choice.

JINJA
# templates/sshd_hardening.conf.j2
# Managed by Ansible. Local edits will be overwritten.
PermitRootLogin {{ baseline_ssh_permit_root_login }}
PasswordAuthentication {{ baseline_ssh_password_authentication }}
MaxAuthTries {{ baseline_ssh_max_auth_tries }}
AllowUsers {{ baseline_ssh_allow_users | join(' ') }}
YAML
# roles/baseline/tasks/ssh.yml
- name: Refuse to lock everyone out
  ansible.builtin.assert:
    that:
      - baseline_ssh_allow_users | length > 0
      - baseline_admin_users | length > 0
    fail_msg: "Set baseline_ssh_allow_users and baseline_admin_users first."
  tags: [ssh]

- name: Install the hardening drop-in
  ansible.builtin.template:
    src: sshd_hardening.conf.j2
    dest: /etc/ssh/sshd_config.d/00-baseline.conf
    owner: root
    group: root
    mode: "0644"
    validate: "/usr/sbin/sshd -t -f %s"
  notify: reload sshd
  tags: [ssh]

Two safety nets are at work. The assert task stops the run before it writes anything dangerous. The validate option makes the module test the new file with sshd -t before installing it, so a typo never reaches the real location. (For a fragment, check on your system that sshd -t -f accepts the drop-in on its own; if it does not, validate with a handler that runs sshd -t on the whole configuration, as in Project: Provision a Web Server.) The handler lives in handlers/main.yml:

YAML
- name: reload sshd
  ansible.builtin.service:
    name: ssh
    state: reloaded

- name: reload auditd rules
  ansible.builtin.command: augenrules --load
  changed_when: true

On Debian and Ubuntu the service is called ssh; on Red Hat family systems it is sshd, so a role meant for both would set the name from a variable chosen by ansible_facts['os_family'].

Users and sudo

Named accounts make audit logs meaningful: you can see who did something, not just "root". The role creates each admin, installs their public key and grants sudo through a file in /etc/sudoers.d/, never by editing /etc/sudoers directly.

YAML
# roles/baseline/tasks/users.yml
- name: Create admin accounts
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: sudo
    append: true
    shell: /bin/bash
  loop: "{{ baseline_admin_users }}"
  loop_control:
    label: "{{ item.name }}"
  tags: [users]

- name: Install their SSH keys
  ansible.posix.authorized_key:
    user: "{{ item.name }}"
    key: "{{ item.ssh_key }}"
    exclusive: true
  loop: "{{ baseline_admin_users }}"
  loop_control:
    label: "{{ item.name }}"
  tags: [users]

- name: Install the sudo policy
  ansible.builtin.copy:
    dest: /etc/sudoers.d/90-baseline
    content: |
      %sudo ALL=(ALL:ALL) {{ 'NOPASSWD: ' if baseline_sudo_nopasswd else '' }}ALL
    owner: root
    group: root
    mode: "0440"
    validate: "/usr/sbin/visudo -cf %s"
  tags: [users, sudo]

loop_control.label keeps output short and avoids printing the whole key. exclusive: true removes keys that are not in the list, which is how you revoke access; use it only when the list is complete. The validate option with visudo -cf is not optional in spirit: a broken sudoers file can remove everyone's ability to become root.

Updates and auditing

YAML
# roles/baseline/tasks/updates.yml
- name: Install unattended-upgrades
  ansible.builtin.apt:
    name: unattended-upgrades
    state: present
  when: baseline_unattended_upgrades
  tags: [updates, packages]

- name: Turn on the daily update runs
  ansible.builtin.copy:
    dest: /etc/apt/apt.conf.d/20auto-upgrades
    content: |
      APT::Periodic::Update-Package-Lists "1";
      APT::Periodic::Unattended-Upgrade "1";
    mode: "0644"
  when: baseline_unattended_upgrades
  tags: [updates]
YAML
# roles/baseline/tasks/audit.yml
- name: Install auditd
  ansible.builtin.apt:
    name: auditd
    state: present
  when: baseline_audit_enabled
  tags: [audit, packages]

- name: Watch sensitive files
  ansible.builtin.template:
    src: audit.rules.j2
    dest: /etc/audit/rules.d/90-baseline.rules
    mode: "0640"
  when: baseline_audit_enabled
  notify: reload auditd rules
  tags: [audit]
JINJA
# templates/audit.rules.j2
{% for path in baseline_audit_watch_paths %}
-w {{ path }} -p wa -k baseline
{% endfor %}

Each line watches a path for writes and attribute changes (-p wa) and labels the events with the key baseline, so ausearch -k baseline finds them later. The role's entry point simply imports the four files:

YAML
# roles/baseline/tasks/main.yml
- ansible.builtin.import_tasks: ssh.yml
- ansible.builtin.import_tasks: users.yml
- ansible.builtin.import_tasks: updates.yml
- ansible.builtin.import_tasks: audit.yml

Using the role

YAML
# baseline.yml
- hosts: all
  become: true
  roles:
    - role: baseline
      vars:
        baseline_ssh_allow_users: [alice, bob]
        baseline_admin_users:
          - { name: alice, ssh_key: "ssh-ed25519 AAAA... [email protected]" }
          - { name: bob,   ssh_key: "ssh-ed25519 AAAA... [email protected]" }

In real projects the user list lives in group_vars/all.yml so the playbook stays tiny.

Tags and check mode

Tags on each task let you apply one concern at a time. Combine them with check mode and diff to review before changing anything:

Terminal
ansible-playbook baseline.yml --check --diff
ansible-playbook baseline.yml --tags ssh --check --diff
ansible-playbook baseline.yml --tags ssh
ansible-playbook baseline.yml --skip-tags packages

Check mode is only a prediction. Modules that run commands (the augenrules handler here) are skipped in check mode, and later tasks that depend on something an earlier task would have installed may report errors. Treat a clean check as a good sign, not a guarantee.

Stand-in: which tasks run for a tag selection

This model has six tasks, each with tags, and applies --tags and --skip-tags rules to them. It matches how selection works: a task runs when it has at least one requested tag (or none were requested) and none of the skipped tags.

JS Selecting tasks with --tags and --skip-tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(In real Ansible, tasks tagged always run unless skipped, and tags on an import_tasks line are inherited by the imported tasks. Neither is modelled here.)

Verifying the result

A baseline is only useful if you can prove it holds. Apart from running the playbook a second time and expecting changed=0, you can audit settings directly. On a real host, sshd -T prints the effective SSH configuration, and a lint pass over the role catches style errors (see Testing, Linting and Debugging).

Stand-in: auditing a configuration against the baseline

The baseline itself is just data: a list of expectations. This program checks three made-up servers against it and reports compliant, failing and missing values. The configuration objects stand in for what you would collect from real hosts (for example with sshd -T and package queries).

JS Audit servers against the baseline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real tools do the same job at scale, with ready-made rule sets from public security benchmarks. Treat any benchmark as input to your judgement, not a checklist to apply blindly, because some recommendations break legitimate workloads.

Extend the project

  • Add a firewall task file and a baseline_firewall_ports variable.
  • Support Red Hat family hosts with ansible_facts['os_family'] conditions and dnf-automatic.
  • Write a Molecule scenario that applies the role in a container and verifies the files (see Testing, Linting and Debugging).
  • Move the role into its own repository and install it with requirements.yml (see Collections, Galaxy and Reusable Content).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do role variables get a prefix such as baseline_?

    Role variables are not isolated; two roles using port would overwrite each other. A role-name prefix prevents that.
  2. 2. What does validate: "/usr/sbin/visudo -cf %s" do on the sudoers task?

    The module writes the content to a temporary file, runs the command on it (the %s) and installs it only if the command succeeds.
  3. 3. Which command applies only the SSH part and shows what would change, without changing it?

    --tags selects tasks, --check predicts without changing and --diff shows the file differences.
  4. 4. Why does baseline_ssh_allow_users default to an empty list plus an assert task?

    A hardening role must not guess identities. Requiring explicit users, and stopping if none are given, protects against a lock-out.
  5. 5. What does exclusive: true do for authorized_key?

    With exclusive, keys that are not in the task are removed, which revokes old access. Use it only when the list is complete.

Summary

  • A baseline role captures SSH, users, updates and auditing once and applies them everywhere.
  • Prefix variables with the role name, keep safe defaults in defaults/main.yml, and require callers to set risky values.
  • Use validate (sshd -t, visudo -cf) and an assert guard so mistakes never lock you out.
  • Tags and --check --diff let you review and apply one concern at a time; check mode is a prediction, not a guarantee.
  • Audit results as data: a baseline is a list of expectations you can test against.

Next: Project: Multi-Tier Stack with Roles and Vault.