Lesson 7 of 13 · 24m
Jinja2 Templates and Vault Secrets
template/copy/lineinfile by ownership, validate: so a bad config never lands, and the vars.yml+vault.yml layout that keeps secrets greppable but encrypted.
"Prod was down because the deploy script wrote the staging DB password into the prod config" — a real retro line, and the script was a sed one-liner. Templates exist so that class of bug — wrong values in the wrong file on the wrong host — becomes structurally impossible. Vault exists so the secrets inside those templates can live next to the code without ending up in git history.
template: you own the file, Jinja renders it
- name: Ship app config
ansible.builtin.template:
src: app.env.j2
dest: /opt/acme/app.env
owner: acme
group: acme
mode: "0600"
validate: /usr/sbin/sshd -t -f %s
notify: Restart acme-apptemplate renders a .j2 file from templates/ (or the role's templates/) onto the host — the whole file, every byte, as the declared state. The validate: argument is criminally underused: it renders to a temp file, runs your command against %s, and only installs on a pass. sshd -t -f, nginx -t, visudo -cf all fit — a broken config physically cannot land. Quote the mode ("0600" not 0600); YAML's octal parsing has ruined more than one file's permissions.
{# templates/app.env.j2 #}
# Managed by Ansible — manual edits will be overwritten
DATABASE_URL=postgres://{{ db_user }}:{{ db_password }}@{{ db_host }}:5432/{{ db_name }}
LOG_LEVEL={{ log_level | default('info') }}
ALLOWED_HOSTS={{ allowed_hosts | join(',') }}
{% for host in groups['metrics'] %}
METRICS_PEER_{{ loop.index }}={{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }}
{% endfor %}The idioms that cover ninety percent of real templates: | default('x') for optional knobs, | join(',') for lists, {% for %} + loop.index for peer enumeration, groups[]/hostvars[] for values that live on other hosts. {# comments #} never render; # and // inside the file do. One warning on hostvars: it only contains facts for hosts that have been set up this run — template before the metrics group has been gathered and you get undefined at render time, not a helpful error.
The ownership rule: template vs copy vs lineinfile
template:— you own the whole file. Rendered from Jinja, immune to drift: run it and the file is the declaration again.copy: content:— you own the whole file and it's short or static (a MOTD, a one-line sysctl include).lineinfile:/blockinfile:— you own one line or one block inside a file other tools also touch: a line in/etc/fstab, a stanza in a sharedsudoers.dfile. They edit, they don't own — which is exactly why they're weaker: runlineinfiletwice with a slightly differentregexpand you own two lines.
The rule is ownership, not convenience. If the whole file is yours, template it — lineinfile stacking is how a config becomes palimpsest nobody can read.
Vault: secrets that can live in git
ansible-vault encrypt group_vars/dbservers/vault.yml # encrypt a whole file
ansible-vault encrypt_string 's3cr3t' --name db_password # one variable, inline
ansible-vault edit group_vars/dbservers/vault.yml # decrypt → edit → re-encrypt
ansible-playbook site.yml --ask-vault-pass
ansible-playbook site.yml --vault-id prod@~/.vault_prod.txt # vault ID per environmentVault encrypts with AES256 at rest; in memory during the run, a vaulted value is indistinguishable from any other variable. The layout that survives team growth: every group_vars/<group>/ gets a vars.yml (plaintext) and a vault.yml (encrypted), and plaintext vars reference vaulted vars —
# group_vars/dbservers/vars.yml — name greppable, value never is
db_password: "{{ vault_db_password }}"so grep -r db_password finds the reference, not the secret. --vault-id prod@... lets one repo hold per-environment vault passwords and Ansible prompts or loads the right one. ansible-vault rekey rotates the password; edit rotates the value — different operations, both scheduled events.
The mechanics people skip until the incident: vault only protects the value at rest. no_log: true on any task that touches a secret, or the decrypted password prints in -v output and lands in CI logs, Slack-paste debugging sessions, and ARA recordings. And the password file — ~/.vault_pass.txt — belongs in .gitignore on day one; a vault password committed to the repo it protects is the oldest self-own in the ecosystem.
Field notes
ansible-vault viewreads without editing;decryptexists and is almost never what you want in a shared repo.mode,owner,backup: trueontemplate/copy—backupkeeps a timestamped copy of the old file on the host, which has saved more than one "what did it look like before?" incident review.- Templates run on the control node; only the rendered bytes cross SSH. A Jinja error is a local bug, and it fails the task before anything touches the target.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.