|
|
|
@@ -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
|