ansible/playbooks/utils.yml
2026-10-11 23:02:48 +02:00

379 lines
13 KiB
YAML

---
# Baseline for every machine, plus an opt-in system upgrade.
# Settings: inventories/group_vars/all/utils.yml.
#
# ansible-playbook playbooks/utils.yml -CD # dry run first
# ansible-playbook playbooks/utils.yml
# ansible-playbook playbooks/utils.yml --tags ssh,motd # only some parts
# ansible-playbook playbooks/utils.yml --tags upgrade -l lxc
# ansible-playbook playbooks/utils.yml --tags upgrade -l k3s_workers -e utils_reboot=true
#
# Tags: apt, packages, locale, time, journald, disk, ssh, hostname, motd,
# proxmox, docker, upgrade (opt-in).
#
# LXC vs VM:
# - hostname: an LXC's hostname lives in its Proxmox config (pct set), which
# rewrites /etc/hostname and /etc/hosts at every start. A VM's lives inside it.
# - NTP, fstrim, guest agent: VMs only. LXCs use the host's clock and kernel.
# - reboot after an upgrade: VMs only. LXCs run the host's kernel.
- name: Baseline
hosts: all
gather_facts: true
gather_subset: [min]
vars:
utils_mirror_rewrites:
- from: https?://deb\.debian\.org/debian(?=[/\s]|$)
to: http://prism.viarezo.fr/debian
- from: https?://security\.debian\.org(/debian-security)?(?=[/\s]|$)
to: http://prism.viarezo.fr/debian-security
- from: https?://([a-z]{2}\.)?archive\.ubuntu\.com/ubuntu(?=[/\s]|$)
to: http://prism.viarezo.fr/ubuntu
- from: https?://security\.ubuntu\.com/ubuntu(?=[/\s]|$)
to: http://prism.viarezo.fr/ubuntu
handlers:
- name: Restart journald
ansible.builtin.systemd_service:
name: systemd-journald
state: restarted
tasks:
# ---------------------------------------------------------------- apt
- name: Find apt source files
ansible.builtin.find:
paths: [/etc/apt, /etc/apt/sources.list.d]
patterns: ["sources.list", "*.list", "*.sources"]
register: utils_apt_files
tags: [apt]
- name: Point Debian/Ubuntu sources at the ViaRézo mirror
ansible.builtin.replace:
path: "{{ item.0.path }}"
regexp: "{{ item.1.from }}"
replace: "{{ item.1.to }}"
loop: "{{ utils_apt_files.files | product(utils_mirror_rewrites) | list }}"
loop_control:
label: "{{ item.0.path }}: {{ item.1.to }}"
register: utils_mirror
tags: [apt]
# ----------------------------------------------------------- packages
- name: Install admin tools
ansible.builtin.apt:
name: "{{ utils_packages }}"
state: present
install_recommends: false
update_cache: true
cache_valid_time: "{{ 0 if utils_mirror is changed else 3600 }}"
tags: [packages]
- name: Install the QEMU guest agent (VMs only)
ansible.builtin.apt:
name: qemu-guest-agent
state: present
install_recommends: false
when: host_type == 'vm'
tags: [packages]
- name: Start the QEMU guest agent (VMs only)
ansible.builtin.systemd_service:
name: qemu-guest-agent
state: started
# The unit has no [Install] section: udev starts it when the virtio port shows up.
when: host_type == 'vm' and not ansible_check_mode
tags: [packages]
# ------------------------------------------------------------- locale
- name: Install the locales package
ansible.builtin.apt:
name: locales
state: present
tags: [locale]
- name: Generate locales
community.general.locale_gen:
name: "{{ utils_locales }}"
state: present
# In a dry run, the locales package may not be installed yet.
ignore_errors: "{{ ansible_check_mode }}"
tags: [locale]
# --------------------------------------------------------------- time
- name: Set the timezone
community.general.timezone:
name: "{{ utils_timezone }}"
when: utils_timezone is defined
tags: [time]
- name: List services (VMs only)
ansible.builtin.service_facts:
when: host_type in ['vm', 'external']
tags: [time]
# Ubuntu and the ViaRézo VM run chrony, VM 107 systemd-timesyncd: keep
# whichever is there, install timesyncd only when nothing syncs the clock.
- name: Install systemd-timesyncd where no NTP client runs (VMs only)
ansible.builtin.apt:
name: systemd-timesyncd
state: present
when:
- host_type in ['vm', 'external']
- ansible_facts.services | dict2items
| selectattr('key', 'in', ['chrony.service', 'systemd-timesyncd.service', 'ntpsec.service'])
| selectattr('value.state', '==', 'running') | list | length == 0
tags: [time]
# ------------------------------------------------------- journald, disk
- name: Cap the journal size
ansible.builtin.copy:
dest: /etc/systemd/journald.conf.d/size.conf
content: |
[Journal]
SystemMaxUse={{ utils_journald_max_use }}
owner: root
group: root
mode: "0644"
notify: Restart journald
tags: [journald]
- name: Trim free space on VM disks weekly (VMs only)
ansible.builtin.systemd_service:
name: fstrim.timer
enabled: true
state: started
when: host_type in ['vm', 'external']
tags: [disk]
# ----------------------------------------------------------------- ssh
- name: Harden sshd
tags: [ssh]
block:
- name: Write the sshd drop-in
ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/10-hardening.conf
content: |
# Managed by Ansible (utils.yml). Keys only; root by key only.
{% for k, v in utils_sshd_settings.items() %}
{{ k }} {{ v }}
{% endfor %}
owner: root
group: root
mode: "0644"
register: utils_sshd_dropin
# sshd -t needs it, and it's missing while only ssh.socket is active.
- name: Create the sshd privilege separation directory
ansible.builtin.file:
path: /run/sshd
state: directory
owner: root
group: root
mode: "0755"
when: utils_sshd_dropin is changed
- name: Test the whole sshd config
ansible.builtin.command: /usr/sbin/sshd -t
changed_when: false
when: utils_sshd_dropin is changed and not ansible_check_mode
- name: Reload sshd
ansible.builtin.systemd_service:
name: ssh
state: reloaded
when: utils_sshd_dropin is changed
rescue:
- name: Remove the drop-in that broke the sshd config
ansible.builtin.file:
path: /etc/ssh/sshd_config.d/10-hardening.conf
state: absent
- name: Stop on this host
ansible.builtin.fail:
msg: "sshd -t failed with the hardening drop-in, so it was removed and sshd not reloaded."
# ------------------------------------------------------------ hostname
# The inventory name is the hostname. k3s nodes and the Proxmox host are
# only checked: renaming them renames the k8s node / breaks the PVE node.
- name: Refuse to rename a k3s node or the Proxmox host
ansible.builtin.assert:
that: ansible_facts.hostname == inventory_hostname
fail_msg: "{{ inventory_hostname }} is called {{ ansible_facts.hostname }}. Rename it by hand, not with Ansible."
quiet: true
when: host_type == 'proxmox' or inventory_hostname in groups['k3s']
tags: [hostname]
# The hostname module updates ansible_facts.hostname, so keep the old name.
- name: Remember the current hostname
ansible.builtin.set_fact:
utils_old_hostname: "{{ ansible_facts.hostname }}"
tags: [hostname]
- name: Rename the guest
when:
- utils_old_hostname != inventory_hostname
- host_type != 'proxmox' and inventory_hostname not in groups['k3s']
tags: [hostname]
block:
- name: Set the hostname in the LXC's Proxmox config
ansible.builtin.command: pct set {{ proxmox_vmid }} --hostname {{ inventory_hostname }}
delegate_to: "{{ groups['hypervisors'] | first }}"
changed_when: true
when: host_type == 'lxc'
- name: Look for cloud-init
ansible.builtin.stat:
path: /etc/cloud/cloud.cfg
register: utils_cloudinit
# cloud-init (ViaRézo VM) would put the old name back at boot.
- name: Keep cloud-init from resetting the hostname
ansible.builtin.copy:
dest: /etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg
content: "preserve_hostname: true\n"
owner: root
group: root
mode: "0644"
when: utils_cloudinit.stat.exists
- name: Set the hostname now
ansible.builtin.hostname:
name: "{{ inventory_hostname }}"
- name: Rename the old hostname in /etc/hosts
ansible.builtin.replace:
path: /etc/hosts
regexp: (?<![\w.-]){{ utils_old_hostname | regex_escape }}(?![\w.-])
replace: "{{ inventory_hostname }}"
# ---------------------------------------------------------------- motd
- name: Write the motd
ansible.builtin.template:
src: motd.j2
dest: /etc/motd
owner: root
group: root
mode: "0644"
tags: [motd]
- name: Proxmox host
hosts: hypervisors
gather_facts: false
tags: [proxmox]
tasks:
# The file was fully commented out, so the host got no PVE updates at all.
- name: Enable the pve-no-subscription repository
ansible.builtin.copy:
dest: /etc/apt/sources.list.d/proxmox.sources
content: |
Types: deb
URIs: http://download.proxmox.com/debian/pve
Suites: trixie
Components: pve-no-subscription
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
owner: root
group: root
mode: "0644"
register: utils_pve_repo
- name: Refresh apt
ansible.builtin.apt:
update_cache: true
when: utils_pve_repo is changed
# WireGuard on udp/443 for networks that block 51820. Live since
# 2026-10-11 but never saved, so a reboot would drop it.
- name: Forward udp/443 to the WireGuard hub (live)
ansible.builtin.iptables:
table: nat
chain: PREROUTING
in_interface: vmbr0
protocol: udp
match: [udp]
destination_port: "443"
jump: DNAT
to_destination: 10.0.0.250:51820
- name: Forward udp/443 to the WireGuard hub (rules.v4)
ansible.builtin.lineinfile:
path: /etc/iptables/rules.v4
line: -A PREROUTING -i vmbr0 -p udp -m udp --dport 443 -j DNAT --to-destination 10.0.0.250:51820
insertafter: ^-A PREROUTING -i vmbr0 -p udp -m udp --dport 51820 -j DNAT
- name: Docker hosts
hosts: all:!hypervisors:!k3s
gather_facts: false
tags: [docker]
tasks:
- name: Look for Docker
ansible.builtin.stat:
path: /usr/bin/docker
register: utils_docker
# Dangling images only (old layers left by updates). `prune -a` would also
# delete images no container uses right now, like Overleaf's 9 GB TeX Live
# image that only throwaway compile containers use, and break compiles.
- name: Prune dangling Docker images weekly
ansible.builtin.copy:
dest: /etc/cron.weekly/docker-prune
content: |
#!/bin/sh
# Managed by Ansible (utils.yml)
docker image prune -f >/dev/null
docker builder prune -f >/dev/null
owner: root
group: root
mode: "0755"
when: utils_docker.stat.exists
- name: Upgrade
hosts: all:!hypervisors
gather_facts: false
serial: "{{ utils_serial | default(1) }}"
tags: [upgrade, never]
tasks:
- name: Refuse to upgrade everything at once
ansible.builtin.assert:
that: ansible_limit is defined
fail_msg: "Pick the hosts with --limit (e.g. -l lxc, -l k3s_workers, -l jellyfin)."
run_once: true
- name: Upgrade packages
ansible.builtin.apt:
upgrade: full
update_cache: true
autoremove: true
- name: Check whether a reboot is needed
ansible.builtin.stat:
path: /var/run/reboot-required
register: utils_reboot_required
- name: Reboot (VMs only, with -e utils_reboot=true)
ansible.builtin.reboot:
reboot_timeout: 600
when:
- utils_reboot_required.stat.exists
- host_type == 'vm'
- utils_reboot | default(false) | bool
- name: Wait for the k3s node to be Ready again
ansible.builtin.command: k3s kubectl wait --for=condition=Ready node/{{ inventory_hostname }} --timeout=300s
delegate_to: "{{ groups['k3s_masters'] | first }}"
changed_when: false
when:
- utils_reboot_required.stat.exists
- inventory_hostname in groups['k3s']
- utils_reboot | default(false) | bool
- name: Report a pending reboot
ansible.builtin.debug:
msg: >-
{{ inventory_hostname }} ({{ host_type }}) wants a reboot.
{{ 'Rerun with -e utils_reboot=true.' if host_type == 'vm'
else 'LXC: restart the services instead (needrestart), or pct reboot from the host if needed.' if host_type == 'lxc'
else 'Reboot it by hand.' }}
when:
- utils_reboot_required.stat.exists
- not (host_type == 'vm' and utils_reboot | default(false) | bool)