Infrastructure as code: Ansible for Linux and Windows
The entire configuration of my Proxmox lab turned into version-controlled code: a single command left any machine installed, configured and hardened. The same repository managed Linux containers and VMs over SSH and Windows Server over WinRM, with hardening applied in two phases and named per-person accounts (secrets encrypted with Ansible Vault) kept separate from the service account used by the automation itself.
A project from my personal lab, which is currently paused: this write-up describes how it was built and how it worked.
Context
Every time I created an LXC container or a VM on my Proxmox host I repeated the same ritual by hand: update, install the same packages, set locales and time zone, set up fail2ban, create users, harden SSH... Fifteen minutes of identical commands with results that were never quite identical — each machine ended up slightly different depending on the day I installed it.
The solution has had a name for years: infrastructure as code. Configuration is not run, it is declared in version-controlled files, and a tool makes sure reality matches what has been declared. I built the project with Ansible on a minimal management container (1 vCPU, 1 GB of RAM) acting as the single point of administration — and once the model worked on Linux, I extended it to Windows Server, because real-world infrastructure is mixed.
Design
A dedicated management node
A lightweight LXC container holds Ansible and the only private key with access to the other machines. All administration of the lab went out from that point, auditable and isolated. Managed machines need no agent installed: Linux is administered over SSH and Windows over WinRM, both native.
Roles with the standard structure
Each piece of configuration is a role created with ansible-galaxy init, which generates the standard skeleton (tasks, handlers, defaults, vars, meta...). Only what the role needs is filled in — at a minimum tasks/main.yml (the tasks), and optionally defaults/main.yml (variables with default values, which is what makes the role reusable) and handlers/main.yml (actions triggered only if something changed, such as restarting a service). The remaining folders stay empty and Ansible ignores them.
Grouped inventory + a single entry point
The inventory sorts machines into three groups: linux (Debian/Ubuntu/Kali containers and VMs...), windows (Server, Windows 11) and homelab (the Proxmox node, which gets special treatment). site.yml maps groups to roles: Linux gets base + usuario_ansible + hardening_ssh; Windows gets base_windows; the node gets base and user but no hardening (a deliberate decision: it is the machine whose plan B is the physical console). Adding a new machine is one line in the inventory and one command.
One model, two worlds
Windows is not managed over SSH but over WinRM (port 5985, enabled with Enable-PSRemoting), and it has its own modules: win_timezone, win_updates, win_reboot... But the mental model is identical: declare state, do not run commands. The Windows role even decides for itself whether it needs to reboot after installing updates (register + when). Same idempotence, same repository, same recap.
Conditional tasks
Not everything applies to every machine: chrony cannot adjust the clock inside an LXC container (it has no clock of its own and uses the host's) and qemu-guest-agent only makes sense on VMs. Tasks use when on the "facts" Ansible gathers from each machine (ansible_virtualization_type): one role, the right behaviour on each type of machine.
Named accounts alongside the service account
usuario_ansible is a service account: it is used only by the management node to run playbooks, with passwordless sudo because no human is typing at that point. For human access, a separate role (usuario_hugo) creates a named account per person: on Linux, with its own SSH key and sudo that does ask for a password; on Windows, the same principle with a different mechanism — win_user creates a local account in the administrators group with its own password (WinRM does not use keys). The underlying reason is traceability: if everyone logs in as ansible or as Administrator, the logs cannot tell who did what. With Ansible Vault encrypting passwords and hashes, and the list of keys growing per person (not per machine), adding someone new is one line, not a redeploy.
Published on GitHub
The whole project is version-controlled with Git and published for reference. The inventory in the repository contains example IP addresses and credentials; the real values exist only on the management node.
Selective runs
Day-to-day work is not "provision everything": it is touching one group or a single machine. That is what --limit is for; it intersects with the groups in site.yml — each machine gets only the roles that apply to it:
# The whole lab (Linux + Windows + node): ansible-playbook site.yml # Linux machines only: ansible-playbook site.yml --limit linux # Windows machines only: ansible-playbook site.yml --limit windows # One specific machine: ansible-playbook site.yml --limit test-debian # Dry run without touching anything (what would change): ansible-playbook site.yml --limit windows --check # Any run that touches encrypted variables needs the vault password: ansible-playbook site.yml --limit linux --ask-vault-pass
Problems along the way
Problem 1 — fail2ban died on start-up in the LXC containers
The playbook installed and started fail2ban without errors, but on every run the task came back as changed — a sign that Ansible kept finding it stopped. journalctl -u fail2ban revealed the cause: Have not found any log file for sshd jail. Minimal Debian 12 containers do not ship with rsyslog, so /var/log/auth.log does not exist and fail2ban gave up when it could not find it.
jail.local in the role with backend = systemd (plus python3-systemd): fail2ban reads the journal directly instead of looking for log files. The fix is now encoded in the role — no future machine will have this problem again.
Problem 2 — The chicken-and-egg of hardening
The goal was to administer everything with a dedicated user and forbid root logins over SSH. But the dedicated user is created by the playbook itself... connecting as root. If you close root too early, you lock yourself out of your own machine — as I found out when Ansible returned Permission denied against my own test VM.
visudo -cf); a manual check that the door opens; and only then a second phase that closes the old one and switches the inventory to the new user. Rule learned: never close one door without having tried the other.
Problem 3 — The Windows installer could not see the disk
The Windows Server VM was created with paravirtualised hardware (VirtIO SCSI, VirtIO network), which is the efficient choice on Proxmox — but Windows does not ship with those drivers, so the installer reached the disk selection screen and showed an empty list: as far as Windows was concerned, the disk did not exist.
virtio-win.iso on another. From the installer itself, "Load driver" → VirtIO drive → SCSI driver, and the disk appears. After installation, the full driver package + qemu-guest-agent from that same ISO, which also lets Proxmox see the VM's IP address and shut it down cleanly.
Problem 4 — Ansible would not start: locales
Midway through the project, Ansible stopped starting, with unsupported locale setting. SSH from my own machine was forwarding es_ES.UTF-8 to the management container, which did not have that locale generated, and Python aborted before running anything.
locale_gen task in the base role — the problem was declared and solved for every machine in one go.
Problem 5 — group_vars: a file and a folder with the same name cannot coexist
When I split the ordinary and secret Windows variables (group_vars/windows.yml + group_vars/windows_vault.yml), ansible_password disappeared with no error at all — WinRM failed with "auth method basic requires a password" as if the vault did not exist. It happened again later with group_vars/all.yml: one variable resolved fine and the other did not, with no apparent pattern.
group_vars rule is strict — either a single <group>.yml file, or a <group>/ folder with several files inside, never both for the same group. A standalone windows_vault.yml was treated as variables for a group literally called windows_vault, which does not exist in any inventory — it was silently ignored, with no warning from Ansible.
group_vars/windows/vars.yml + group_vars/windows/vault.yml, group_vars/all/vars.yml + group_vars/all/vault.yml. Ansible automatically loads everything it finds inside the folder.
Problem 6 — win_user failed: the "Administrators" group does not exist in Spanish
When creating the hugo account on Windows with win_user, the task failed with group 'Administrators' not found — even though the user did get created. The cause: the local administrators group has a different name depending on the Windows installation language, and this VM is in Spanish.
Administradores, not Administrators. The task is idempotent, so retrying did not duplicate the user; it simply completed what was missing (adding it to the group).
Problem 7 — Provisioning a Terraform-built machine for the first time exposed two new Ansible limits
With Terraform now creating containers and VMs directly, provisioning the first new machine (ttyd) end to end ran into two Ansible behaviours that had never shown up on machines created by hand.
ansible_user: ansible in group_vars points to an account created by the usuario_ansible role itself — which has not yet run on a freshly created machine. Trying to force root with -u root on the command line achieved nothing: -u has low precedence, and any ansible_user defined in group_vars overrides it regardless.
-e ansible_user=root (extra vars) for the first contact — -e does take precedence over group_vars. It is only needed that once: as soon as usuario_ansible creates the real account, subsequent runs go back to the normal default.
--skip-tags gives no warning if the tag does not exist. site.yml had never had tags: on its roles — a --skip-tags hardening_ssh found nothing to skip and ran the whole playbook, hardening included, with no error or warning. The machine ended up with root SSH access closed without anyone having asked for it.
{ role: hardening_ssh, tags: [hardening_ssh] }), and checking with --check that the filter really works before trusting it — skipped tasks must show as skipping, not ok/changed. Reverting what had been applied in excess was simple (putting PermitRootLogin/PasswordAuthentication back by hand on that machine), but the real warning is not to trust a flag that was never verified.
Outcome
Adding a machine to the lab — Linux or Windows — went from fifteen minutes of manual commands to one line in the inventory and one command. Every machine ended up in an identical, verifiable state: on Linux, nobody logs in over SSH with a password, root cannot log in even with a key, fail2ban watches for attempts and security patches are applied automatically; on Windows, security updates installed and an automatic reboot only if needed. Each person logs in with their own account and their own key — the logs show who did what, not just that "ansible" did it. All from a single, audited management point.
And if the mini PC dies tomorrow, the configuration of the whole lab does not die with it: it is in the repository.
Once Terraform came into play, the loop closed completely: a machine is born declared in code and leaves here configured and hardened — ttyd was the first to go the whole way, from nothing to a running service, without a single manual step in between.
Lessons learned
changed on every run is not a cosmetic detail — it is a service dying in a loop.group_vars does not warn you when you misuse it: a file and a folder with the same group name raise no error, one of the two is simply ignored. If a variable "disappears" for no apparent reason, it is the first place to look.--check is not reliable for chains of dependent tasks: if task 1 is simulated (user created) rather than actually run, task 2 (authorising their key) may fail because it depends on something that never came to exist in simulation mode. It is not a bug in the playbook, it is a known limit of --check mode itself.-u loses to ansible_user in group_vars; to really force a user (first contact with a new machine) you need -e, which does take precedence.--check before trusting a new --skip-tags, always.Quick notes
A day-to-day reference — so there is no need to go and look it up in the repository.
Dry run without applying changes
# What would change, without touching anything: ansible-playbook site.yml --check --diff # Just check the YAML is valid, without connecting to any machine: ansible-playbook site.yml --syntax-check
Add a new machine to the inventory
If it was created by hand: one line in inventory.ini, under the relevant group ([linux], [windows] or [homelab]). If it comes from Terraform, nothing needs touching — you point straight at the inventory it generates on every apply:
ansible-playbook site.yml --limit nombre_maquina_nueva ansible-playbook site.yml -i ../homelab-terraform/inventory_generado.ini --limit nombre_maquina_nueva
On a machine freshly created by Terraform, the management user does not exist yet — the first contact needs -e ansible_user=root (see Problems, above).
Secrets with Ansible Vault
# Encrypt a variables file: ansible-vault encrypt group_vars/all/vault.yml # Edit it (decrypts, opens the editor, re-encrypts on save): ansible-vault edit group_vars/all/vault.yml # Run a playbook that uses encrypted variables: ansible-playbook site.yml --ask-vault-pass
Run only part of it (tags and roles)
Each role carries its own tag, with the same name — base, usuario_ansible, usuario_hugo, hardening_ssh, base_windows:
# One specific role only: ansible-playbook site.yml --tags usuario_hugo # Everything except that one: ansible-playbook site.yml --skip-tags hardening_ssh # Resume from a specific task if something failed midway: ansible-playbook site.yml --start-at-task="Instalar fail2ban"
A tag that does not exist in site.yml raises no error — --tags/--skip-tags simply match nothing, and the playbook runs in full as if the flag were not there. Do a dry run before trusting a new filter:
ansible-playbook site.yml --limit <host> --skip-tags hardening_ssh --check --ask-vault-pass
The skipped role's tasks must appear as skipping, not ok/changed.
The correct group_vars structure
Never a <group>.yml file and a <group>/ folder at the same time for the same group — one of the two is ignored without warning. If you separate ordinary variables from vault secrets, put everything inside the folder:
group_vars/ ├── all/ │ ├── vars.yml # ordinary variables, in clear text │ └── vault.yml # secrets, encrypted └── windows/ ├── vars.yml └── vault.yml
Add a new person (usuario_hugo)
One more key in the list in group_vars/all/vars.yml (or create that person's variable if it is the first time) and run the playbook again — the role does not need touching.
hugo_ssh_pubkeys: - "ssh-rsa AAAA... clave-portatil" - "ssh-rsa AAAA... clave-casa"
The sudo password hash, always encrypted in group_vars/all/vault.yml, never in clear text:
openssl passwd -6 # prompts for the password and returns the SHA-512 hash
win_user and the administrators group on non-English Windows
The name of the local group depends on the Windows installation language — in Spanish it is Administradores, not Administrators. To check inside the VM if it fails:
Get-LocalGroup | Select-Object Name
View the code
The whole project — roles, playbooks and documentation — is public: