Feature: Add Ansible foundation and connectivity check #2

Merged
claude-bot Bot merged 2 commits from feature/add-ansible-foundation into main 2026-11-26 01:33:32 +01:00
15 changed files with 491 additions and 0 deletions

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Stop hook: makes Claude fix lint errors before it can finish a reply.
#
# When YAML files have uncommitted changes, run yamllint and ansible-lint from
# .venv. On failure, exit 2 sends the errors back to Claude. It never contacts a
# host. If .venv doesn't exist it does nothing, and CI still runs both linters.
input=$(cat)
# Set when Claude is already continuing because of this hook; stopping here
# prevents an endless loop if it can't fix the error.
[[ "$(jq -r '.stop_hook_active // false' <<<"$input")" == "true" ]] && exit 0
cd "$CLAUDE_PROJECT_DIR" || exit 0
[[ -x .venv/bin/yamllint && -x .venv/bin/ansible-lint ]] || exit 0
# -uall lists files inside new folders, not just the folder.
git status --porcelain -uall | grep -qE '\.ya?ml$|\.j2$|\.ansible-lint$' || exit 0
failed=0
for check in ".venv/bin/yamllint --strict ." ".venv/bin/ansible-lint"; do
if ! out=$($check 2>&1); then
echo "'$check' failed, fix before finishing:" >&2
tail -n 30 <<<"$out" >&2
failed=1
fi
done
[[ $failed -eq 1 ]] && exit 2
exit 0
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# PreToolUse hook for Bash: forces a permission prompt before any command that
# can reach or change a live host. The ask rules in .claude/settings.json match
# the command text as Claude usually writes it; this catches the same commands
# when they are wrapped (sh -c '...', env VAR=x ..., absolute paths).
set -euo pipefail
input=$(cat)
cmd=$(jq -r '.tool_input.command // empty' <<<"$input")
[ -z "$cmd" ] && exit 0
[[ $cmd =~ ^ansible[[:space:]]+--version[[:space:]]*$ ]] && exit 0
# A tool name must start a word. "/" is allowed before it to catch absolute
# paths, "-" is not, so the folder name homelab-ansible doesn't match.
start='(^|[^[:alnum:]_.-])'
end="([[:space:]\"')]|\$)"
ansible_re="${start}(ansible-playbook|ansible-pull|ansible-console|ansible-vault|ansible)[[:space:]]"
remote_re="${start}(ssh|scp|sftp|rsync)[[:space:]]"
proxmox_re="${start}(pct|qm|pvesh|pvesm|vzdump)[[:space:]]"
docker_re="${start}docker([[:space:]]+compose)?[[:space:]]+([^|;&]*[[:space:]])?(up|down|start|stop|restart|kill|rm|rmi|run|exec|pull|push|create|build|prune|cp|update|rename|pause|unpause|volume|network|system)$end"
what=""
if [[ $cmd =~ $ansible_re ]]; then
what="${BASH_REMATCH[2]}"
elif [[ $cmd =~ $remote_re ]]; then
what="${BASH_REMATCH[2]} to a host"
elif [[ $cmd =~ $proxmox_re ]]; then
what="${BASH_REMATCH[2]} on Proxmox"
elif [[ $cmd =~ $docker_re ]]; then
what="docker ${BASH_REMATCH[4]}"
fi
[ -z "$what" ] && exit 0
reason="Live infrastructure: '$what'. Approve only if you want Claude to run this instead of running it yourself."
jq -n --arg reason "$reason" '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "ask",
permissionDecisionReason: $reason
}
}'
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Gitea API helper so Claude Code can work with pull requests.
#
# Why: the remote is a self-hosted Gitea, so the GitHub CLI `gh` doesn't work.
# This script calls the Gitea API instead, as the claude-bot account, so PRs
# show up as the bot's work and it only has the rights you gave it.
#
# Scope: used for PRs only (list, open, check CI status, merge after your OK).
# Technically it can call any endpoint; CLAUDE.md limits its use to PRs.
# In .claude/settings.json, GET and POST (e.g. opening a PR) run without a
# prompt. Merging a PR (POST .../merge), PATCH, PUT and DELETE always ask first.
#
# Usage: gitea.sh METHOD PATH [BODY]
# METHOD GET | POST | PATCH | PUT | DELETE
# PATH path below /api/v1, e.g. /repos/kasun/homelab-ansible/pulls?state=open
# BODY JSON string, or @file to send a file
#
# Read-only CI wait: gitea.sh WAIT /repos/OWNER/REPO/commits/SHA/status
# Polls until checks finish. Exit 0: passed or no CI ran. 1: a check failed.
# 2: bad usage. 3: timed out after 15 minutes.
#
# Config (outside the repo, never committed):
# ${XDG_CONFIG_HOME:-~/.config}/homelab-agent/url e.g. http://gitea.example:3000
# ${XDG_CONFIG_HOME:-~/.config}/homelab-agent/token chmod 600
# Token: Site Administration → Identity & Access → User Accounts → claude-bot → generate
# (write:repository, write:issue). claude-bot is a collaborator with Write on the repo.
#
# Adapted from the deverenz repo (.claude/scripts/gitea.sh).
set -euo pipefail
method=${1:?usage: gitea.sh METHOD PATH [BODY]}
path=${2:?usage: gitea.sh METHOD PATH [BODY]}
body=${3:-}
if [[ "$method" == "WAIT" ]]; then
[[ "$path" =~ ^/repos/[^/]+/[^/]+/commits/[0-9a-f]{40}/status$ ]] \
|| { echo "WAIT only accepts /repos/OWNER/REPO/commits/SHA/status" >&2; exit 2; }
for ((i = 1; i <= 45; i++)); do
status=$("$0" GET "$path") || status='{}'
total=$(jq '.statuses // [] | length' <<<"$status")
running=$(jq '[.statuses // [] | .[] | select(.status == "pending" or .status == "running")] | length' <<<"$status")
# Give checks time to register. Path-filtered workflows may never start any.
if (( total == 0 && i >= 7 )); then
echo "no CI ran"
exit 0
fi
if (( total > 0 && running == 0 && i >= 4 )); then
jq -r '.statuses[] | "\(.context): \(.status) \(.target_url)"' <<<"$status"
jq -e '[.statuses[].status] | any(. == "failure" or . == "error") | not' <<<"$status" >/dev/null || exit 1
exit 0
fi
sleep 20
done
echo "timed out waiting for CI" >&2
exit 3
fi
case "$method" in
GET | POST | PATCH | PUT | DELETE) ;;
*) echo "unsupported method: $method" >&2; exit 2 ;;
esac
config=${XDG_CONFIG_HOME:-$HOME/.config}/homelab-agent
for f in url token; do
[[ -s "$config/$f" ]] || { echo "missing $config/$f" >&2; exit 2; }
done
url=$(<"$config/url")
token=$(<"$config/token")
args=(-sS --fail-with-body -X "$method" -H "Accept: application/json")
# The token header is read from stdin so it never shows up in the process list.
args+=(-H @-)
if [[ -n "$body" ]]; then
[[ "$body" == "@-" ]] && { echo "BODY from stdin is not supported, use @file" >&2; exit 2; }
args+=(-H "Content-Type: application/json" --data-binary "$body")
fi
out=$(curl "${args[@]}" "${url%/}/api/v1${path}" <<<"Authorization: token $token") \
|| { echo "$out" >&2; exit 1; }
if command -v jq >/dev/null && [[ -n "$out" ]]; then
jq . <<<"$out" 2>/dev/null || echo "$out"
else
echo "$out"
fi
+114
View File
@@ -0,0 +1,114 @@
{
"permissions": {
"defaultMode": "plan",
"disableAutoMode": "disable",
"allow": [
"Bash(.venv/bin/yamllint *)",
"Bash(.venv/bin/ansible-lint *)",
"Bash(.venv/bin/ansible-lint)",
"Bash(ansible --version)",
"Bash(ansible-doc *)",
"Bash(git log *)",
"Bash(git status *)",
"Bash(git diff *)",
"Bash(git show *)",
"Bash(git grep *)",
"Bash(git blame *)",
"Bash(git ls-files *)",
"Bash(git ls-tree *)",
"Bash(git rev-parse *)",
"Bash(git describe *)",
"Bash(git shortlog *)",
"Bash(git merge-base *)",
"Bash(git reflog show *)",
"Bash(git stash list *)",
"Bash(git branch --list *)",
"Bash(git branch -a *)",
"Bash(git branch -v *)",
"Bash(git tag --list *)",
"Bash(git remote -v)",
"Bash(git fetch *)",
"Bash(git add *)",
"Bash(git switch *)",
"Bash(git commit *)",
"Bash(git push *)",
"Bash(ls *)",
"Bash(pwd)",
"Bash(wc *)",
"Bash(which *)",
"Bash(jq *)",
"Bash(.claude/scripts/gitea.sh GET *)",
"Bash(.claude/scripts/gitea.sh WAIT *)",
"Bash(.claude/scripts/gitea.sh POST *)",
"WebFetch(domain:docs.ansible.com)",
"WebFetch(domain:docs.docker.com)",
"WebFetch(domain:docs.gitea.com)",
"WebFetch(domain:github.com)",
"WebFetch(domain:raw.githubusercontent.com)"
],
"ask": [
"Bash(ansible *)",
"Bash(ansible-playbook *)",
"Bash(ansible-pull *)",
"Bash(ansible-console *)",
"Bash(ansible-vault *)",
"Bash(ssh *)",
"Bash(scp *)",
"Bash(sftp *)",
"Bash(rsync *)",
"Bash(docker *)",
"Bash(pct *)",
"Bash(qm *)",
"Bash(curl *)",
"Bash(.claude/scripts/gitea.sh POST */merge*)",
"Bash(.claude/scripts/gitea.sh PATCH *)",
"Bash(.claude/scripts/gitea.sh PUT *)",
"Bash(.claude/scripts/gitea.sh DELETE *)"
],
"deny": [
"Bash(env)",
"Bash(printenv *)",
"Bash(ansible-vault view *)",
"Bash(ansible-vault decrypt *)",
"Bash(*/etc/homelab-ansible*)",
"Bash(*homelab-agent/token*)",
"Read(**/.env)",
"Read(**/.env.*)",
"Read(**/vault.yml)",
"Read(**/vault.yaml)",
"Read(**/.vault_pass*)",
"Read(//etc/homelab-ansible/**)",
"Edit(//etc/homelab-ansible/**)",
"Read(~/.config/homelab-agent/token)",
"Edit(~/.config/homelab-agent/**)"
]
},
"attribution": {
"commit": "",
"pr": ""
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-live-infra.sh"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-on-stop.sh",
"timeout": 300
}
]
}
]
}
}
+18
View File
@@ -0,0 +1,18 @@
name: Check Connectivity
on:
workflow_dispatch:
jobs:
check-connectivity:
name: Check Connectivity
runs-on: ansible
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Show Ansible Version
run: ansible-playbook --version
- name: Run Connectivity Playbook
run: ansible-playbook playbooks/check-connectivity.yml
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# Git commit-msg hook: rejects commit messages that don't follow CONVENTIONS.md.
#
# Checks:
# - first line is `<type>(<scope>): <summary>` with a known type, an optional
# known scope, and no period at the end
# - no AI attribution lines
#
# Activate once per clone: git config core.hooksPath .githooks
msg_file="$1"
first_line=$(grep -v '^#' "$msg_file" | head -n1)
# Let git's own merge/revert/fixup messages through.
[[ "$first_line" =~ ^(Merge|Revert|fixup!|squash!) ]] && exit 0
types='feature|bug|enhancement|chore|docs'
scopes='ci|claude|inventory|playbooks|roles|scripts|stacks'
pattern="^($types)(\(($scopes)\))?: .*[^.]$"
if ! [[ "$first_line" =~ $pattern ]]; then
echo "commit-msg: '$first_line'" >&2
echo " expected '<type>(<scope>): <summary>' with no trailing period (see CONVENTIONS.md)" >&2
echo " types: ${types//|/ }" >&2
echo " scopes: ${scopes//|/ } (optional)" >&2
exit 1
fi
if grep -qiE '^(Co-Authored-By:.*(claude|anthropic)|.*Generated with \[?Claude)' "$msg_file"; then
echo "commit-msg: no AI attribution lines (see CLAUDE.md)" >&2
exit 1
fi
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Git pre-commit hook: blocks a commit if its staged changes contain a secret.
#
# Activate once per clone: git config core.hooksPath .githooks
if ! command -v betterleaks >/dev/null 2>&1; then
echo "pre-commit: betterleaks is not installed, so staged changes can't be scanned" >&2
exit 1
fi
exec betterleaks git --pre-commit --staged --redact --no-banner --no-color .
+49
View File
@@ -0,0 +1,49 @@
# CLAUDE.md
Ansible automation for a Proxmox homelab. It deploys Docker stacks and single scripts into containers and LXCs, from git, through Gitea Actions.
## Hosts
- `ansible`: unprivileged LXC that runs Ansible and has SSH key access to `docker`.
- `docker`: unprivileged LXC running Gitea, its Actions runner, Postgres and the apps. Compose files live in `/home/pi/docker/<service>/docker-compose.yml`.
## Layout (planned)
`inventory/{hosts.yml,group_vars/}`, `roles/{docker_stack,script,lxc_base}`, `stacks/<service>/{docker-compose.yml,env.j2}`, `scripts/`, `playbooks/`, `.gitea/workflows/`.
## Deployment flow
Branch → PR (lint, secret scan, later `--check --diff`) → merge to protected `main` → dedicated runner on the `ansible` LXC (`runs-on: ansible`) → playbook over SSH → restart only changed stacks → health check. Roll back with `git revert`.
## Rules for stacks
- Keep the `/home/pi/docker/<service>/` paths, because Compose derives the project name from the folder.
- Ansible manages config, never data. No ownership changes under `DOCKER_DATA_ROOT` (mapped UIDs).
- When adopting a stack: pin its image, remove its Watchtower label, and require a no-change dry run first.
- Gitea, its runner and Postgres never auto-deploy. I trigger them from the `ansible` LXC.
## Secrets
- The real vault file and password live in `/etc/homelab-ansible/` on the `ansible` LXC, never in git. Commit only `vault.example.yml`.
- This repo is meant to become public. Don't commit secrets, internal IPs or hostnames beyond the inventory aliases.
## Live infrastructure
- Don't change live systems (hosts, containers, Proxmox, Gitea settings) on your own initiative, even for small or reversible changes. Give me the exact steps and let me decide who runs them.
- That includes `ansible`, `ansible-playbook` (even with `--check`), SSH and Docker commands against a host.
- Code edits in the repo are fine without asking.
- Never recreate a VM or LXC to apply a change.
## Git conventions
Branch names, commit messages and PR titles follow @CONVENTIONS.md. The git hooks need `git config core.hooksPath .githooks` once per clone.
Only commit when I explicitly say "commit" for that change. A yes to a question that also mentioned committing is not enough; when unsure, ask.
The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-ansible/pulls?state=open'`. Use it for PRs only, and ask before opening or merging one. Reading from Gitea is free.
## Verifying changes
Install the lint tools once with `python3 -m venv .venv` and `.venv/bin/pip install -r requirements-dev.txt`. After editing, run `.venv/bin/yamllint --strict .` and `.venv/bin/ansible-lint`, and show the output.
Don't silence a check to make it pass (`# noqa`, lint skip lists, `git commit --no-verify`) without a stated reason and my OK.
+51
View File
@@ -0,0 +1,51 @@
# Git Conventions
## Branch Naming
```
<type>/<short-kebab-case-description>
```
- All lowercase, hyphens only
- Keep the description short (3–5 words)
- No ticket tracker is used, so branch names don't carry an ID
| Type | Use for |
|---|---|
| `feature/` | New functionality (e.g. a new role, a newly adopted stack) |
| `bug/` | Bug fixes |
| `enhancement/` | Improvements or refactors to existing functionality, no new capability |
| `chore/` | Dependency bumps, tooling, CI/CD, cleanup |
| `docs/` | Documentation only |
**Examples:** `feature/adopt-uptime-kuma-stack`, `bug/fix-stack-health-check`, `chore/pin-ansible-lint`
---
## Commit Messages
```
<type>(<scope>): <imperative, present-tense summary>
<optional body: explain WHY, not WHAT>
```
- **Type**: same list as the branch types above
- **Scope**: optional. The allowed values are defined in `.githooks/commit-msg`, which enforces them
- **Summary**: imperative mood ("add", not "added" or "adds"), no period at the end
- **Body**: only when the reasoning isn't obvious from the diff
---
## Pull Request Titles
Gitea's merge commit reuses the PR title as its summary, so the title should stand on its own in `git log`. Describe the outcome:
```
<Type>: <what changes for the homelab>
```
**Examples:**
- `Feature: Deploy Uptime Kuma through Ansible`
- `Bug: Fix health check for stacks without a published port`
- `Chore: Add secret scan and lint checks`
+9
View File
@@ -0,0 +1,9 @@
[defaults]
inventory = inventory/hosts.yml
roles_path = roles
host_key_checking = True
interpreter_python = auto_silent
retry_files_enabled = False
[ssh_connection]
pipelining = True
+3
View File
@@ -0,0 +1,3 @@
---
# Compose derives each project name from its folder, so these paths must not change.
homelab_stacks_root: /home/pi/docker
+11
View File
@@ -0,0 +1,11 @@
---
# On the ansible LXC, ~/.ssh/config maps "docker" to its real address, user and key.
all:
children:
control:
hosts:
ansible:
ansible_connection: local
docker_hosts:
hosts:
docker:
+35
View File
@@ -0,0 +1,35 @@
---
# Read-only: proves Ansible can reach each host. It changes nothing.
- name: Check that every host responds
hosts: all
gather_facts: false
tasks:
- name: Ping host
ansible.builtin.ping:
- name: Check the Docker host
hosts: docker_hosts
gather_facts: false
tasks:
- name: Read Docker Compose version
ansible.builtin.command: docker compose version
register: check_connectivity_compose
changed_when: false
check_mode: false
- name: Show Docker Compose version
ansible.builtin.debug:
msg: "{{ check_connectivity_compose.stdout }}"
- name: Read stacks root
ansible.builtin.stat:
path: "{{ homelab_stacks_root }}"
register: check_connectivity_stacks_root
- name: Require stacks root
ansible.builtin.assert:
that:
- check_connectivity_stacks_root.stat.isdir is defined
- check_connectivity_stacks_root.stat.isdir
fail_msg: "{{ homelab_stacks_root }} is missing or is not a directory"
quiet: true
+1
View File
@@ -1,2 +1,3 @@
ansible-core==2.22.0
ansible-lint==26.11.0
yamllint==1.38.0
+4
View File
@@ -0,0 +1,4 @@
---
# Template only. The real file is /etc/homelab-ansible/vault.yml on the ansible LXC,
# encrypted with ansible-vault and never committed.
vault_example_secret: CHANGE_ME