use as gitea action
Publish Action Image / build (push) Successful in 31s

This commit is contained in:
2026-06-29 16:01:01 +10:00
parent 4ee1b9e13c
commit 9adb5780f2
6 changed files with 236 additions and 248 deletions
+11 -8
View File
@@ -1,15 +1,18 @@
FROM golang:1.22-alpine AS builder FROM golang:1.22-alpine AS builder
WORKDIR /app WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . . COPY . .
RUN go build -o kforge . RUN go build -o /usr/local/bin/kforge .
FROM alpine:3.19 FROM alpine:3.20
COPY --from=builder /app/kforge /usr/local/bin/kforge RUN apk add --no-cache ca-certificates curl git
RUN apk add --no-cache curl docker-cli && \
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" && \
install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl && \
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
ARG KUBECTL_VERSION=v1.31.0
RUN curl -fsSL "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl" \
-o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl
COPY --from=builder /usr/local/bin/kforge /usr/local/bin/kforge
COPY entrypoint.sh /entrypoint.sh COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh RUN chmod +x /entrypoint.sh
+19 -52
View File
@@ -1,62 +1,29 @@
name: "K8s YAML Generator" name: 'kforge'
description: "Builds a Docker image, pushes it to a private registry, generates Kubernetes YAML from a simplified YML file, and deploys it." description: 'Generate and apply Kubernetes manifests from kforge.yml'
author: "Claude Code made this"
inputs: inputs:
image_name: command:
description: "Docker image name to build and push (e.g. my-app)" description: 'deploy | preview-up | preview-down | validate | secrets'
required: true
image_tag:
description: "Docker image tag. If omitted, defaults to both 'latest' and the short commit SHA."
required: false required: false
dockerfile: default: 'deploy'
description: "Path to Dockerfile" env:
description: 'Environment to target (e.g. production, staging). Omit to target all.'
required: false required: false
default: "Dockerfile" config:
max_tags: description: 'Path to kforge.yml relative to the workspace root'
description: "Maximum number of SHA image tags to keep in the registry"
required: false required: false
default: "5" default: 'kforge.yml'
namespace:
registry: description: 'Kubernetes namespace for rollout restart (defaults to env name)'
description: "Docker registry URL"
required: false required: false
default: "registry.natelubitz.com" pr_number:
registry_username: description: 'PR number — required for preview-up and preview-down'
description: "Registry username"
required: true
registry_password:
description: "Registry password"
required: true
kube_host:
description: "Kubernetes API server URL"
required: false required: false
default: "192.168.1.20:16443" namespace_prefix:
kube_certificate: description: 'Namespace prefix for preview environments'
description: "Base64 encoded Kubernetes CA certificate"
required: true
kube_token:
description: "Kubernetes service account token"
required: true
scan_image:
description: "Scan image for vulnerabilities before pushing"
required: false required: false
default: "true" default: 'preview-pr'
scan_severity:
description: "Fail on these severity levels (UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL)"
required: false
default: "HIGH,CRITICAL"
# outputs:
# output_file:
# description: "Path to the generated Kubernetes YAML file"
runs: runs:
using: "docker" using: docker
image: "docker://registry.natelubitz.com/infra/kforge:latest" image: Dockerfile
# args:
# - ${{ inputs.input_file }}
# - ${{ inputs.output_file }}
# - ${{ inputs.auto_deploy }}
+76 -132
View File
@@ -1,146 +1,90 @@
#!/bin/sh #!/bin/sh
set -e set -e
# INPUT_FILE="$1" COMMAND="${INPUT_COMMAND:-deploy}"
# OUTPUT_FILE="$2" CONFIG="${INPUT_CONFIG:-kforge.yml}"
# AUTO_DEPLOY="$3"
# ---------------------------------------------------------------- # Build a kubeconfig from the standard KUBE_* CI secrets.
# Registry login setup_kube() {
# ---------------------------------------------------------------- [ -z "$KUBE_HOST" ] && return
if [ -n "$INPUT_REGISTRY_USERNAME" ] && [ -n "$INPUT_REGISTRY_PASSWORD" ]; then mkdir -p ~/.kube
echo "Logging in to $INPUT_REGISTRY..." cat > ~/.kube/config <<KUBEEOF
echo "$INPUT_REGISTRY_PASSWORD" | docker login "$INPUT_REGISTRY" \ apiVersion: v1
-u "$INPUT_REGISTRY_USERNAME" --password-stdin kind: Config
fi clusters:
- cluster:
# ---------------------------------------------------------------- certificate-authority-data: ${KUBE_CERTIFICATE}
# Build and push image server: ${KUBE_HOST}
# ---------------------------------------------------------------- name: kforge
cleanup_old_tags() { contexts:
IMAGE="$1" - context:
KEEP="$2" cluster: kforge
user: kforge
echo "Fetching tags for $IMAGE..." name: kforge
current-context: kforge
TAGS=$(curl -s -u "$INPUT_REGISTRY_USERNAME:$INPUT_REGISTRY_PASSWORD" \ users:
"https://$INPUT_REGISTRY/v2/$IMAGE/tags/list" \ - name: kforge
| tr ',' '\n' \ user:
| grep -o '"[a-f0-9]\{7\}"' \ token: ${KUBE_TOKEN}
| tr -d '"') KUBEEOF
chmod 600 ~/.kube/config
COUNT=$(echo "$TAGS" | grep -c .)
DELETE_COUNT=$((COUNT - KEEP))
if [ "$DELETE_COUNT" -le 0 ]; then
echo "Only $COUNT hash tags found, no cleanup needed."
return
fi
echo "Found $COUNT hash tags, deleting oldest $DELETE_COUNT..."
echo "$TAGS" | head -n "$DELETE_COUNT" | while read -r TAG; do
echo "Deleting tag: $TAG..."
DIGEST=$(curl -s -I \
-u "$INPUT_REGISTRY_USERNAME:$INPUT_REGISTRY_PASSWORD" \
-H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
"https://$INPUT_REGISTRY/v2/$IMAGE/manifests/$TAG" \
| grep -i "docker-content-digest" \
| tr -d '\r' \
| awk '{print $2}')
if [ -n "$DIGEST" ]; then
curl -s -X DELETE \
-u "$INPUT_REGISTRY_USERNAME:$INPUT_REGISTRY_PASSWORD" \
"https://$INPUT_REGISTRY/v2/$IMAGE/manifests/$DIGEST"
echo "Deleted $TAG ($DIGEST)"
else
echo "Could not find digest for $TAG, skipping."
fi
done
} }
if [ -n "$INPUT_IMAGE_NAME" ]; then cd "${GITHUB_WORKSPACE:-/github/workspace}"
FULL_IMAGE="$INPUT_REGISTRY/$INPUT_IMAGE_NAME"
if [ -n "$INPUT_IMAGE_TAG" ]; then case "$COMMAND" in
echo "Building image $FULL_IMAGE:$INPUT_IMAGE_TAG..." deploy)
docker build -t "$FULL_IMAGE:$INPUT_IMAGE_TAG" -f "$INPUT_DOCKERFILE" . export KFORGE_IMAGE_TAG="$(git rev-parse --short HEAD)"
setup_kube
echo "Scanning image for vulnerabilities..." kforge validate -c "$CONFIG"
trivy image \ if [ -n "$INPUT_ENV" ]; then
--exit-code 1 \ kforge secrets apply --env "$INPUT_ENV" -c "$CONFIG"
--severity "$INPUT_SCAN_SEVERITY" \ kforge generate --env "$INPUT_ENV" --output .kforge-out -c "$CONFIG"
--no-progress \
"$FULL_IMAGE:$INPUT_IMAGE_TAG"
echo "Scan passed, pushing image..."
docker push "$FULL_IMAGE:$INPUT_IMAGE_TAG"
else else
SHA=$(echo "$GITHUB_SHA" | cut -c1-7) kforge generate --output .kforge-out -c "$CONFIG"
echo "Building image $FULL_IMAGE:latest and $FULL_IMAGE:$SHA..."
docker build \
-t "$FULL_IMAGE:latest" \
-t "$FULL_IMAGE:$SHA" \
-f "$INPUT_DOCKERFILE" .
echo "Scanning image for vulnerabilities..."
trivy image \
--exit-code 1 \
--severity "$INPUT_SCAN_SEVERITY" \
--no-progress \
"$FULL_IMAGE:latest"
echo "Scan passed, pushing image..."
docker push "$FULL_IMAGE:latest"
docker push "$FULL_IMAGE:$SHA"
cleanup_old_tags "$INPUT_IMAGE_NAME" "${INPUT_MAX_TAGS:-5}"
fi fi
fi kubectl apply -f .kforge-out/ --insecure-skip-tls-verify
NAMESPACE="${INPUT_NAMESPACE:-${INPUT_ENV}}"
if [ -n "$NAMESPACE" ]; then
kubectl rollout restart deployment -n "$NAMESPACE" --insecure-skip-tls-verify || true
fi
;;
# ---------------------------------------------------------------- preview-up)
# Generate Kubernetes YAML [ -z "$INPUT_PR_NUMBER" ] && echo "::error::pr_number input is required for preview-up" && exit 1
# ---------------------------------------------------------------- setup_kube
echo "Generating Kubernetes YAML from .kforge.yml" kforge secrets apply --pr-number "$INPUT_PR_NUMBER" -c "$CONFIG"
/usr/local/bin/kforge generate kforge generate --pr-number "$INPUT_PR_NUMBER" --output .kforge-out -c "$CONFIG"
kubectl apply -f .kforge-out/ --insecure-skip-tls-verify
NS="${INPUT_NAMESPACE_PREFIX:-preview-pr}-${INPUT_PR_NUMBER}"
kubectl rollout status deployment -n "$NS" --timeout=120s --insecure-skip-tls-verify || true
;;
# ---------------------------------------------------------------- preview-down)
# Deploy to Kubernetes [ -z "$INPUT_PR_NUMBER" ] && echo "::error::pr_number input is required for preview-down" && exit 1
# ---------------------------------------------------------------- setup_kube
# Build kubeconfig from token-based credentials NS="${INPUT_NAMESPACE_PREFIX:-preview-pr}-${INPUT_PR_NUMBER}"
echo "Configuring kubectl..." kubectl delete namespace "$NS" --ignore-not-found --insecure-skip-tls-verify
;;
# Try writing the cert and check if it worked validate)
echo "$INPUT_KUBE_CERTIFICATE" | base64 -d > /tmp/kube-ca.crt 2>&1 kforge validate -c "$CONFIG"
echo "Cert file size: $(wc -c < /tmp/kube-ca.crt)" ;;
echo "Cert file contents: $(cat /tmp/kube-ca.crt | head -1)"
kubectl config set-cluster default \ secrets)
--server="$INPUT_KUBE_HOST" \ setup_kube
--certificate-authority=/tmp/kube-ca.crt if [ -n "$INPUT_PR_NUMBER" ]; then
kforge secrets apply --pr-number "$INPUT_PR_NUMBER" -c "$CONFIG"
elif [ -n "$INPUT_ENV" ]; then
kforge secrets apply --env "$INPUT_ENV" -c "$CONFIG"
else
echo "::error::env or pr_number input is required for the secrets command"
exit 1
fi
;;
kubectl config set-credentials default \ *)
--token="$INPUT_KUBE_TOKEN" echo "::error::Unknown command '$COMMAND'. Valid: deploy, preview-up, preview-down, validate, secrets"
exit 1
kubectl config set-context default \ ;;
--cluster=default \ esac
--user=default
kubectl config use-context default
# Create/update regcred secret idempotently
# echo "Creating regcred secret..."
# kubectl create secret docker-registry regcred \
# --docker-server="$INPUT_REGISTRY" \
# --docker-username="$INPUT_REGISTRY_USERNAME" \
# --docker-password="$INPUT_REGISTRY_PASSWORD" \
# --dry-run=client -o yaml | kubectl apply -f - --insecure-skip-tls-verify --validate=false
echo "Deploying to Kubernetes..."
kubectl apply --insecure-skip-tls-verify --validate=false -f ./.kforge-out/
echo "Deploy complete."
echo "Cleanup"
rm -f /tmp/kube-ca.crt
+6
View File
@@ -2,6 +2,7 @@ package config
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
"kforge/pkg/interpolate" "kforge/pkg/interpolate"
@@ -306,6 +307,11 @@ func ResolveEnvironment(cfg *KforgeConfig, envKey string) (ResolvedEnvironment,
if imageTag == "" { if imageTag == "" {
imageTag = DefaultImageTag imageTag = DefaultImageTag
} }
// Allow the action entrypoint (or CI) to override the image tag at generate
// time without modifying kforge.yml (e.g. KFORGE_IMAGE_TAG=abc1234).
if override := os.Getenv("KFORGE_IMAGE_TAG"); override != "" {
imageTag = override
}
image := registry.URL + "/" + registry.Repository + ":" + imageTag image := registry.URL + "/" + registry.Repository + ":" + imageTag
replicas := *cfg.Defaults.Replicas replicas := *cfg.Defaults.Replicas
+6
View File
@@ -14,6 +14,12 @@ type KforgeConfig struct {
Infrastructure InfrastructureConfig `yaml:"infrastructure"` Infrastructure InfrastructureConfig `yaml:"infrastructure"`
Preview PreviewConfig `yaml:"preview,omitempty"` Preview PreviewConfig `yaml:"preview,omitempty"`
Environments map[string]EnvironmentConfig `yaml:"environments"` Environments map[string]EnvironmentConfig `yaml:"environments"`
// ActionRef is the Gitea Actions reference to this kforge installation
// (e.g. "gitea.example.com/infra/kforge@main"). When set, kforge gitea-actions
// and kforge gitea-preview generate workflows that call kforge as a reusable
// action step instead of installing and running kforge inline.
ActionRef string `yaml:"action_ref,omitempty"`
} }
// ------------------------------------------------------------ // ------------------------------------------------------------
+69 -7
View File
@@ -74,10 +74,6 @@ func writeDeployJobs(b *strings.Builder, cfg *config.KforgeConfig, opts GiteaAct
"with": map[string]any{"fetch-depth": 0}, "with": map[string]any{"fetch-depth": 0},
}) })
writeStep(b, "Create short commit hash", map[string]any{
"run": `echo "SHORT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV`,
})
writeStep(b, "Login to registry", map[string]any{ writeStep(b, "Login to registry", map[string]any{
"uses": "docker/login-action@v2", "uses": "docker/login-action@v2",
"with": map[string]any{ "with": map[string]any{
@@ -101,6 +97,39 @@ func writeDeployJobs(b *strings.Builder, cfg *config.KforgeConfig, opts GiteaAct
}, },
}) })
if cfg.ActionRef != "" {
writeActionDeploySteps(b, cfg, opts)
} else {
writeInlineDeploySteps(b, cfg, opts)
}
}
// writeActionDeploySteps emits one `uses: action_ref` step per environment.
func writeActionDeploySteps(b *strings.Builder, cfg *config.KforgeConfig, opts GiteaActionsOptions) {
for _, envKey := range opts.Environments {
env, err := config.ResolveEnvironment(cfg, envKey)
if err != nil {
continue
}
label := strings.Title(envKey) //nolint:staticcheck
writeStep(b, fmt.Sprintf("Deploy (%s)", label), map[string]any{
"uses": cfg.ActionRef,
"with": map[string]any{
"command": "deploy",
"env": envKey,
"namespace": env.Namespace,
},
"env": actionEnv(),
})
}
}
// writeInlineDeploySteps emits the classic multi-step inline approach.
func writeInlineDeploySteps(b *strings.Builder, cfg *config.KforgeConfig, opts GiteaActionsOptions) {
writeStep(b, "Create short commit hash", map[string]any{
"run": `echo "SHORT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV`,
})
writeStep(b, "Install kforge", map[string]any{ writeStep(b, "Install kforge", map[string]any{
"run": "KFORGE_VERSION=\"latest\"\ncurl -fsSL \"https://kforge/releases/download/${KFORGE_VERSION}/kforge-linux-amd64\" -o /usr/local/bin/kforge\nchmod +x /usr/local/bin/kforge", "run": "KFORGE_VERSION=\"latest\"\ncurl -fsSL \"https://kforge/releases/download/${KFORGE_VERSION}/kforge-linux-amd64\" -o /usr/local/bin/kforge\nchmod +x /usr/local/bin/kforge",
}) })
@@ -244,6 +273,29 @@ func GeneratePreviewActions(cfg *config.KforgeConfig) (string, error) {
}, },
}) })
if cfg.ActionRef != "" {
writeStep(&b, "Deploy preview", map[string]any{
"if": "${{ github.event.action != 'closed' }}",
"uses": cfg.ActionRef,
"with": map[string]any{
"command": "preview-up",
"pr_number": "${{ github.event.number }}",
"namespace_prefix": nsPrefix,
},
"env": actionEnv(),
})
writeStep(&b, "Destroy preview", map[string]any{
"if": "${{ github.event.action == 'closed' }}",
"uses": cfg.ActionRef,
"with": map[string]any{
"command": "preview-down",
"pr_number": "${{ github.event.number }}",
"namespace_prefix": nsPrefix,
},
"env": actionEnv(),
})
} else {
writeStep(&b, "Install kforge", map[string]any{ writeStep(&b, "Install kforge", map[string]any{
"if": "${{ github.event.action != 'closed' }}", "if": "${{ github.event.action != 'closed' }}",
"run": "KFORGE_VERSION=\"latest\"\ncurl -fsSL \"https://kforge/releases/download/${KFORGE_VERSION}/kforge-linux-amd64\" -o /usr/local/bin/kforge\nchmod +x /usr/local/bin/kforge", "run": "KFORGE_VERSION=\"latest\"\ncurl -fsSL \"https://kforge/releases/download/${KFORGE_VERSION}/kforge-linux-amd64\" -o /usr/local/bin/kforge\nchmod +x /usr/local/bin/kforge",
@@ -269,9 +321,7 @@ func GeneratePreviewActions(cfg *config.KforgeConfig) (string, error) {
"uses": "actions-hub/kubectl@master", "uses": "actions-hub/kubectl@master",
"env": giteaKubeEnv(), "env": giteaKubeEnv(),
"with": map[string]any{ "with": map[string]any{
"args": fmt.Sprintf( "args": "apply -f .kforge-out/ --insecure-skip-tls-verify",
"apply -f .kforge-out/ --insecure-skip-tls-verify",
),
}, },
}) })
@@ -298,6 +348,7 @@ func GeneratePreviewActions(cfg *config.KforgeConfig) (string, error) {
), ),
}, },
}) })
}
return b.String(), nil return b.String(), nil
} }
@@ -383,6 +434,17 @@ func giteaKubeEnv() map[string]any {
} }
} }
// actionEnv returns the combined env block for a kforge action step —
// kubectl auth plus the node IP for external-dns annotation resolution.
func actionEnv() map[string]any {
return map[string]any{
"KUBE_CERTIFICATE": "${{ secrets.KUBE_CERTIFICATE }}",
"KUBE_HOST": "${{ secrets.KUBE_HOST }}",
"KUBE_TOKEN": "${{ secrets.KUBE_TOKEN }}",
"KFORGE_NODE_IP": "${{ secrets.KFORGE_NODE_IP }}",
}
}
func mergeMaps(maps ...map[string]any) map[string]any { func mergeMaps(maps ...map[string]any) map[string]any {
result := map[string]any{} result := map[string]any{}
for _, m := range maps { for _, m := range maps {