Files
infra/ansible/playbooks/pve-gitea.yml
T
DmitryandClaude Sonnet 5 a3fe8031fe feat: migrate all managed LXC provisioning to OpenTofu (blue-green)
Blue-green: a new container is created beside the old one, data is copied, the
IP is moved onto it, and the old container is kept stopped as rollback for at
least a week. Keeping the IP means only the VMID changes, and its consumers
(backup jobs, backup audit) already derive it from the registry.

Batch 1 (2026-09-02): emergency-bot 148->151, docker-test 145->152,
gitea 141->153, vaultwarden 140->154, monitoring 146->155, gyro 150->156,
grimmory 149->157.
Batch 2 (2026-09-03): adguard 144->158, mihomo 143->159, ovpn-mini 132->160.
All migratable LXC are now provisioner: tofu. hermes-ai (frozen) and pbs stay.

- tofu/services.tf + tofu/svc-*.tf: one resource per service, reproducing the
  pct-config etalon. /dev/fuse -> features.fuse; /dev/net/tun ->
  device_passthrough (first live use on mihomo and ovpn-mini); gitea bind mount
  -> datastore volume (data finally reaches PBS); console { type = "shell" }
  declared explicitly (provider tracks cmode there).
- services.yml: vmid + provisioner: tofu for every migrated service; features
  strings and device notes updated to the tofu representation; also drops the
  memoir-bot entry and adds homelab_reverse_proxy_image/_unit.
- pve-*.yml: configuration play target is `{{ pve_config_target | default(...) }}`
  so it can run against <name>-new on a temp address (a bare --limit zeroes the
  play instead of retargeting it). Container-creation plays are gated behind
  `provisioner != 'tofu'` / `pve_provisioning_enabled` (meta: end_play), so a
  stray run cannot pct start a stopped OLD VMID on a live IP. Override for
  intentional legacy rollback: -e pve_<svc>_legacy_provisioning_enabled=true.
- ssh_config: drop memoir-bot; ovpn-mini gets ProxyJump none (a jump via ru-vps
  would route through the very tunnel ovpn-mini terminates).
- gyro.yml / uptime-kuma.yml: same pve_config_target override.
- roles/uptime_kuma: only freeze homelab-monitoring when the unit actually
  exists (a fresh blue-green container never had it).
- offsite-restic-yadisk.yml: the gitea restic profile now runs inside the LXC
  (hosts: gitea), since the bind-mount host path is gone after the volume move;
  lost+found excluded (unreadable in an unprivileged LXC, restic exit 3).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012uoq5AVK8mkBgg83Mq6o5V
2026-09-03 07:05:46 +03:00

245 lines
8.3 KiB
YAML

- name: Create Gitea LXC on cloud-pc
hosts: cloud-pc
gather_facts: false
pre_tasks:
- name: Skip legacy Gitea provisioning for runtime-only calls
ansible.builtin.meta: end_play
when: not (pve_provisioning_enabled | default(true) | bool)
vars:
gitea_vmid: 141
gitea_hostname: gitea
gitea_ip: 192.168.1.25/24
gitea_gateway: 192.168.1.1
gitea_bridge: vmbr0
gitea_rootfs: data:32
gitea_host_data_dir: /opt/data/gitea
gitea_host_data_uid: 101000
gitea_host_data_gid: 101000
gitea_container_data_dir: /opt/gitea/data
gitea_ostemplate: local:vztmpl/debian-13-standard_13.1-2_amd64.tar.zst
gitea_pubkey_file: ~/.ssh/id_ed25519_homelab.pub
handlers:
- name: restart gitea lxc
ansible.builtin.shell: "pct stop {{ gitea_vmid }} || true; pct start {{ gitea_vmid }}"
changed_when: true
tasks:
- name: Check if Gitea LXC exists
ansible.builtin.command: "pct config {{ gitea_vmid }}"
register: gitea_pct_config
changed_when: false
failed_when: false
- name: Refuse to modify a foreign Gitea VMID
ansible.builtin.assert:
that:
- gitea_pct_config.rc != 0 or gitea_existing_hostname == 'gitea'
fail_msg: VMID {{ gitea_vmid }} already exists and is not the Gitea container.
vars:
gitea_existing_hostname: >-
{{ gitea_pct_config.stdout_lines
| select('match', '^hostname: ')
| map('regex_replace', '^hostname: ', '')
| first
| default('') }}
- name: Install Gitea LXC SSH public key on PVE host
ansible.builtin.copy:
dest: /tmp/gitea-lxc.pub
owner: root
group: root
mode: "0600"
content: "{{ lookup('file', gitea_pubkey_file) }}\n"
when: gitea_pct_config.rc != 0
- name: Create Gitea LXC
ansible.builtin.command: >-
pct create {{ gitea_vmid }} {{ gitea_ostemplate }}
--hostname {{ gitea_hostname }}
--rootfs {{ gitea_rootfs }}
--cores 2
--memory 2048
--swap 1024
--net0 name=eth0,bridge={{ gitea_bridge }},gw={{ gitea_gateway }},ip={{ gitea_ip }},firewall=1
--nameserver 1.1.1.1
--unprivileged 1
--features nesting=1,keyctl=1
--onboot 1
--startup order=50
--cmode shell
--ssh-public-keys /tmp/gitea-lxc.pub
when: gitea_pct_config.rc != 0
- name: Start Gitea LXC
ansible.builtin.command: "pct start {{ gitea_vmid }}"
register: gitea_pct_start
changed_when: gitea_pct_start.rc == 0
failed_when: gitea_pct_start.rc not in [0, 255]
- name: Allow FUSE device in Gitea LXC config
ansible.builtin.lineinfile:
path: "/etc/pve/lxc/{{ gitea_vmid }}.conf"
line: "lxc.cgroup2.devices.allow: c 10:229 rwm"
state: present
notify: restart gitea lxc
- name: Bind mount FUSE device in Gitea LXC config
ansible.builtin.lineinfile:
path: "/etc/pve/lxc/{{ gitea_vmid }}.conf"
line: "lxc.mount.entry: /dev/fuse dev/fuse none bind,create=file"
state: present
notify: restart gitea lxc
- name: Bind mount Gitea data directory in LXC config
ansible.builtin.lineinfile:
path: "/etc/pve/lxc/{{ gitea_vmid }}.conf"
line: "mp0: {{ gitea_host_data_dir }},mp={{ gitea_container_data_dir }}"
state: present
notify: restart gitea lxc
- name: Ensure Gitea host data directory ownership matches unprivileged LXC uid map
ansible.builtin.file:
path: "{{ gitea_host_data_dir }}"
state: directory
owner: "{{ gitea_host_data_uid }}"
group: "{{ gitea_host_data_gid }}"
recurse: true
- name: Apply pending LXC config changes
ansible.builtin.meta: flush_handlers
- name: Wait for Gitea SSH through ru-vps
ansible.builtin.wait_for_connection:
timeout: 120
delegate_to: gitea
vars:
ansible_become: false
- name: Configure Docker and Gitea inside LXC
# Таргет переопределяем ради blue-green переезда на OpenTofu: во время
# миграции этот play нужно прогнать против нового контейнера на временном
# адресе. Просто `--limit gitea-new` для этого НЕ годится — лимит
# пересекается с паттерном play и даёт ноль хостов, а не перенацеливание
# (проверено 2026-09-02 через --list-hosts на всех плейбуках).
# Использовать вместе с --limit, чтобы play создания контейнера отсеялся:
# ansible-playbook playbooks/pve-gitea.yml \
# -e pve_config_target=gitea-new --limit gitea-new
# По умолчанию поведение не меняется.
hosts: "{{ pve_config_target | default('gitea') }}"
gather_facts: true
vars:
ansible_become: false
gitea_data_dir: /opt/gitea/data
gitea_image: gitea/gitea:1.27.1@sha256:b64126cf5c3f4e5f0f231b510bb13715f6cb8e508188b44de90bdb9a04f3055d
gitea_container_name: gitea
gitea_http_port: 3000
gitea_ssh_port: 2222
tasks:
- name: Install Docker packages
ansible.builtin.apt:
name:
- docker.io
- fuse-overlayfs
- sqlite3
- rsync
- ca-certificates
- curl
state: present
update_cache: true
- name: Ensure Docker config directory exists
ansible.builtin.file:
path: /etc/docker
state: directory
owner: root
group: root
mode: "0755"
- name: Configure Docker storage driver for unprivileged LXC
ansible.builtin.copy:
dest: /etc/docker/daemon.json
owner: root
group: root
mode: "0644"
content: |
{
"storage-driver": "fuse-overlayfs"
}
register: docker_daemon_config
- name: Ensure Docker service is enabled and running
ansible.builtin.systemd:
name: docker
state: "{{ 'restarted' if docker_daemon_config.changed else 'started' }}"
enabled: true
- name: Ensure Gitea data directory has container ownership
ansible.builtin.file:
path: "{{ gitea_data_dir }}"
state: directory
owner: "1000"
group: "1000"
mode: "0750"
- name: Check if the configured Gitea image is present
ansible.builtin.command: "docker image inspect {{ gitea_image }}"
register: gitea_image_inspect
changed_when: false
failed_when: false
- name: Pull the configured Gitea image
ansible.builtin.command: "docker pull {{ gitea_image }}"
when: gitea_image_inspect.rc != 0
register: gitea_image_pull
changed_when: true
- name: Install Gitea systemd unit
ansible.builtin.copy:
dest: /etc/systemd/system/gitea.service
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Gitea container
After=docker.service
Requires=docker.service
[Service]
Restart=always
RestartSec=10
ExecStartPre=-/usr/bin/docker rm -f {{ gitea_container_name }}
ExecStart=/usr/bin/docker run --rm \
--name {{ gitea_container_name }} \
--pull never \
-p {{ gitea_http_port }}:3000 \
-p {{ gitea_ssh_port }}:22 \
-v {{ gitea_data_dir }}:/data \
-e USER_UID=1000 \
-e USER_GID=1000 \
{{ gitea_image }}
ExecStop=/usr/bin/docker stop {{ gitea_container_name }}
[Install]
WantedBy=multi-user.target
register: gitea_unit
- name: Reload systemd when Gitea unit changes
ansible.builtin.systemd:
daemon_reload: true
when: gitea_unit.changed
- name: Enable and start Gitea
ansible.builtin.systemd:
name: gitea
state: "{{ 'restarted' if gitea_unit.changed or gitea_image_pull.changed else 'started' }}"
enabled: true
- name: Wait for Gitea HTTP health endpoint
ansible.builtin.uri:
url: "http://127.0.0.1:{{ gitea_http_port }}/api/healthz"
status_code: 200
register: gitea_health
retries: 24
delay: 5
until: gitea_health.status == 200