4 Commits
v2 ... v5
Author SHA1 Message Date
tthandClaude Opus 5.5 380988c194 portainer-deploy: content-addressed Swarm configs from repo files (v5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:24:36 +01:00
tthandClaude Opus 5.5 a3c4ae5edf portainer-deploy: update a Swarm stack from the repo's compose file (v4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:20:28 +01:00
tthandClaude Opus 5.5 67a711fe3c gitleaks: fetch the parent of a single scanned commit in shallow checkouts (v3)
A dispatch or cron run has no before-sha, so one commit is scanned; in a
depth-1 checkout it has no parent and gitleaks diffed it as a root commit,
reporting the whole tree (corescope: 3 upstream files).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:34:32 +01:00
tthandClaude Opus 5.5 9591a27e59 README: dot-free version tags (runner mangles v1.2), v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:09:45 +01:00
3 changed files with 255 additions and 4 deletions

No files matched your search

+54 -3
View File
@@ -32,7 +32,7 @@ the git-tracked files plus lockfiles generated in the job (also gitignored
ones like Flutter's `pubspec.lock`), so run it after the dependency fetch: ones like Flutter's `pubspec.lock`), so run it after the dependency fetch:
```yaml ```yaml
- uses: https://git.rfa.cz/tth-pub/ci-actions/trivy-gate@v1.1 - uses: https://git.rfa.cz/tth-pub/ci-actions/trivy-gate@v2
with: with:
scan-type: fs scan-type: fs
``` ```
@@ -78,7 +78,7 @@ other IaC in the tree. These findings are reported (HIGH/CRITICAL by
default) and never block. default) and never block.
```yaml ```yaml
- uses: https://git.rfa.cz/tth-pub/ci-actions/trivy-gate@v1.2 - uses: https://git.rfa.cz/tth-pub/ci-actions/trivy-gate@v2
with: with:
scan-type: fs scan-type: fs
scanners: misconfig scanners: misconfig
@@ -94,7 +94,58 @@ default rules apply with test files and fixtures allowlisted. The release
binary is verified by SHA-256. binary is verified by SHA-256.
```yaml ```yaml
- uses: https://git.rfa.cz/tth-pub/ci-actions/gitleaks@v1.2 - uses: https://git.rfa.cz/tth-pub/ci-actions/gitleaks@v2
with: with:
mode: block # or warn mode: block # or warn
``` ```
## Versions
`v1` image gate + SBOM; `v2` fs scans, binary runtime, misconfig, gitleaks;
`v3` gitleaks fetches the parent of a single commit in a depth-1 checkout
(dispatch/cron runs scanned the whole tree as a root commit before).
## portainer-deploy
Updates a Portainer Swarm stack from a compose file in the repository - the
last step of the build → `trivy-gate` → move `latest` → deploy pipeline. The
compose file in git is the single source of truth: Portainer's stored
compose is replaced on every deploy. The stack's env vars (where the secrets
live) are kept and never logged; only `vars` are overwritten. Images are
re-pulled (`pullImage`).
```yaml
- uses: https://git.rfa.cz/tth-pub/ci-actions/portainer-deploy@v5
with:
url: ${{ secrets.PORTAINER_URL }}
token: ${{ secrets.PORTAINER_TOKEN }}
stack-id: ${{ secrets.PORTAINER_STACK_ID }} # empty = skip with a notice
compose-file: docker-compose.swarm.yml
vars: |
IMAGE_TAG=sha-${{ steps.build.outputs.sha }}
smoke-url: https://app.example.org/health # optional
smoke-status: "200"
smoke-timeout: "180"
```
Config files from the repo can ride along as Swarm configs. Each becomes a
config named after its content hash, created when missing; the stack
variable points at it, so a changed file rolls the services that mount it,
and superseded versions are removed once nothing uses them:
```yaml
configs: |
CFG_NGINX=deploy/nginx.conf
config-prefix: myapp_
```
```yaml
# compose
configs:
nginx_conf: {external: true, name: "${CFG_NGINX}"}
```
Pin images in the compose file to the variable (`image: …:${IMAGE_TAG}`), so
the deployed version is the commit that passed the gate, not whatever
`latest` points at when Swarm pulls.
+8 -1
View File
@@ -83,7 +83,14 @@ runs:
opts="--first-parent --diff-merges=off $BEFORE..$SHA" opts="--first-parent --diff-merges=off $BEFORE..$SHA"
fi fi
fi fi
[ -n "$opts" ] || opts="--diff-merges=off -1 ${SHA:-HEAD}" if [ -z "$opts" ]; then
# One commit (dispatch/cron). In a depth-1 checkout it has no
# parent and would be diffed as a root commit, i.e. the whole
# tree (upstream files of a fork included): fetch its parent.
head="${SHA:-HEAD}"
git rev-parse -q --verify "$head^" >/dev/null 2>&1 || git fetch -q --deepen=1 origin 2>/dev/null || true
opts="--diff-merges=off -1 $head"
fi
fi fi
if [ -n "$CONFIG" ] && [ -f "$CONFIG" ]; then if [ -n "$CONFIG" ] && [ -f "$CONFIG" ]; then
cfg=(--config "$CONFIG") cfg=(--config "$CONFIG")
+193
View File
@@ -0,0 +1,193 @@
name: portainer-deploy
description: >
Update a Portainer Swarm stack from a compose file in the repository. The
compose file is the single source of truth: Portainer's stored compose is
replaced on every deploy, the stack's env vars (where the secrets live) are
kept and only the given variables are overwritten. Images are re-pulled.
Config files from the repo can be shipped as content-addressed Swarm
configs. Optionally waits until a URL answers with the expected status.
inputs:
url:
description: Portainer base URL.
required: true
token:
description: Portainer API key (X-API-Key).
required: true
stack-id:
description: >
Portainer stack id. Empty = skip the deploy with a notice (a repo that
has no stack yet).
default: ""
compose-file:
description: Compose file in the checkout to deploy.
required: true
endpoint-id:
description: Portainer environment (endpoint) id.
default: "1"
vars:
description: >
Stack variables to set, one NAME=value per line (e.g. IMAGE_TAG=sha-1234abcd).
Every other stack variable is kept as it is.
default: ""
configs:
description: >
Files shipped as Swarm configs, one VAR=path per line. Each file becomes
a config named <config-prefix><var>-<sha256[:12] of the content>
(created when missing) and the stack variable VAR is set to that name,
so the compose file references it as
`{external: true, name: "${VAR}"}`. A changed file = a new config =
the service is updated; older versions of the same VAR are removed once
no service uses them.
default: ""
config-prefix:
description: Prefix of the config names (e.g. the stack name and an underscore).
default: ""
prune:
description: Remove services that are no longer in the compose file.
default: "false"
smoke-url:
description: URL polled after the deploy until it answers smoke-status. Empty = no check.
default: ""
smoke-status:
description: Expected HTTP status of smoke-url.
default: "200"
smoke-timeout:
description: Seconds to wait for smoke-url.
default: "180"
runs:
using: composite
steps:
- shell: bash
env:
PORTAINER_URL: ${{ inputs.url }}
PORTAINER_TOKEN: ${{ inputs.token }}
STACK_ID: ${{ inputs.stack-id }}
COMPOSE_FILE: ${{ inputs.compose-file }}
ENDPOINT_ID: ${{ inputs.endpoint-id }}
SET_VARS: ${{ inputs.vars }}
CONFIGS: ${{ inputs.configs }}
CONFIG_PREFIX: ${{ inputs.config-prefix }}
PRUNE: ${{ inputs.prune }}
SMOKE_URL: ${{ inputs.smoke-url }}
SMOKE_STATUS: ${{ inputs.smoke-status }}
SMOKE_TIMEOUT: ${{ inputs.smoke-timeout }}
run: |
set -euo pipefail
if [ -z "$STACK_ID" ]; then
echo "::notice::portainer-deploy: no stack id, deploy skipped"
exit 0
fi
# The stack env carries the secrets: it only ever lives in this
# process's memory, between the GET and the PUT, never in the log.
python3 - <<'PY'
import base64, hashlib, json, os, ssl, sys, time, urllib.error, urllib.parse, urllib.request
E = os.environ
base = E["PORTAINER_URL"].rstrip("/")
token = E["PORTAINER_TOKEN"]
stack_id, endpoint = E["STACK_ID"], E.get("ENDPOINT_ID") or "1"
if not base or not token:
sys.exit("::error::portainer-deploy: url and token are required")
def api(method, path, body=None, ok=(200,)):
req = urllib.request.Request(base + path, method=method,
headers={"X-API-Key": token, "Content-Type": "application/json"},
data=None if body is None else json.dumps(body).encode())
try:
with urllib.request.urlopen(req, timeout=120) as r:
status, raw = r.status, r.read()
except urllib.error.HTTPError as e:
status, raw = e.code, e.read()
if status not in ok:
raise RuntimeError(f"{method} {path.split('?')[0]} -> HTTP {status}: {raw[:300].decode(errors='replace')}")
return status, (json.loads(raw) if raw.strip() else None)
def lines(name):
out = {}
for line in E.get(name, "").splitlines():
line = line.strip()
if not line:
continue
key, sep, value = line.partition("=")
if not sep or not key.strip():
sys.exit(f"::error::portainer-deploy: bad {name.lower()} line (want NAME=value): {key!r}")
out[key.strip()] = value.strip() if name == "CONFIGS" else value
return out
try:
sets = lines("SET_VARS")
docker = f"/api/endpoints/{endpoint}/docker"
# Content-addressed configs: the name changes with the content, so
# a changed file rolls the services that mount it.
prefix = E.get("CONFIG_PREFIX", "")
stale = []
for var, path in lines("CONFIGS").items():
with open(path, "rb") as f:
data = f.read()
stem = f"{prefix}{var.lower()}"
name = f"{stem}-{hashlib.sha256(data).hexdigest()[:12]}"
flt = urllib.parse.quote(json.dumps({"label": [f"portainer-deploy.config={stem}"]}))
_, existing = api("GET", f"{docker}/configs?filters={flt}")
names = {c["Spec"]["Name"]: c["ID"] for c in existing or []}
if name in names:
print(f"config {name} ({path}) unchanged")
else:
api("POST", f"{docker}/configs/create", {
"Name": name,
"Data": base64.b64encode(data).decode(),
"Labels": {"portainer-deploy.config": stem},
}, ok=(200, 201))
print(f"config {name} created from {path}")
stale += [(n, i) for n, i in names.items() if n != name]
sets[var] = name
_, stack = api("GET", f"/api/stacks/{stack_id}")
env = [e for e in (stack.get("Env") or []) if e.get("name") not in sets]
kept = len(env)
env += [{"name": k, "value": v} for k, v in sets.items()]
with open(E["COMPOSE_FILE"]) as f:
compose = f.read()
api("PUT", f"/api/stacks/{stack_id}?endpointId={endpoint}", {
"stackFileContent": compose,
"env": env,
"prune": E.get("PRUNE", "false").lower() == "true",
"pullImage": True,
})
shown = ", ".join(f"{k}={v}" for k, v in sets.items()) or "nothing"
print(f"stack {stack.get('Name', stack_id)} updated from {E['COMPOSE_FILE']}: {shown}; {kept} other variable(s) kept")
# Older versions go once nothing mounts them; Docker refuses to
# delete a config in use (the previous task may still be draining),
# the next deploy retries.
for name, cid in stale:
try:
api("DELETE", f"{docker}/configs/{cid}", ok=(200, 204))
print(f"config {name} removed (superseded)")
except RuntimeError:
print(f"config {name} still in use, kept for the next deploy")
except (RuntimeError, OSError) as exc:
sys.exit(f"::error::portainer-deploy: {exc}")
url = E.get("SMOKE_URL", "")
if url:
want, deadline = E.get("SMOKE_STATUS", "200"), time.time() + float(E.get("SMOKE_TIMEOUT") or 180)
ctx = ssl.create_default_context()
ctx.check_hostname, ctx.verify_mode = False, ssl.CERT_NONE
while True:
try:
with urllib.request.urlopen(url, timeout=10, context=ctx) as r:
got = str(r.status)
except urllib.error.HTTPError as e:
got = str(e.code)
except (urllib.error.URLError, OSError):
got = "000"
if got == want:
print(f"smoke: {url} answered {got}")
break
if time.time() >= deadline:
sys.exit(f"::error::smoke: {url} answered {got}, expected {want}")
time.sleep(10)
PY