Throughout the course, lesson after lesson, you've been noting down security issues "for Lesson 9.2": the servers' SSH accepts passwords, the team users don't have their keys managed, sudo hasn't been reviewed, nginx advertises its version, Docker publishes ports ahead of the firewall, Ansible deploys to Kubernetes with a cluster administrator identity, the CI runner runs jobs directly on awx1… The time has come to settle them. In this lesson you'll review Aurora Store's security with a common set of criteria (least privilege, everything in code, always verify) and apply the changes with Ansible: SSH hardening with a template and validation, team keys and passwords, sudo rules validated with visudo, an automation account, verified host keys, nginx without its version, Docker without accidental exposure, a limited deployment account in Kubernetes, and a policy for the Vault, CI and cloud secrets. You'll also see how to protect the supply chain of your automation.
Warning. This lesson applies widely accepted best practices, but security depends on each organization, its regulations and its risks. Before applying any of these configurations to real systems, have them reviewed by a security professional. The example values (networks, users, keys) are fictitious.
Contents
- Aurora Store's risk inventory
- Principles that guide the changes
- Hardened SSH with a template and validation
- Team keys and passwords
- Minimal
sudoand the automation account - Host keys: verifying who you connect to
- nginx without its version:
ansible-role-nginx1.1.0 - Docker: the
dockergroup, ports and the registry - Kubernetes: a deployment account instead of the administrator
- CI: the runner and secrets
- The cloud: a minimal IAM policy
- Vault: identities, rotation,
no_logand external managers - The supply chain
- The lab's security debt
- Aurora Store's risk inventory
Before changing anything, it's worth gathering everything that's pending in a table. It's the same exercise an auditor would do: what the risk is, where it appeared and what will be done about it.
| Risk | Origin | What this lesson does |
|---|---|---|
SSH accepts passwords and root |
Default configuration (Lesson 2.5) | Hardened sshd template in the common role (section 3) |
Team users without managed keys or a password for sudo |
Lessons 3.6 and 5.3 | Exclusive authorized_key and hashed passwords (section 4) |
sudo not reviewed; Ansible logs in as vagrant with full sudo |
Lessons 2.4 and 3.6 | Validated rules and an automation account (section 5) |
| Host keys accepted without verification on AWS and disabled in AWX | Lessons 7.5 and 8.4 | Managed known_hosts (section 6) |
nginx shows its version (Server: nginx/1.24.0 (Ubuntu)) |
Lesson 5.2 | server_tokens off (section 7) |
docker group = root; Docker ports bypass ufw; registry without TLS |
Lesson 8.1 | Section 8 |
Cluster administrator kubeconfig used for deployments |
Lesson 8.2 | Limited service account (section 9) |
Runner in host mode on awx1; CI secrets |
Lesson 8.3 | Section 10 |
| IAM user with broad permissions | Lesson 8.4 | Minimal policy (section 11) |
| Secret rotation, external managers | Lesson 5.4 | Section 12 |
| Third-party content (roles, collections, images, actions) | Lessons 6.1 and 8.3 | Section 13 |
node_exporter on 127.0.0.1:9100, AWX and Gitea over HTTP |
Lessons 6.2 and 7.2 | Documented debt (section 14) |
- Principles that guide the changes
- Least privilege. Each person, account or process has only the permissions it needs, and only in the environments where it needs them. Applied to Ansible:
becomewhere necessary,become_userto an unprivileged user when that's enough (likepostgres), and separate accounts for people and for automation. - Defense in depth. No measure is enough on its own: SSH with keys only and a firewall and limited users.
- Everything in code. A security measure applied by hand is lost at the next reinstallation; in a role, it's applied on every server and in every environment, and it's reviewed in a pull request.
- Verify, don't assume. Every change is checked (with
sshd -T,visudo -c,curl -I…) and, better still, with automated tests (Lesson 9.5). - Don't lock yourself out. Access changes can saw off the branch you're sitting on. That's why they're applied with prior validation, first to a single host (
--limit web2) and with a backup session open.
- Hardened SSH with a template and validation
3.1. Why a file in sshd_config.d/
In Lesson 2.5 you tried lineinfile on /etc/ssh/sshd_config in check mode, and doing it properly was left pending. There are three ways to manage the SSH configuration:
| Option | Advantage | Drawback |
|---|---|---|
lineinfile on sshd_config |
Minimal change | Fragile: depends on the original content and on commented-out lines |
Template for the whole sshd_config |
Full control | Replaces the distribution's file; package updates no longer improve it |
Template in /etc/ssh/sshd_config.d/ |
A file of your own, the original untouched | You need to know the "first value wins" rule |
Ubuntu (20.04 or later) includes the line Include /etc/ssh/sshd_config.d/*.conf at the beginning of /etc/ssh/sshd_config, and sshd keeps the first value it finds for each option. A file called 00-common.conf is read before any other file in that directory (for example, the 50-cloud-init.conf that some cloud images ship with PasswordAuthentication yes) and before the rest of sshd_config. Aurora uses this option.
3.2. Variables and template
In roles/common/defaults/main.yml:
# SSH access (Lesson 9.2)
common_ssh_permit_root_login: "no" # in quotes: without them, YAML would read it as false
common_ssh_password_authentication: false
common_ssh_max_auth_tries: 3
common_ssh_allow_groups: [] # empty = no restriction by groupNotice the quotes around "no": it's the YAML 1.1 booleans problem from Lesson 3.2. Without them, the variable would be false and the template would write PermitRootLogin False, which sshd rejects.
In roles/common/vars/main.yml (fixed paths for the Debian family):
common_sshd_binary: /usr/sbin/sshd
common_sshd_dropin: /etc/ssh/sshd_config.d/00-common.conf
common_ssh_service: sshroles/common/templates/sshd.conf.j2:
# {{ ansible_managed }}
# SSH hardening (common role). sshd uses the FIRST value it finds for each
# option: this file is included at the beginning of sshd_config and wins over the others.
PermitRootLogin {{ common_ssh_permit_root_login }}
PasswordAuthentication {{ 'yes' if common_ssh_password_authentication else 'no' }}
KbdInteractiveAuthentication no
PermitEmptyPasswords no
PubkeyAuthentication yes
X11Forwarding no
MaxAuthTries {{ common_ssh_max_auth_tries }}
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
{% if common_ssh_allow_groups | length > 0 %}
AllowGroups {{ common_ssh_allow_groups | join(' ') }}
{% endif %}| Directive | Effect |
|---|---|
PermitRootLogin no |
Nobody logs in directly as root; you log in with a user and escalate with sudo (which records who did it) |
PasswordAuthentication no, KbdInteractiveAuthentication no |
Keys only: eliminates brute-force attacks against passwords |
MaxAuthTries 3 |
Drops the connection after 3 authentication attempts |
LoginGraceTime 30 |
30 seconds to authenticate |
ClientAliveInterval/CountMax |
Closes idle or hung sessions (about 10 minutes) |
X11Forwarding no |
Disables a feature a server doesn't need |
AllowGroups |
Allowlist of groups that can log in; powerful but dangerous: if you forget the Ansible user's group, you lock yourself out |
3.3. Task with validation and a handler
In roles/common/tasks/main.yml, a new block at the end:
- name: Access hardening
tags:
- config
- security
block:
- name: Publish the sudo rules
ansible.builtin.template:
src: sudoers.j2
dest: "{{ common_sudoers_file }}"
owner: root
group: root
mode: "0440"
validate: /usr/sbin/visudo -cf %s
- name: Publish the hardened SSH configuration
ansible.builtin.template:
src: sshd.conf.j2
dest: "{{ common_sshd_dropin }}"
owner: root
group: root
mode: "0644"
validate: "{{ common_sshd_binary }} -t -f %s"
notify: Reload SSH(The sudo task is explained in section 5.) The common role had no handlers; create roles/common/handlers/main.yml with the same pattern you used for nginx in Lesson 5.1:
---
- name: Validate the full SSH configuration
ansible.builtin.command:
cmd: "{{ common_sshd_binary }} -t"
changed_when: false
listen: Reload SSH
- name: Apply the SSH reload
ansible.builtin.systemd_service:
name: "{{ common_ssh_service }}"
state: reloaded
listen: Reload SSHTwo validations, with different purposes:
validate: sshd -t -f %schecks the new file before copying it into place. If it has a syntax error, the task fails and the file isn't installed.- The
sshd -thandler checks the full configuration (sshd_configplus all the.d/*.conffiles) before reloading. If the combination is invalid, the reload doesn't happen and the service keeps the previous configuration.
Reloading (reloaded) doesn't drop open sessions: sshd only applies the new configuration to new connections. The new functional tag security lets you apply only the hardening (--tags security).
3.4. Applying it without locking yourself out
ansible-playbook playbooks/common.yml --tags security --check --diff --limit web2
ansible-playbook playbooks/common.yml --tags security --limit web2
ssh web2 true && echo "I can still log in with my key"
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password web2 trueThe last command must fail with Permission denied (publickey).: the server no longer offers password authentication. Check the effective configuration (the one resulting from combining all the files):
ansible --playbook-dir playbooks web2 -b -m ansible.builtin.command -a "sshd -T" | grep -Ei '^(permitrootlogin|passwordauthentication|maxauthtries)'Then do the rest: ansible-playbook playbooks/common.yml --tags security. If something went wrong and you couldn't log in over SSH, in the lab you have the VirtualBox console or vagrant ssh (which uses its own key); in the cloud, the provider's serial console. Always have an emergency access route ready before touching SSH in production.
- Team keys and passwords
4.1. Public keys with ansible.posix.authorized_key
The users laura and marc have existed since Lesson 3.6, but they can't log in: they have no keys. Each person generates their key pair on their own computer and hands over only the public key (it isn't a secret). To practice, simulate your colleagues' keys:
ssh-keygen -t ed25519 -N '' -C [email protected] -f ~/.ssh/aurora_laura
ssh-keygen -t ed25519 -N '' -C [email protected] -f ~/.ssh/aurora_marc
cat ~/.ssh/aurora_laura.pub ~/.ssh/aurora_marc.pubThe public keys are added to the team definition, playbooks/group_vars/all/team.yml, in a new ssh_keys field (a list: a person can have several computers):
---
# Aurora Store team (the same in every environment).
common_users:
- name: deploy
comment: Aurora Store deployments
- name: laura
comment: Laura Gómez - Development
# Administrator in lab and staging; in production, without privileges.
admin: "{{ aurora_env != 'production' }}"
password_hash: "{{ vault_common_password_hashes['laura'] }}"
ssh_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... [email protected]
- name: marc
comment: Marc Soler - Operations
admin: true
password_hash: "{{ vault_common_password_hashes['marc'] }}"
ssh_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... [email protected]
- name: jordi
comment: Former contributor
state: absent(Paste your full keys where the ellipses are.) In the "Team users" block of roles/common/tasks/main.yml, after "Manage the team users":
- name: Authorize the SSH keys of the team users
ansible.posix.authorized_key:
user: "{{ item.name }}"
key: '{{ item.ssh_keys | join("\n") }}'
exclusive: true
state: present
loop: "{{ common_users }}"
loop_control:
label: "{{ item.name }}"
when:
- item.ssh_keys is defined
- item.state | default('present') == 'present'keyaccepts several keys separated by newlines;join("\n")joins them. YAML single quotes pass\nthrough to Jinja as is, and Jinja turns it into a newline.exclusive: truemakesauthorized_keyscontain exactly those keys: if someone adds one by hand, or a person changes laptops and removes the old key from the repository, Ansible deletes the extra ones. This is what turns the repository into the source of truth for who can log in.- Users without
ssh_keys(likedeploy) aren't touched.
Be careful with
exclusiveand the Ansible account. Never manage the keys of the user Ansible connects with (here,vagrant) withexclusive: truefrom a list that might be incomplete: if the key in use is missing, the next connection will fail.
4.2. Passwords for sudo, hashed
An administrator needs a password to use sudo (Ubuntu's rule for the sudo group asks for it). But the password must never be in the repository, not even encrypted: what's stored is its hash, and in Vault, because a leaked hash allows unlimited dictionary attacks. The procedure:
- Each person generates the hash of their password on their own computer and hands it over (the password never leaves their head):
-6 produces a salted SHA-512 hash ($6$...), the /etc/shadow format.
- Operations stores it in each environment's vault, in a dictionary:
(Repeat in staging/vault.yml and production/vault.yml; ideally each person uses different passwords per environment.)
- The "Manage the team users" task applies the hash and stops showing its data:
- name: Manage the team users
ansible.builtin.user:
name: "{{ item.name }}"
comment: "{{ item.comment | default(omit) }}"
shell: /bin/bash
password: "{{ item.password_hash | default(omit) }}"
state: "{{ item.state | default('present') }}"
loop: "{{ common_users }}"
loop_control:
label: "{{ item.name }}"
no_log: trueThe module compares the hash with the one in /etc/shadow and only changes it if they differ (it's idempotent). With the default behavior (update_password: always), the vault is in charge: to change a password, you change the hash in the vault. no_log: true prevents the hashes from appearing with -v; the price is that, if the task fails, the message is hidden (to diagnose it, remove it temporarily on your computer, never in the CI or in AWX).
4.3. Administration per environment
Laura is an administrator in the lab and in staging, but not in production: admin: "{{ aurora_env != 'production' }}". For that to work, the role needs two adjustments:
- The condition must convert the template result to a boolean:
item.admin | default(false) | bool. - Remove privileges from those who already had them.
groups+append: trueadds, but never removes:
- name: Grant administrator privileges to the team admins
ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ common_sudo_group }}"
append: true
loop: "{{ common_users }}"
loop_control:
label: "{{ item.name }}"
when:
- item.admin | default(false) | bool
- item.state | default('present') == 'present'
- name: Get the members of the administration group
ansible.builtin.getent:
database: group
key: "{{ common_sudo_group }}"
- name: Revoke administrator privileges from those who no longer have them
ansible.builtin.command:
cmd: "gpasswd -d {{ item.name }} {{ common_sudo_group }}"
loop: "{{ common_users }}"
loop_control:
label: "{{ item.name }}"
when:
- not (item.admin | default(false) | bool)
- item.name in ansible_facts['getent_group'][common_sudo_group][2].split(',')
changed_when: truegetent leaves in ansible_facts['getent_group']['sudo'] a list [password, GID, "member1,member2"]; the third position holds the members. The task only runs (and only reports a change) when there's someone who shouldn't be there.
Add the new fields to common_users.options in roles/common/meta/argument_specs.yml:
password_hash:
type: str
description: Password hash (/etc/shadow format). It must come from Vault.
ssh_keys:
type: list
elements: str
description: Authorized SSH public keys (exclusive management).
- Minimal
sudo and the automation account
sudo and the automation account5.1. What Ansible really needs
It's worth being honest about a limitation: Ansible escalates privileges by running, through sudo, a Python interpreter with a module generated on the fly (sudo -u root /bin/sh -c 'echo BECOME-SUCCESS-...; /usr/bin/python3 ...'). You can't limit sudo to "certain commands" for Ansible: either it can run Python as root, or it can't manage the system. Least privilege for become is therefore applied in other ways:
| Measure | In Aurora |
|---|---|
| A dedicated account for automation, separate from people | automation in production (section 5.3) |
| That account only accepts its key and only from the automation machines | from="..." in authorized_keys |
become only in the plays that need it |
The configuration playbooks use it; staging-provision.yml and the tasks delegated to localhost have become: false |
become_user to an unprivileged user when that's enough |
postgresql tasks as postgres (Lesson 3.4) |
become_ask_pass/password for people |
Human administrators use sudo with their password |
Never a global become: true in ansible.cfg |
[privilege_escalation] become = False since Lesson 2.3 |
5.2. sudo rules validated with visudo
New variables in roles/common/defaults/main.yml:
# sudo (Lesson 9.2)
common_sudo_group: sudo # wheel in the Red Hat family
common_sudo_timeout: 5 # minutes before the password is asked for again
# Automation account ("" = not created)
common_automation_user: ""
common_automation_keys: []
common_automation_key_options: ""And in vars/main.yml: common_sudoers_file: /etc/sudoers.d/common. The template roles/common/templates/sudoers.j2:
# {{ ansible_managed }}
# sudo rules of the common role. Validated with "visudo -cf" before being installed.
# Administrators: sudo with their password, which is asked for again
# after {{ common_sudo_timeout }} minutes without using it.
Defaults:%{{ common_sudo_group }} timestamp_timeout={{ common_sudo_timeout }}
{% if common_automation_user | length > 0 %}
# Automation account: Ansible needs to escalate without an interactive password.
# Its access is limited by key and origin (authorized_keys with from=).
{{ common_automation_user }} ALL=(ALL:ALL) NOPASSWD: ALL
{% endif %}Why each detail matters:
validate: /usr/sbin/visudo -cf %sis essential: asudoers.dfile with a syntax error breakssudofor the whole system, Ansible included, and the only way to fix it would be to log in asroot(which you've just forbidden). Withvalidate, an error makes the task fail and the file isn't installed.mode: "0440":sudoignoressudoers.dfiles with overly open permissions.- The name
commoncontains no dot and doesn't end in~:sudoignoressudoers.dfiles whose name contains a dot (common.confwouldn't be read). - The Vagrant file (
/etc/sudoers.d/vagrant,vagrant ALL=(ALL) NOPASSWD:ALL) isn't touched: it's the lab's automation account.
Pipelining and
requiretty. If you ever addDefaults requiretty, Ansible won't be able to use pipelining (Lesson 9.3), becausesudowould demand a terminal that Ansible doesn't open. Ubuntu doesn't enable it and Aurora won't either.
5.3. The automation account
A new block in roles/common/tasks/main.yml, between "Team users" and "Access hardening":
- name: Automation account
when: common_automation_user | length > 0
tags:
- users
- security
block:
- name: Create the automation account
ansible.builtin.user:
name: "{{ common_automation_user }}"
comment: Automation account (Ansible)
shell: /bin/bash
- name: Authorize the automation account keys
ansible.posix.authorized_key:
user: "{{ common_automation_user }}"
key: '{{ common_automation_keys | join("\n") }}'
key_options: "{{ common_automation_key_options | default(omit, true) }}"
exclusive: true- The account is created without a password (locked for password logins): it can only log in with its key.
key_optionsadds options in front of each key. Withfrom="10.20.0.30", the key is only accepted from that address (the production AWX node): a stolen key is useless from another machine. Other useful options:no-agent-forwarding,no-X11-forwarding,no-port-forwarding.default(omit, true)omits the parameter when the variable is empty (the second argument makes the empty string count as "no value").
In production, inventories/production/group_vars/all/automation.yml:
---
# Account AWX uses to connect to production (ansible_user in connection.yml).
common_automation_user: automation
common_automation_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... [email protected]
common_automation_key_options: 'from="10.20.0.30",no-agent-forwarding,no-X11-forwarding'What about the first time? The account doesn't exist until the role creates it, and to run the role you need to connect. It's the bootstrap problem: the first run is done with the initial account provided by the installation (the cloud image user, or one created by the systems team), with -e ansible_user=<initial account> --tags users,security; from then on, everything goes through automation and the initial account is disabled. In the lab, the automation account is still vagrant, for convenience (there's an exercise to try out the dedicated account).
5.4. Applying and checking
ansible-playbook playbooks/common.yml --tags users,security --check --diff --limit web2
ansible-playbook playbooks/common.yml --tags users,security
ssh -i ~/.ssh/aurora_laura [email protected] 'sudo -l'sudo -l will ask for Laura's password (the one she used to generate the hash) and will show (ALL : ALL) ALL. Also check that the sudo syntax is correct on every server:
- Host keys: verifying who you connect to
6.1. The risk
The first time you connect to a server, SSH shows you its fingerprint and asks whether you trust it. If you accept it without checking it, someone who gets between you on the network could impersonate the server and receive your commands (and the secrets Ansible sends). Aurora has three different situations:
| Environment | Current situation | Policy |
|---|---|---|
lab |
You accepted the fingerprints by hand with ssh web1 (Lesson 1.3); host_key_checking = True |
Versioned and verified known_hosts |
staging |
accept-new (Lesson 8.4) |
accept-new is kept with a dedicated known_hosts: the instances are new every time they're recreated and the network is controlled; the fingerprint is checked with the AWS console if in doubt |
production |
(New) | Versioned known_hosts, with fingerprints obtained through an independent channel |
| AWX | Disables the check by default | It's re-enabled and uses the repository's known_hosts |
6.2. A versioned known_hosts
Public host keys aren't secrets: they can go in the repository. That way, verification doesn't depend on each person's ~/.ssh/known_hosts or on AWX having it. Collect the lab ones:
mkdir -p ssh
ssh-keyscan -t ed25519 192.168.56.10 192.168.56.11 192.168.56.12 192.168.56.21 192.168.56.41 > ssh/known_hosts.lab
ssh-keygen -lf ssh/known_hosts.labssh-keyscan downloads the key without verifying it, so you need to compare the fingerprints through another channel. In the lab, that channel is Vagrant:
cd lab
for vm in lb1 web1 web2 db1 api1; do
vagrant ssh "$vm" -c 'ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub' 2>/dev/null
done
cd ..Each SHA256:... fingerprint must match the one from ssh-keygen -lf ssh/known_hosts.lab. In production, the channel would be the hypervisor console or the output of the automated installation; on AWS, the instance's console output (aws ec2 get-console-output), where cloud-init prints the fingerprints.
In inventories/lab/group_vars/all/connection.yml (new):
---
# Strict host key verification with the repository's known_hosts.
# Path relative to the repository root: Ansible always runs from there
# (your terminal, AWX, ansible-navigator and CI).
ansible_ssh_common_args: -o StrictHostKeyChecking=yes -o UserKnownHostsFile=ssh/known_hosts.labAnd the same in production with ssh/known_hosts.production. Try it:
To see that it really verifies, simulate a "changed" server: edit a line of ssh/known_hosts.lab (change one character of web2's key) and repeat. web2 must end up UNREACHABLE with Host key verification failed. Undo the change with git checkout ssh/known_hosts.lab.
When you reinstall a server (for example, when restoring an old snapshot or recreating a VM), its key will change: the file is updated with the same procedure and reviewed in a pull request, like any other change.
6.3. AWX
AWX disables host key checking by default, and that option, which reaches Ansible as -o StrictHostKeyChecking=no, comes before ansible_ssh_common_args on the ssh command line (and in SSH the first value wins). To make AWX respect the policy:
- In Settings → Job settings → Extra Environment Variables, add
{"ANSIBLE_HOST_KEY_CHECKING": "True"}. - Launch
Aurora - Check configurationwith verbosity 3 (-vvv) and look in theSSH: EXEC ssh ...line for the optionsStrictHostKeyChecking=yesandUserKnownHostsFile=ssh/known_hosts.lab.
Since the file is in the project, AWX gets it on every sync.
- nginx without its version:
ansible-role-nginx 1.1.0
ansible-role-nginx 1.1.0With the current configuration, nginx advertises its exact version in the Server header and on error pages:
It isn't a vulnerability, but it makes it easier for an attacker to look up known flaws in that version. The server_tokens off; directive hides it. The nginx role lives in its own repository (Lesson 6.4) and isn't edited in galaxy_roles/ (section 11 of Lesson 9.1): a new version is released.
In ~/ansible-role-nginx, on a branch:
defaults/main.yml:
In templates/nginx.conf.j2, inside the http { block, next to sendfile:
Add nginx_server_tokens to meta/argument_specs.yml (type: bool, default: false) and to the table in the README.md, and an entry in CHANGELOG.md:
## 1.1.0 - 2026-11-26
### Added
- `nginx_server_tokens` variable (default `false`): nginx no longer shows its version.It's a minor change according to SemVer (it adds a compatible variable), even though it changes the default behavior; that's why it's documented. Release it:
git commit -am "server_tokens configurable and disabled by default"
git switch main && git merge --ff-only server-tokens
git tag -a 1.1.0 -m "Version 1.1.0: server_tokens off"
git push origin main --tagsIn aurora-infra, roles/requirements.yml:
cd ~/aurora-infra
ansible-galaxy role install -r roles/requirements.yml --force
ansible-playbook playbooks/site.yml --tags config --check --diff --limit lb1,web1
ansible-playbook playbooks/site.yml --tags config
curl -sI http://192.168.56.10/ | grep -i ^serverThe diff will show a line added to /etc/nginx/nginx.conf on lb1, web1 and web2, and the handler will validate and reload nginx. The optional "Show the nginx version" task in webservers.yml (info tag) will now only show nginx: that's exactly what you were after.
- Docker: the
docker group, ports and the registry
docker group, ports and the registry8.1. The docker group is equivalent to root
In Lesson 8.1 you added vagrant to the docker group to use the community.docker.docker connection. Belonging to that group lets you talk to the Docker daemon, which runs as root, and with it mount the host's / in a container: it's root with no password and no sudo log. The policy:
docker_usersis only used in the lab (it's already like that since Lesson 9.1: the variable only exists ininventories/lab/group_vars/apiservers.yml, with the warning comment). Nothing changes in the lab, becausevagrantalready has passwordlesssudo.- In
stagingand production, no person or service account joins thedockergroup; whoever needs Docker usessudo docker(which gets logged) and the automation usesbecome. - For services that don't need privileges there's rootless Docker or rootless Podman; Aurora doesn't adopt it yet.
8.2. Ports that bypass ufw
Docker publishes ports by adding iptables rules that are evaluated before the ufw ones. The catalog service publishes 8080 on all of api1's interfaces, even though no ufw rule allows it. The API is only queried locally (the playbook check uses localhost) and from outside people access the Kubernetes version, so listening on 127.0.0.1 is enough.
In roles/aurora_catalog/defaults/main.yml:
# Address the API is published on. 127.0.0.1 = only reachable from the server
# itself (Docker publishes ports ahead of the firewall, Lesson 9.2).
aurora_catalog_bind_address: 127.0.0.1In templates/compose.yaml.j2, catalog service:
Add the variable to meta/argument_specs.yml (type: str). When you apply ansible-playbook playbooks/apiservers.yml, Compose recreates the catalog container (its port publishing has changed); Redis isn't touched. Check from your computer that the port no longer responds and from api1 that it does:
curl -s --max-time 3 http://192.168.56.41:8080/health || echo "Not reachable from outside"
ssh api1 'curl -s http://127.0.0.1:8080/health'If some day a containerized service must be reachable from other servers, publish it on the internal address (aurora_internal_ip) and filter with the iptables DOCKER-USER chain, which Docker reserves for administrator rules and evaluates before its own.
8.3. The registry without TLS or authentication
registry.aurora-store.example:5000 accepts any push without credentials and over HTTP. In the lab that's acceptable because it's only reachable on the 192.168.56.0/24 network; in production, a registry like that would let anyone on the network replace the API image with another one. What would need to be done (it isn't done in the lab): TLS with a certificate from the internal CA, authentication (at least htpasswd, ideally a registry with users and permissions such as Harbor or Gitea's), community.docker.docker_login with the password in Vault and no_log: true, and removing insecure-registries from daemon.json and from Podman's registries.conf. It goes in the table in section 14.
- Kubernetes: a deployment account instead of the administrator
9.1. The problem
~/.kube/aurora-lab.yaml is the k3s cluster administrator kubeconfig. With it, a mistake in kubernetes.yml (or someone with access to your computer) could delete any namespace, including awx. In Exercise 3 of Lesson 8.2 you designed the alternative: a ServiceAccount with a Role limited to the aurora namespace. Now you implement it, with the split from that lesson: the platform play (Traefik, RBAC) keeps using the administrator identity; the applications play, the limited one.
9.2. The RBAC objects
playbooks/templates/k8s-deploy-rbac.yaml.j2:
---
# Service account Ansible uses to deploy the Aurora applications.
apiVersion: v1
kind: ServiceAccount
metadata:
name: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}
---
# Long-lived token for the account (in production, short-lived tokens are better).
apiVersion: v1
kind: Secret
metadata:
name: aurora-deploy-token
namespace: {{ aurora_catalog_k8s_namespace }}
annotations:
kubernetes.io/service-account.name: aurora-deploy
type: kubernetes.io/service-account-token
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}
rules:
- apiGroups: [""]
resources: [configmaps, services]
verbs: [get, list, watch, create, update, patch]
- apiGroups: [""]
resources: [pods]
verbs: [get, list, watch]
- apiGroups: [apps]
resources: [deployments]
verbs: [get, list, watch, create, update, patch]
- apiGroups: [apps]
resources: [replicasets]
verbs: [get, list, watch]
- apiGroups: [networking.k8s.io]
resources: [ingresses]
verbs: [get, list, watch, create, update, patch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: aurora-deploy
subjects:
- kind: ServiceAccount
name: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}
---
# Read (only read) ITS namespace: the role checks that it exists before deploying.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: aurora-deploy-namespace
rules:
- apiGroups: [""]
resources: [namespaces]
resourceNames: ["{{ aurora_catalog_k8s_namespace }}"]
verbs: [get]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: aurora-deploy-namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: aurora-deploy-namespace
subjects:
- kind: ServiceAccount
name: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}The permissions come from what the aurora_catalog_k8s role does: applying the ConfigMap, Service, Deployment and Ingress (create, update, patch), waiting for the pods (get, list, watch), and rolling back with k8s_rollback (which reads the ReplicaSets and modifies the Deployment). It can't delete anything or touch other namespaces, nodes or cluster resources. The role's "Create the application namespace" task still works: the namespace already exists and there are no differences, so the module only reads it; that's why a get permission limited to that name (resourceNames) is enough.
9.3. The platform play creates the account and its kubeconfig
In inventories/lab/host_vars/k3s-lab.yml, the access variables become two sets:
# Cluster administration (only the platform play). Outside the repository.
k8s_admin_kubeconfig: ~/.kube/aurora-lab.yaml
k8s_admin_context: aurora-lab
# Application deployment: account limited to the aurora namespace (Lesson 9.2).
# The file is generated by the platform play in kubernetes.yml.
k8s_kubeconfig: ~/.kube/aurora-lab-deploy.yaml
k8s_context: aurora-lab-deploy
k8s_api_server: https://192.168.56.30:6443In playbooks/kubernetes.yml, the first play uses the administrator identity for everything (including the k8s modules) and adds, after Traefik:
- name: Install the cluster platform components
hosts: k8s_clusters
gather_facts: false
module_defaults:
group/kubernetes.core.k8s:
kubeconfig: "{{ k8s_admin_kubeconfig }}"
context: "{{ k8s_admin_context }}"
group/kubernetes.core.helm:
kubeconfig: "{{ k8s_admin_kubeconfig }}"
context: "{{ k8s_admin_context }}"
tasks:
# ... chart repository and Traefik installation (unchanged) ...
- name: Create the applications namespace
kubernetes.core.k8s:
api_version: v1
kind: Namespace
name: "{{ aurora_catalog_k8s_namespace }}"
state: present
- name: Create the deployment account and its permissions
kubernetes.core.k8s:
template: k8s-deploy-rbac.yaml.j2
state: present
apply: true
- name: Read the deployment account token
kubernetes.core.k8s_info:
kind: Secret
namespace: "{{ aurora_catalog_k8s_namespace }}"
name: aurora-deploy-token
register: aurora_k8s_token
until: aurora_k8s_token.resources[0].data.token is defined
retries: 5
delay: 2
no_log: true
- name: Generate the deployment account kubeconfig
ansible.builtin.template:
src: kubeconfig-deploy.yaml.j2
dest: "{{ k8s_kubeconfig }}"
mode: "0600"
no_log: true- The namespace is now created by the platform (with cluster permissions); the application role only checks that it exists.
- Kubernetes fills in the token
Secretasynchronously; theuntilwaits for it to appear. no_log: trueon the two tasks that handle the token: with-vit would be printed.
playbooks/templates/kubeconfig-deploy.yaml.j2:
# {{ ansible_managed }}
apiVersion: v1
kind: Config
clusters:
- name: {{ k8s_context }}
cluster:
server: {{ k8s_api_server }}
certificate-authority-data: {{ aurora_k8s_token.resources[0].data['ca.crt'] }}
users:
- name: aurora-deploy
user:
token: {{ aurora_k8s_token.resources[0].data.token | b64decode }}
contexts:
- name: {{ k8s_context }}
context:
cluster: {{ k8s_context }}
user: aurora-deploy
namespace: {{ aurora_catalog_k8s_namespace }}
current-context: {{ k8s_context }}The fields of a Secret come in Base64: the CA certificate is copied as is (the kubeconfig also expects it in Base64), and the token is decoded with b64decode. The second play doesn't change: it still uses k8s_kubeconfig and k8s_context, which now point to the limited account.
ansible-playbook playbooks/kubernetes.yml
ansible-playbook playbooks/kubernetes.yml # changed=0
ansible --playbook-dir playbooks k3s-lab -m kubernetes.core.k8s_info \
-a "kind=Node kubeconfig={{ k8s_kubeconfig }} context={{ k8s_context }}"The last command must fail with a 403 Forbidden error ("cannot list resource nodes"): the deployment account can't see the nodes. That's the proof that the limit works.
- CI: the runner and secrets
10.1. The runner in host mode
The act_runner on awx1 runs each job directly as the runner user, on the same machine where AWX, k3s, Gitea and the registry run. Anyone who can modify a workflow in a repository of the ops organization can run commands on awx1. The measures, from least to most effort:
| Measure | Effect |
|---|---|
The runner user without sudo or privileged groups (no docker, no adm) |
Limits what a malicious job can do |
Register the runner at repository level (aurora-infra), not at organization level |
Only that repository's workflows use it |
Protected branches: main only through a reviewed pull request (Lesson 8.3) |
A modified workflow doesn't reach main without review |
Secrets are only used in main and tag jobs (like lab-check) |
An arbitrary branch doesn't receive AWX_TOKEN; Gitea also doesn't hand secrets to pull requests from forks |
act_runner in container mode (each job in a throwaway container) |
The job can't see awx1's system |
| A runner on its own VM | A failing job doesn't compromise AWX or Gitea |
In the lab, apply the first three; the last two are the recommendation for production (noted in section 14).
10.2. Secrets in CI
- Least privilege: the
AWX_TOKENtoken belongs togitea-ci, which can only run two templates and can't approve (Lesson 8.3). Every CI credential should be like that. - Expiry and rotation: create the AWX tokens with an expiry date and renew them (for example, every 90 days); note the date in the
README.md. - Don't print them: Gitea masks secrets in the logs, but only if they appear literally; a transformed secret (in Base64, truncated) would be shown. Never
echoa secret, neverset -xin steps that use them. - Pin actions by commit:
uses: actions/checkout@v4follows a tag its author can move. Pinning by SHA (uses: actions/checkout@<40-character sha> # v4.x) guarantees that exactly the reviewed code runs. You'll see this again in section 13. - Detect secrets before they get in: a
gitleaksscan on every commit (you'll add it withpre-commitin Lesson 9.4) and over the whole history (gitleaks git .).
- The cloud: a minimal IAM policy
In Lesson 8.4 you created the aurora-ansible user with "only what's needed". A concrete IAM policy for OpenTofu and Ansible in staging limits by region and by the project tag. A starting point (illustrative, not complete):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadEC2InRegion",
"Effect": "Allow",
"Action": ["ec2:Describe*"],
"Resource": "*",
"Condition": { "StringEquals": { "aws:RequestedRegion": "eu-south-2" } }
},
{
"Sid": "CreateAuroraTaggedResources",
"Effect": "Allow",
"Action": [
"ec2:CreateVpc", "ec2:CreateSubnet", "ec2:CreateInternetGateway",
"ec2:CreateRouteTable", "ec2:CreateSecurityGroup", "ec2:ImportKeyPair",
"ec2:RunInstances", "ec2:CreateTags"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:RequestedRegion": "eu-south-2",
"aws:RequestTag/Project": "aurora"
}
}
},
{
"Sid": "ModifyDeleteOnlyAurora",
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances", "ec2:DeleteVpc", "ec2:DeleteSubnet",
"ec2:DeleteSecurityGroup", "ec2:AuthorizeSecurityGroupIngress",
"ec2:RevokeSecurityGroupIngress", "ec2:DeleteRouteTable",
"ec2:DeleteInternetGateway", "ec2:AttachInternetGateway",
"ec2:DetachInternetGateway", "ec2:AssociateRouteTable", "ec2:CreateRoute"
],
"Resource": "*",
"Condition": { "StringEquals": { "aws:ResourceTag/Project": "aurora" } }
}
]
}aws:RequestedRegionprevents creating anything outsideeu-south-2(also useful against configuration mistakes that would create billable resources in another region).aws:RequestTag/Projectrequires resources to be created with theProject=auroratag; OpenTofu'sdefault_tags(Lesson 8.5) always set it.aws:ResourceTag/Projectlimits modifications and deletions to resources already tagged as Aurora's: even if the credentials leak, they can't be used to delete other projects' resources.
Not all EC2 actions support these conditions in the same way (RunInstances, for example, touches several resource types at once: image, subnet, network interface, volume), so a real policy is refined by testing and with tools like IAM Access Analyzer, which generates policies from the activity recorded in CloudTrail. In addition: temporary identities (IAM Identity Center/SSO or assumed roles) instead of permanent access keys, MFA for people, and in AWX the Amazon Web Services credential type instead of files on disk. The final policy must be reviewed by whoever manages the account's security.
- Vault: identities, rotation,
no_log and external managers
no_log and external managers12.1. Per-environment identities (done)
Lesson 9.1 left one vault per environment with its own identity. Go over who has each password: the lab, the whole team; staging, Operations and CI; production, AWX and those responsible for it. If a person leaves the team, the Vault passwords of the environments they had access to must be rotated.
12.2. Rotating: the Vault password and the secrets
There are two different rotations, and it's important not to confuse them:
| Rotation | What changes | When | How |
|---|---|---|---|
| Of the Vault password | The key the file is encrypted with; the secrets stay the same | Periodically, or when someone with access leaves | ansible-vault rekey |
| Of the secrets | The PostgreSQL passwords, the tokens… | When a secret may have leaked (also after a rekey because someone who could have copied them left) |
New value in the vault + apply |
rekey of the lab vault with a new password:
ansible localhost -m ansible.builtin.copy \
-a "content={{ lookup('ansible.builtin.password', '/dev/null', length=32, chars=['ascii_letters', 'digits']) }} dest=~/.ansible/vault/aurora-lab-new.pass mode=0600"
ansible-vault rekey \
--vault-id lab@~/.ansible/vault/aurora-lab.pass \
--new-vault-id lab@~/.ansible/vault/aurora-lab-new.pass \
playbooks/group_vars/lab/vault.yml
mv ~/.ansible/vault/aurora-lab-new.pass ~/.ansible/vault/aurora-lab.passAfterwards: update the Aurora - Vault lab credential in AWX, distribute the new password through the password manager and commit the re-encrypted file. The Git history keeps the previous version encrypted with the old password: that's why a rekey isn't enough if the old password leaked; in that case the secrets must be rotated as well.
Rotating a secret, for example the store database password:
- New value with
ansible-vault editin the environment's vault. ansible-playbook playbooks/site.yml --tags users,deploy(PostgreSQL changes the user's password;aurora_apprewrites/etc/aurora/db.conf).- Between the two steps there are a few seconds during which the website has the old password. For a zero-downtime rotation, you first create a new user, switch the application over and retire the old one; with PostgreSQL and an in-house application, Aurora accepts the brief outage in a maintenance window.
12.3. no_log: review it, don't assume it
A simple audit: find the tasks that handle sensitive values and check that they have no_log: true.
grep -rn -B2 -A12 -E 'password|token|secret' roles/ playbooks/ --include=*.yml | grep -E 'name:|no_log' | lessIn Lesson 9.4 you'll also enable the ansible-lint no-log-password rule, which detects tasks with a password parameter and no no_log. Remember that no_log also hides errors; and that it doesn't protect against everything: a failing module can include values in its message, and ansible-playbook -vvvv shows the connection arguments.
12.4. External secret managers
Ansible Vault encrypts files, but it isn't a secret manager: it has no per-secret access control, no log of who read what, no expiry and no automatic rotation. When an organization grows, secrets are stored in a specialized service and Ansible queries them at the moment of use with a lookup (which runs on the control node, Lesson 5.3):
# HashiCorp Vault (community.hashi_vault collection), KV engine version 2.
aurora_db_password: >-
{{ lookup('community.hashi_vault.vault_kv2_get', 'aurora/' ~ aurora_env ~ '/db',
engine_mount_point='secret').secret.password }}The server URL and the authentication (token, AppRole…) are taken from environment variables like VAULT_ADDR or from the lookup options. With AWS Secrets Manager, the amazon.aws collection (which you already have) offers an equivalent lookup:
aurora_db_password: "{{ lookup('amazon.aws.secretsmanager_secret', 'aurora/staging/db-password', region='eu-south-2') }}"In AWX, credential plugins (HashiCorp Vault Secret Lookup, AWS Secrets Manager Lookup, CyberArk…) fill in a credential's fields by querying the manager, without the secret being stored in AWX. Aurora doesn't adopt them now (there's no secret manager in the lab), but the variable design allows it: you only need to change the value of aurora_db_password in playbooks/group_vars/all/aurora.yml, without touching any role.
- The supply chain
Your automation runs other people's code with your credentials: collections (their plugins run on the control node, Lesson 6.1), roles, container images, Python packages and CI actions. The measures:
| Element | Aurora's situation | Additional measure |
|---|---|---|
| Collections | Exact versions in collections/requirements.yml |
Verify signatures when the server offers them |
| Roles | Exact versions; nginx from the internal Gitea |
Review the diff between versions before upgrading |
| Images | redis:7.4-alpine, python:3.12-slim, EE base by tag |
Pin by digest (@sha256:...), which can't move |
| Python packages (CI, EE) | Pinned versions or ranges | pip install --require-hashes with a file generated by pip-compile --generate-hashes |
| CI actions | actions/checkout@v4 |
Pin by commit SHA |
About collection signatures: ansible-galaxy can verify GPG signatures for the collections that publish them (Automation Hub signs certified content; a Private Automation Hub can sign internally approved content). Verification is configured with a keyring of trusted keys:
ansible-galaxy collection install -r collections/requirements.yml \
--keyring ~/.ansible/aurora-trust.kbx --required-valid-signature-count 1
ansible-galaxy collection verify community.postgresql:4.2.2 --keyring ~/.ansible/aurora-trust.kbxIn requirements.yml you can also specify additional signatures per collection (signatures:, Lesson 6.3). Public Galaxy doesn't publish signatures for most community collections: that's why, for Aurora, the realistic measure today is to pin versions, review the changes when upgrading and, if the external content grows, serve it from an internal server that approves it (option D in Lesson 7.4). And remember that collection verify without signatures only checks integrity against the server, not that the content is safe.
- The lab's security debt
There are things the lab does insecurely on purpose, for simplicity. The professional thing is to know it and write it down, so that nobody copies them into production. Add this table to the "Security" section of the README.md:
| Lab | Production |
|---|---|
Ansible logs in as vagrant with passwordless sudo |
automation account with a key restricted by origin |
| AWX, Gitea and the registry over HTTP | HTTPS with certificates from the internal CA |
Registry without authentication, insecure-registries |
Registry with TLS, users and permissions |
docker_users: [vagrant] |
Nobody in the docker group |
Runner in host mode on awx1, alongside AWX |
Runner in container mode and on its own VM |
| AWX's k3s shared with the applications | Clusters separated by function |
Long-lived token for aurora-deploy |
Short-lived tokens or an AWX credential |
node_exporter on 127.0.0.1:9100 (no Prometheus yet) |
Open only to the Prometheus server's IP with ufw, and with TLS/authentication if it crosses networks |
| Production Vault password on the student's laptop | Only in AWX and in the password manager |
| Local OpenTofu state | Encrypted remote state with locking |
Commit this lesson's changes:
git add -A
git commit -m "Security: hardened SSH, team keys and sudo, known_hosts, nginx 1.1.0, local Docker and k8s deployment account"(and the CHANGELOG.md with a "Security" section summarizing the changes).
Common Mistakes and Tips
- Locking yourself out over SSH. Always:
--check --difffirst,--limitto one host, a backup session open and an emergency access route (console). Never useAllowGroupswithout checking the Ansible user's group. PermitRootLogin False. You wrotenowithout quotes in YAML. Always quote"yes","no","on"and"off"when they're text values.sudobroken on every server. Asudoers.dfile withoutvalidate: visudo -cf %s. If it happens, recovery is through the console, asrootor in rescue mode. That's whyvalidateisn't optional.Missing privilege separation directory: /run/sshdwhen validating withsshd -t. It shows up on systems where the SSH service isn't running (test containers, Lesson 9.5); it doesn't happen on a server you're connected to over SSH.- A "ghost" administrator. Removing
admin: trueisn't enough withappend: true: you need the task that removes the user from the group (section 4.3). Host key verification failedafter recreating a VM. That's the system working. Updatessh/known_hosts.labwith the verification procedure; don't disable the check "just to get by".403 Forbiddeninkubernetes.yml. The deployment account lacks a permission the role needs (for example, after adding a new resource to the template). Extend the Role with the specific verb and resource; don't go back to the administratorkubeconfig.- Tip: keep security changes in separate commits with clear messages. When an auditor asks "since when has password authentication been disabled?", the answer will be in
git log.
Exercises
Exercise 1: the automation account in the lab
Create the automation account in the lab only on web2, with the key ~/.ssh/aurora_ed25519.pub restricted to the origin 192.168.56.1 (your computer's address on the Vagrant network), and check that Ansible can work with it. What would happen if AWX tried to connect with that account?
Exercise 2: security headers in nginx
Propose a change to ansible-role-nginx that adds the X-Content-Type-Options: nosniff and X-Frame-Options: DENY headers to the site, enabled with a variable. What version number would the role have? What steps would you follow until it reaches lb1?
Exercise 3: quick audit
Write a playbook playbooks/security-audit.yml (read-only, no changes) that, for all the aurora servers, checks with assert that: the effective PermitRootLogin is no, the effective PasswordAuthentication is no, visudo -c succeeds, and there's no user with UID 0 other than root. It must be possible to run it with --check.
Solutions
Exercise 1. inventories/lab/host_vars/web2.yml:
common_automation_user: automation
common_automation_keys:
- "{{ lookup('ansible.builtin.file', lookup('ansible.builtin.env', 'HOME') ~ '/.ssh/aurora_ed25519.pub') }}"
common_automation_key_options: 'from="192.168.56.1"'(The file lookup reads the public key on your computer, Lesson 5.3; the path is built with HOME so as not to depend on the lookup expanding ~.) Apply with ansible-playbook playbooks/common.yml --tags users,security --limit web2 and test with ansible --playbook-dir playbooks web2 -u automation -m ansible.builtin.ping and with ansible --playbook-dir playbooks web2 -u automation -b -m ansible.builtin.command -a id, which must show uid=0(root). Here -u works because in the lab the user comes from remote_user in ansible.cfg, not from ansible_user in the inventory (which would win over -u, Lesson 2.2). AWX connects from a pod on awx1: the origin web2 sees is 192.168.56.30, not 192.168.56.1, so the key would be rejected (from= doesn't match). In a real case, from= would include the address of the AWX execution nodes. Undo the change (delete the added host_vars file and, on web2, run userdel -r automation; the sudoers.d/common file is regenerated without that line on the next run).
Exercise 2. A variable nginx_security_headers: false (the default, so as not to change the behavior for those who already use the role) and, in site.conf.j2, inside server:
{% if nginx_security_headers %}
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
{% endif %}It adds compatible functionality: version 1.2.0. Steps: a branch in ansible-role-nginx, argument_specs, README, CHANGELOG, merge, tag 1.2.0 and push; in aurora-infra, version: "1.2.0" in roles/requirements.yml, nginx_security_headers: true in playbooks/group_vars/loadbalancers.yml (and in webservers.yml if you also want it on the web servers), ansible-galaxy role install -r roles/requirements.yml --force, --check --diff and apply. always makes nginx add the header to error responses too.
Exercise 3.
---
# Read-only security audit (Lesson 9.2).
- name: Audit the security of the Aurora Store servers
hosts: aurora
become: true
gather_facts: false
tasks:
- name: Get the effective SSH configuration
ansible.builtin.command:
cmd: sshd -T
register: aurora_audit_sshd
changed_when: false
check_mode: false
- name: Check the sudo syntax
ansible.builtin.command:
cmd: visudo -c
register: aurora_audit_sudo
changed_when: false
failed_when: false
check_mode: false
- name: Look up the users with UID 0
ansible.builtin.getent:
database: passwd
- name: Check the security policy
ansible.builtin.assert:
that:
- "'permitrootlogin no' in aurora_audit_sshd.stdout_lines"
- "'passwordauthentication no' in aurora_audit_sshd.stdout_lines"
- aurora_audit_sudo.rc == 0
- >-
ansible_facts['getent_passwd'] | dict2items
| selectattr('value.1', 'equalto', '0') | map(attribute='key') | list == ['root']
fail_msg: "{{ inventory_hostname }} does not comply with the security policy"
success_msg: "{{ inventory_hostname }} complies with the security policy"getent with database: passwd stores each user as a key and a list [password, UID, GID, ...] as the value; that's why the UID is value.1. check_mode: false on the read commands makes them run with --check too (Lesson 3.7).
Conclusion
You've paid off the security debt Aurora Store had been accumulating. The servers accept only keys over SSH, with a configuration in sshd_config.d/ that's validated before being installed and before reloading; the team has its keys managed exclusively and its sudo passwords stored as encrypted hashes in each environment's vault, with privileges that depend on the environment; the sudo rules go through visudo -cf, and the production automation account only accepts its key from AWX. Host keys are verified with a versioned known_hosts, in AWX too, nginx no longer advertises its version (ansible-role-nginx 1.1.0), the catalog API only listens locally, and Ansible deploys to Kubernetes with an account limited to the aurora namespace. You also have criteria for the CI runner and secrets, a minimal IAM policy by region and tag, a procedure for rotating Vault passwords and secrets, a path toward external secret managers and measures for the supply chain, and the debt that remains in the lab is documented. All of this means more tasks, templates, validations and handlers: site.yml does considerably more work today than at the beginning, and in larger environments that shows in the run time. In the next lesson, Performance Tuning, you'll measure where the time goes and tune forks, pipelining, persistent connections, the facts cache and strategies, both in your terminal and in AWX.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
