Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Hardening as code with Ansible

After this lesson: I can write a hardening step as code and use it to find drift.

60 min lesson8 commandsLinux administration lab: users, permissions, cron and systemd in your browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Forty servers, one forgotten setting

Hardening as code means writing every hardening step in a file that a tool applies, instead of typing it on each server. The file can be reviewed, tested and run again.

A college hardens forty lab machines by hand from a checklist. Six weeks later, three have a setting back the old way and nobody knows which. Code would have found them in a minute. Work only on your own lab copy.

By the end of this lesson

Note

I can write a hardening step as code and use it to find drift.

Key words

WordWhat it meansExample
Playbookan Ansible file listing the tasks to apply to machines
Idempotentsafe to run again: a second run changes nothing
Check modea run that reports what would change and changes nothing--check
Drifta machine moving away from the state its code describes
Desired statewhat the code says the machine should be like

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Code describes a state, not keystrokes

A hardening script that types commands does them again every time. An Ansible task describes the desired state instead: this file has this content, this folder has this mode. Ansible compares and changes only what differs.

That makes it idempotent. Module 59 teaches Ansible itself; here it applies three hardening steps.

Install Ansible from Ubuntu's archive

Command
sudo apt-get install -y -qq --no-install-recommends ansible-core

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Which version is it?

Command
ansible --version | head -1

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the hardening playbook

Command
printf -- '- hosts: localhost\n  connection: local\n  become: true\n  gather_facts: false\n  tasks:\n    - name: Do not accept redirects\n      ansible.builtin.copy:\n        dest: /etc/sysctl.d/61-redirects.conf\n        content: "net.ipv4.conf.all.accept_redirects = 0\\n"\n        mode: "0644"\n    - name: Show a login banner\n      ansible.builtin.copy:\n        dest: /etc/issue.net\n        content: "Authorised use only.\\n"\n        mode: "0644"\n    - name: Only root reads monthly jobs\n      ansible.builtin.file:\n        path: /etc/cron.monthly\n        mode: "0700"\n' > harden.yml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Worked example: the three tasks

TaskModuleDesired state
Do not accept redirectscopyA sysctl file with the setting at 0
Show a login bannercopy/etc/issue.net says Authorised use only.
Only root reads monthly jobsfile/etc/cron.monthly has mode 0700

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Check mode first: what would change?

Command
ansible-playbook -i localhost, harden.yml --check

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Apply it

Command
ansible-playbook -i localhost, harden.yml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Apply it again

Command
ansible-playbook -i localhost, harden.yml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What did the three runs print?

Have a go

What did the three runs print?

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Check mode finds drift

Machines drift. Somebody loosens a mode to fix a problem at night and never puts it back. Run the playbook in check mode on a schedule and every drifted setting shows as changed.

Play the tired admin now: put one setting back by hand, then ask the code.

Undo one setting by hand

Command
sudo chmod 755 /etc/cron.monthly

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask the code what drifted

Command
ansible-playbook -i localhost, harden.yml --check

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think any script is hardening as code. A script of commands such as echo line >> file adds the line again each run, and cannot report drift. Describe the state, so a second run changes nothing.

Idempotence in a few lines

Code: python
desired = {"accept_redirects": "0", "banner": "Authorised use only.", "cron_monthly": "700"}
machine = {"accept_redirects": "1", "banner": "Ubuntu", "cron_monthly": "755"}

for run in [1, 2]:
    changed = 0
    for name in desired:
        if machine[name] != desired[name]:
            machine[name] = desired[name]
            changed = changed + 1
    print("run", run, "changed", changed)
# Set machine["cron_monthly"] = "755" between the runs. What does run 2 say?

Make a free account to save your work and track your progress.

Match each word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: plan and apply a desired state

desired and machine are dictionaries from a setting's name to its value. Write plan(desired, machine), which returns, in the order of desired, a list of [name, old, new] for every setting that is missing or different, using None as the old value of a missing one. Then write apply(desired, machine). It must not change machine: it returns a new dictionary with every setting of machine and the desired values put in, and the number of settings it changed, as a list [state, changed]. Applying twice must change nothing the second time.

Code: python
def plan(desired, machine):
    # Missing settings have None as their old value.
    return []


def apply(desired, machine):
    # Build a new dictionary; do not change machine itself.
    return [machine, 0]

Make a free account to save your work and track your progress.

Going further: from one machine to forty

The same playbook runs on forty machines with an inventory file listing them. Teams keep it in Git, so each change is reviewed. Ready-made roles exist for whole benchmarks; read one before trusting it, as you would any code.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.