feat(blog): add staging and production CI/CD

This commit is contained in:
dahyeon committed 2026-11-17 18:47:40 +09:00
1 parent ca3817f8da
commit b44398719c
25 files changed
+1219 -2

No files matched your search

+93
View File
@@ -0,0 +1,93 @@
# Blog CI/CD
`make-space`의 Tekton 구조를 따릅니다. `dahyeon/blog`의 `staging`/`prod` push만
받으며 `main`, PR, 브랜치 삭제 이벤트는 배포하지 않습니다. 두 환경 모두 각각
소스 revision을 빌드합니다. staging 이미지의 별도 승격 파이프라인은 없습니다.
```text
signed Gitea push
-> blog-clone (정확한 SHA와 브랜치 최신 커밋 확인)
-> blog-quality (fmt + Rust tests/architecture + SSR/WASM check)
-> blog-build-arm64 (rootless BuildKit -> Harbor)
-> blog-update-gitops (환경별 digest/source revision/replica 커밋)
-> Argo CD 자동 Sync
```
| 브랜치 | Pipeline | 갱신 파일 | URL |
| --- | --- | --- | --- |
| `staging` | `blog-staging` | `apps/blog/overlays/staging/kustomization.yaml` | `https://blog.dahyeon.us` |
| `prod` | `blog-prod` | `apps/blog/overlays/prod/kustomization.yaml` | `https://rabbitmaus.com` |
## 실행 계약
`foundation.yaml`은 ServiceAccount와 namespace RBAC, `infisical-secret.yaml`은 CI
자격 증명, `tasks.yaml`과 `pipeline.yaml`은 실행 단계, `trigger.yaml`과 `ingress.yaml`은
서명된 webhook 수신을 담당합니다. 클러스터 범위 권한과 공통 리소스 정책은 platform에 둡니다.
PipelineRun은 공유 `tekton-ci`의 ARM64 노드, 10 GiB `local-path` PVC를 사용합니다.
최대 시간은 90분(Tasks 85분)입니다. quality의 Cargo jobs는 2이며 debug symbols와
incremental cache를 줄입니다. 공통 quota와 완료 실행 정리는 platform-state 소유입니다.
quality는 앱 저장소의 `sh tools/ci/check.sh`를 실행합니다. Rust 1.100.0,
rustfmt, wasm32 target으로 `ssr`와 `hydrate`를 분리 검증하고 아키텍처 검사·전체 Rust
테스트를 실행합니다. MongoDB/Infisical에는 연결하지 않습니다. 상호작용·라우팅·폼·
hydration 변경 시 필요한 Playwright 검증은 앱 README의 별도 절차로 실행합니다.
이 초안은 DB 기반 브라우저 테스트를 자동화하지 않습니다.
빌드는 같은 SHA를 별도 디렉터리에 clone하고 앱 Dockerfile을 실행합니다.
`sha-<40자리 소스 SHA>-<PipelineRun UID>` 태그로 push한 뒤 실제 digest를 배포합니다.
이미지에는 SSR 바이너리·site·라이선스가 들어가며 Node와 dev-ui는 포함하지 않습니다.
DB/Entra ID Secret은 quality, Docker build, WASM 번들에서 사용하지 않습니다.
GitOps push 직전에 소스 브랜치 최신 SHA를 다시 확인합니다. service-state가 병렬
실행으로 앞서간 경우 자동 rebase나 force push 없이 실패하므로 최신 소스로 재실행합니다.
어느 Task든 실패하면 후속 GitOps 변경은 실행하지 않습니다.
## 처음 연결할 때
1. 앱의 배포 브랜치에 `Dockerfile`, `.dockerignore`, `tools/ci/check.sh`와 컴파일에
필요한 생성 자산이 커밋되어 있어야 합니다. 로컬 미커밋 파일은 CI에 전달되지 않습니다.
2. Harbor `dahyeon/blog` 접근 권한을 준비합니다. CI에는 push robot을,
`blog-staging`/`blog-prod`의 `harbor-registry`에는 pull 권한을 준비합니다.
기존 서비스와 동일하게 pull Secret 생성은 이 매니페스트의 범위 밖입니다.
3. 플랫폼 Infisical 프로젝트 `8520b8c0-3796-4fd6-a03c-6f0508c8c42c`, 환경 `prod`,
경로 `/platform/tekton/blog`에 다음 값을 등록합니다.
| 키 | 용도 |
| --- | --- |
| `GITEA_USERNAME` | 소스 읽기·service-state 쓰기 bot |
| `GITEA_TOKEN` | 해당 bot의 토큰 |
| `HARBOR_DOCKER_CONFIG_JSON` | CI push용 Docker config JSON |
| `GITEA_WEBHOOK_SECRET` | push 서명 검증 |
4. [앱 런타임 Secret](../../apps/blog/README.md)의 staging/prod 6개 키와 공유
`infisical-auth` identity의 프로젝트·환경·경로 권한을 확인합니다.
5. platform-state의 네임스페이스·EventListener ClusterRole/Binding·`blog-ci`
Application·prod 자동 Sync 허용·`rabbitmaus.com` HTTP-01 solver를 반영합니다.
service-state의 `ci/blog`, 앱 overlays도 `main`에 반영합니다. 두 저장소 사이의
적용 순서는 sync-wave만으로 보장되지 않으므로 컨트롤러·네임스페이스·Secret이
준비된 뒤 첫 push를 보냅니다. 초안은 두 환경 모두 replica 0으로 시작합니다.
6. 앱 DNS가 Ingress로 연결되도록 설정합니다. `rabbitmaus.com`의 HTTP-01 challenge
경로는 외부에서 접근 가능해야 합니다. 모든 블로그 Ingress는 SSL redirect를 끕니다.
7. Gitea `dahyeon/blog`에 JSON push webhook
`https://tekton-hook.dahyeon.us/blog`를 등록하고 동일한 서명 secret을 사용합니다.
공유 webhook 호스트의 TLS Secret은 기존 lolympus Ingress가 발급합니다.
초안 작성만으로 webhook, Harbor 권한, Secret 값, DNS를 생성하거나 클러스터에 적용하지
않습니다. DB 마이그레이션·시드와 Entra ID 기능 구현도 실행하지 않습니다.
## 검증과 운영
```sh
kubectl kustomize ci/blog
kubectl kustomize apps/blog/overlays/staging
kubectl kustomize apps/blog/overlays/prod
```
CRD와 namespace가 준비된 클러스터에서는 별도로
`kubectl apply --dry-run=server -k ci/blog`를 실행합니다. 실제 연결 검증은 서명된 staging
push 한 건으로 PipelineRun, Harbor digest, service-state 커밋, Argo CD Sync, `/healthz`와
SSR/hydration을 확인합니다. 잘못된 서명·다른 브랜치·삭제 SHA는 실행을 만들면 안 됩니다.
Secret 갱신 후 앱 Pod 재생성이 필요하며, 파이프라인의 성공은 Argo CD rollout 완료를
의미하지 않습니다. 배포 완료는 해당 Application의 Synced/Healthy 상태까지 확인합니다.
+55
View File
@@ -0,0 +1,55 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: blog-pipeline
automountServiceAccountToken: false
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: blog-event-listener
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: blog-event-listener
rules:
- apiGroups: [tekton.dev]
resources: [pipelineruns]
verbs: [create, get, list]
- apiGroups: [triggers.tekton.dev]
resources:
[
eventlisteners,
interceptors,
triggerbindings,
triggertemplates,
triggers,
]
verbs: [get, list, watch]
- apiGroups: [""]
resources: [configmaps]
verbs: [get, list, watch]
- apiGroups: [""]
resources: [serviceaccounts]
resourceNames: [blog-pipeline]
verbs: [impersonate]
- apiGroups: [""]
resources: [events]
verbs: [create, patch]
- apiGroups: [""]
resources: [secrets]
resourceNames: [blog-webhook]
verbs: [get]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: blog-event-listener
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: blog-event-listener
subjects:
- kind: ServiceAccount
name: blog-event-listener
+45
View File
@@ -0,0 +1,45 @@
apiVersion: secrets.infisical.com/v1beta1
kind: InfisicalStaticSecret
metadata:
name: blog-ci-credentials
spec:
infisicalAuthRef:
name: infisical-auth
namespace: infisical
syncOptions:
refreshInterval: 60s
instantUpdates: false
sources:
- projectId: 8520b8c0-3796-4fd6-a03c-6f0508c8c42c
environmentSlug: prod
secretPath: /platform/tekton/blog
recursive: false
targets:
- name: blog-gitea
namespace: tekton-ci
kind: Secret
creationPolicy: Owner
secretType: kubernetes.io/basic-auth
template:
engineVersion: v1
data:
username: "{{ .GITEA_USERNAME.Value }}"
password: "{{ .GITEA_TOKEN.Value }}"
- name: blog-harbor
namespace: tekton-ci
kind: Secret
creationPolicy: Owner
secretType: kubernetes.io/dockerconfigjson
template:
engineVersion: v1
data:
.dockerconfigjson: "{{ .HARBOR_DOCKER_CONFIG_JSON.Value }}"
- name: blog-webhook
namespace: tekton-ci
kind: Secret
creationPolicy: Owner
secretType: Opaque
template:
engineVersion: v1
data:
secretToken: "{{ .GITEA_WEBHOOK_SECRET.Value }}"
+23
View File
@@ -0,0 +1,23 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: blog-main-webhook
annotations:
haproxy.org/ssl-redirect: 'false'
spec:
ingressClassName: haproxy
tls:
- hosts: [tekton-hook.dahyeon.us]
# The existing lolympus Ingress owns issuance for this shared hostname.
secretName: lolympus-main-webhook-tls
rules:
- host: tekton-hook.dahyeon.us
http:
paths:
- path: /blog
pathType: Prefix
backend:
service:
name: el-blog-main
port:
number: 8080
+16
View File
@@ -0,0 +1,16 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: tekton-ci
resources:
- foundation.yaml
- infisical-secret.yaml
- tasks.yaml
- pipeline.yaml
- trigger.yaml
- ingress.yaml
labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: blog
app.kubernetes.io/part-of: blog-ci
app.kubernetes.io/managed-by: argocd
+145
View File
@@ -0,0 +1,145 @@
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
name: blog-staging
spec:
description: Validate an exact staging branch revision, publish an arm64 full-stack Leptos image, then update staging GitOps.
params:
- name: git-revision
type: string
results:
- name: image-digest
value: $(tasks.build-arm64.results.image-digest)
- name: gitops-commit
value: $(tasks.update-gitops.results.gitops-commit)
workspaces:
- name: source
- name: gitea-credentials
- name: harbor-dockerconfig
tasks:
- name: clone
taskRef:
name: blog-clone
params:
- name: revision
value: $(params.git-revision)
- name: environment
value: staging
workspaces:
- name: source
workspace: source
- name: credentials
workspace: gitea-credentials
- name: quality
runAfter:
- clone
taskRef:
name: blog-quality
workspaces:
- name: source
workspace: source
- name: build-arm64
runAfter:
- quality
taskRef:
name: blog-build-arm64
params:
- name: revision
value: $(params.git-revision)
- name: image
value: registry.dahyeon.us/dahyeon/blog:sha-$(params.git-revision)-$(context.pipelineRun.uid)
workspaces:
- name: credentials
workspace: gitea-credentials
- name: dockerconfig
workspace: harbor-dockerconfig
- name: update-gitops
runAfter:
- build-arm64
taskRef:
name: blog-update-gitops
params:
- name: revision
value: $(params.git-revision)
- name: environment
value: staging
- name: image-digest
value: $(tasks.build-arm64.results.image-digest)
workspaces:
- name: source
workspace: source
- name: credentials
workspace: gitea-credentials
---
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
name: blog-prod
spec:
description: Validate an exact prod branch revision, publish an arm64 full-stack Leptos image, then update production GitOps.
params:
- name: git-revision
type: string
results:
- name: image-digest
value: $(tasks.build-arm64.results.image-digest)
- name: gitops-commit
value: $(tasks.update-gitops.results.gitops-commit)
workspaces:
- name: source
- name: gitea-credentials
- name: harbor-dockerconfig
tasks:
- name: clone
taskRef:
name: blog-clone
params:
- name: revision
value: $(params.git-revision)
- name: environment
value: prod
workspaces:
- name: source
workspace: source
- name: credentials
workspace: gitea-credentials
- name: quality
runAfter:
- clone
taskRef:
name: blog-quality
workspaces:
- name: source
workspace: source
- name: build-arm64
runAfter:
- quality
taskRef:
name: blog-build-arm64
params:
- name: revision
value: $(params.git-revision)
- name: image
value: registry.dahyeon.us/dahyeon/blog:sha-$(params.git-revision)-$(context.pipelineRun.uid)
workspaces:
- name: credentials
workspace: gitea-credentials
- name: dockerconfig
workspace: harbor-dockerconfig
- name: update-gitops
runAfter:
- build-arm64
taskRef:
name: blog-update-gitops
params:
- name: revision
value: $(params.git-revision)
- name: environment
value: prod
- name: image-digest
value: $(tasks.build-arm64.results.image-digest)
workspaces:
- name: source
workspace: source
- name: credentials
workspace: gitea-credentials
+419
View File
@@ -0,0 +1,419 @@
apiVersion: tekton.dev/v1
kind: Task
metadata:
name: blog-clone
spec:
description: Clone the pushed source revision and verify the selected deployment branch.
params:
- name: revision
type: string
- name: environment
type: string
default: staging
workspaces:
- name: source
- name: credentials
readOnly: true
steps:
- name: clone
image: docker.io/alpine/git:2.49.1@sha256:c0280cf9572316299b08544065d3bf35db65043d5e3963982ec50647d2746e26
computeResources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: "1"
memory: 1Gi
env:
- name: REPO_URL
value: https://git.dahyeon.us/dahyeon/blog.git
- name: REVISION
value: $(params.revision)
- name: DEPLOY_ENV
value: $(params.environment)
- name: SOURCE_DIR
value: $(workspaces.source.path)
- name: GITEA_CREDENTIALS_DIR
value: $(workspaces.credentials.path)
script: |
#!/bin/sh
set -eu
umask 0002
case "$DEPLOY_ENV" in staging|prod) ;; *) echo 'Invalid deployment environment' >&2; exit 1;; esac
printf '%s\n' "$REVISION" | grep -Eq '^[0-9a-f]{40}$'
test "$REVISION" != '0000000000000000000000000000000000000000'
case "$SOURCE_DIR" in /workspace/*) ;; *) echo 'Unexpected workspace path' >&2; exit 1;; esac
AUTH_DIR="$(mktemp -d)"
trap 'rm -rf "$AUTH_DIR"' EXIT
cat >"$AUTH_DIR/askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) cat "$GITEA_CREDENTIALS_DIR/username" ;;
*Password*) cat "$GITEA_CREDENTIALS_DIR/password" ;;
*) exit 1 ;;
esac
EOF
chmod 0700 "$AUTH_DIR/askpass"
export GIT_ASKPASS="$AUTH_DIR/askpass" GIT_TERMINAL_PROMPT=0
REMOTE_REVISION="$(git ls-remote "$REPO_URL" "refs/heads/$DEPLOY_ENV" | awk 'NR == 1 {print $1}')"
if [ "$REMOTE_REVISION" != "$REVISION" ]; then
echo 'Source revision was superseded before checkout.' >&2
exit 1
fi
find "$SOURCE_DIR" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
git clone --quiet --no-tags "$REPO_URL" "$SOURCE_DIR"
git -C "$SOURCE_DIR" checkout --quiet --detach "$REVISION"
test "$(git -C "$SOURCE_DIR" rev-parse HEAD)" = "$REVISION"
---
apiVersion: tekton.dev/v1
kind: Task
metadata:
name: blog-quality
spec:
description: Check formatting, architecture, Rust tests, SSR, and WASM without runtime credentials.
workspaces:
- name: source
stepTemplate:
workingDir: $(workspaces.source.path)
env:
- name: CI
value: "true"
steps:
- name: verify-rust
image: docker.io/library/rust:1.100.0-trixie@sha256:e19840879045c951c905d0eaa9887f3439c62000e429963371b376bac8d38c31
computeResources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: "4"
memory: 8Gi
env:
- name: PATH
value: /usr/local/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
- name: CARGO_HOME
value: /usr/local/cargo
- name: CARGO_BUILD_JOBS
value: "2"
- name: CARGO_INCREMENTAL
value: "0"
- name: CARGO_PROFILE_DEV_DEBUG
value: "0"
- name: CARGO_PROFILE_TEST_DEBUG
value: "0"
script: |
#!/bin/sh
set -eu
rustup component add rustfmt
rustup target add wasm32-unknown-unknown
sh tools/ci/check.sh
---
apiVersion: tekton.dev/v1
kind: Task
metadata:
name: blog-build-arm64
spec:
description: Build and push the linux/arm64 full-stack Leptos image natively using rootless BuildKit.
params:
- name: revision
type: string
- name: image
type: string
results:
- name: image-url
description: Published repository and unique tag.
- name: image-digest
description: Immutable linux/arm64 image digest.
workspaces:
- name: credentials
readOnly: true
- name: dockerconfig
readOnly: true
volumes:
- name: build-source
emptyDir: {}
- name: buildkit-state
emptyDir: {}
steps:
- name: clone-source
image: docker.io/alpine/git:2.49.1@sha256:c0280cf9572316299b08544065d3bf35db65043d5e3963982ec50647d2746e26
computeResources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: "1"
memory: 1Gi
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
workspaces:
- name: credentials
volumeMounts:
- name: build-source
mountPath: /workspace/build
env:
- name: REPO_URL
value: https://git.dahyeon.us/dahyeon/blog.git
- name: REVISION
value: $(params.revision)
- name: GITEA_CREDENTIALS_DIR
value: $(workspaces.credentials.path)
script: |
#!/bin/sh
set -eu
umask 0002
printf '%s\n' "$REVISION" | grep -Eq '^[0-9a-f]{40}$'
test "$REVISION" != '0000000000000000000000000000000000000000'
AUTH_DIR="$(mktemp -d)"
trap 'rm -rf "$AUTH_DIR"' EXIT
cat >"$AUTH_DIR/askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) cat "$GITEA_CREDENTIALS_DIR/username" ;;
*Password*) cat "$GITEA_CREDENTIALS_DIR/password" ;;
*) exit 1 ;;
esac
EOF
chmod 0700 "$AUTH_DIR/askpass"
export GIT_ASKPASS="$AUTH_DIR/askpass" GIT_TERMINAL_PROMPT=0
git clone --quiet --no-tags "$REPO_URL" /workspace/build/source
git -C /workspace/build/source checkout --quiet --detach "$REVISION"
test "$(git -C /workspace/build/source rev-parse HEAD)" = "$REVISION"
- name: build-and-push
image: docker.io/moby/buildkit:v0.31.1-rootless@sha256:946cf909534b789c9b84af75e6d4f8cb23c3b9cb387daec5ba0f4878a3e4647c
computeResources:
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "4"
memory: 8Gi
securityContext:
privileged: false
allowPrivilegeEscalation: true
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
seccompProfile:
type: Unconfined
appArmorProfile:
type: Unconfined
workspaces:
- name: dockerconfig
volumeMounts:
- name: build-source
mountPath: /workspace/build
- name: buildkit-state
mountPath: /home/user/.local/share/buildkit
env:
- name: BUILDKITD_FLAGS
value: --oci-worker-no-process-sandbox
- name: DOCKER_CONFIG
value: $(workspaces.dockerconfig.path)
- name: IMAGE
value: $(params.image)
- name: METADATA_FILE
value: /workspace/build/build-metadata.json
script: |
#!/bin/sh
set -eu
printf '%s\n' "$IMAGE" | grep -Eq '^registry\.dahyeon\.us/dahyeon/blog:sha-[0-9a-f]{40}-[a-zA-Z0-9-]+$'
buildctl-daemonless.sh build \
--frontend dockerfile.v0 \
--local context=/workspace/build/source \
--local dockerfile=/workspace/build/source \
--opt filename=Dockerfile \
--opt platform=linux/arm64 \
--output "type=image,name=$IMAGE,push=true" \
--metadata-file "$METADATA_FILE"
- name: record-digest
image: docker.io/mikefarah/yq:4.47.2@sha256:76def1f56f456ecc1c3173ea275218ee17139bc2018c5a07887b15afd88ec03e
computeResources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 250m
memory: 256Mi
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
volumeMounts:
- name: build-source
mountPath: /workspace/build
readOnly: true
env:
- name: IMAGE
value: $(params.image)
- name: METADATA_FILE
value: /workspace/build/build-metadata.json
- name: DIGEST_RESULT_PATH
value: $(results.image-digest.path)
- name: IMAGE_RESULT_PATH
value: $(results.image-url.path)
script: |
#!/bin/sh
set -eu
DIGEST="$(yq -r '."containerimage.digest"' "$METADATA_FILE")"
printf '%s\n' "$DIGEST" | grep -Eq '^sha256:[0-9a-f]{64}$'
printf '%s' "$IMAGE" >"$IMAGE_RESULT_PATH"
printf '%s' "$DIGEST" >"$DIGEST_RESULT_PATH"
---
apiVersion: tekton.dev/v1
kind: Task
metadata:
name: blog-update-gitops
spec:
description: Publish the selected environment's app digest to service-state keeping replicas at 1.
params:
- name: revision
type: string
- name: image-digest
type: string
- name: environment
type: string
default: staging
results:
- name: gitops-commit
description: Commit pushed to service-state main.
workspaces:
- name: source
- name: credentials
readOnly: true
stepTemplate:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
env:
- name: STATE_REPO_URL
value: https://git.dahyeon.us/dahyeon/service-state.git
- name: SOURCE_REPO_URL
value: https://git.dahyeon.us/dahyeon/blog.git
- name: REVISION
value: $(params.revision)
- name: DEPLOY_ENV
value: $(params.environment)
- name: STATE_DIR
value: $(workspaces.source.path)/.cache/gitops-state
- name: GITEA_CREDENTIALS_DIR
value: $(workspaces.credentials.path)
steps:
- name: clone-state
image: docker.io/alpine/git:2.49.1@sha256:c0280cf9572316299b08544065d3bf35db65043d5e3963982ec50647d2746e26
computeResources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 500m
memory: 512Mi
script: |
#!/bin/sh
set -eu
printf '%s\n' "$REVISION" | grep -Eq '^[0-9a-f]{40}$'
case "$STATE_DIR" in /workspace/*/.cache/gitops-state) ;; *) echo 'Unexpected GitOps path' >&2; exit 1;; esac
AUTH_DIR="$(mktemp -d)"
trap 'rm -rf "$AUTH_DIR"' EXIT
cat >"$AUTH_DIR/askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) cat "$GITEA_CREDENTIALS_DIR/username" ;;
*Password*) cat "$GITEA_CREDENTIALS_DIR/password" ;;
*) exit 1 ;;
esac
EOF
chmod 0700 "$AUTH_DIR/askpass"
export GIT_ASKPASS="$AUTH_DIR/askpass" GIT_TERMINAL_PROMPT=0
rm -rf "$STATE_DIR"
git clone --quiet --depth=1 --branch main "$STATE_REPO_URL" "$STATE_DIR"
- name: update-manifest
image: docker.io/mikefarah/yq:4.47.2@sha256:76def1f56f456ecc1c3173ea275218ee17139bc2018c5a07887b15afd88ec03e
computeResources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 250m
memory: 256Mi
env:
- name: APP_IMAGE
value: registry.dahyeon.us/dahyeon/blog
- name: IMAGE_DIGEST
value: $(params.image-digest)
- name: DEPLOYMENT_NAME
value: blog
script: |
#!/bin/sh
set -eu
case "$DEPLOY_ENV" in staging|prod) ;; *) echo 'Invalid deployment environment' >&2; exit 1;; esac
printf '%s\n' "$IMAGE_DIGEST" | grep -Eq '^sha256:[0-9a-f]{64}$'
MANIFEST="$STATE_DIR/apps/blog/overlays/$DEPLOY_ENV/kustomization.yaml"
test "$(yq '[.images[] | select(.name == strenv(APP_IMAGE))] | length' "$MANIFEST")" = 1
test "$(yq '[.replicas[] | select(.name == strenv(DEPLOYMENT_NAME))] | length' "$MANIFEST")" = 1
yq -i '(.images[] | select(.name == strenv(APP_IMAGE))) |= (del(.newTag) | .digest = strenv(IMAGE_DIGEST))' "$MANIFEST"
yq -i '(.replicas[] | select(.name == strenv(DEPLOYMENT_NAME))).count = 1' "$MANIFEST"
yq -i '.commonAnnotations."blog.dahyeon.us/source-revision" = strenv(REVISION)' "$MANIFEST"
- name: commit-and-push
image: docker.io/alpine/git:2.49.1@sha256:c0280cf9572316299b08544065d3bf35db65043d5e3963982ec50647d2746e26
computeResources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 500m
memory: 512Mi
env:
- name: GITOPS_RESULT_PATH
value: $(results.gitops-commit.path)
script: |
#!/bin/sh
set -eu
AUTH_DIR="$(mktemp -d)"
trap 'rm -rf "$AUTH_DIR"' EXIT
cat >"$AUTH_DIR/askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) cat "$GITEA_CREDENTIALS_DIR/username" ;;
*Password*) cat "$GITEA_CREDENTIALS_DIR/password" ;;
*) exit 1 ;;
esac
EOF
chmod 0700 "$AUTH_DIR/askpass"
export GIT_ASKPASS="$AUTH_DIR/askpass" GIT_TERMINAL_PROMPT=0
BASE_COMMIT="$(git -C "$STATE_DIR" rev-parse HEAD)"
REMOTE_STATE="$(git ls-remote "$STATE_REPO_URL" refs/heads/main | awk 'NR == 1 {print $1}')"
if [ "$REMOTE_STATE" != "$BASE_COMMIT" ]; then
echo 'service-state advanced; rerun from the latest source. No automatic rebase or force push.' >&2
exit 1
fi
git -C "$STATE_DIR" config user.name blog-tekton
git -C "$STATE_DIR" config user.email tekton@dahyeon.us
if git -C "$STATE_DIR" diff --quiet; then
git -C "$STATE_DIR" rev-parse HEAD >"$GITOPS_RESULT_PATH"
exit 0
fi
git -C "$STATE_DIR" add "apps/blog/overlays/$DEPLOY_ENV/kustomization.yaml"
git -C "$STATE_DIR" commit -m "chore(blog): deploy $DEPLOY_ENV $REVISION"
REMOTE_REVISION="$(git ls-remote "$SOURCE_REPO_URL" "refs/heads/$DEPLOY_ENV" | awk 'NR == 1 {print $1}')"
if [ "$REMOTE_REVISION" != "$REVISION" ]; then
echo 'Source revision was superseded before GitOps push.' >&2
exit 1
fi
git -C "$STATE_DIR" push origin HEAD:main
git -C "$STATE_DIR" rev-parse HEAD >"$GITOPS_RESULT_PATH"
+101
View File
@@ -0,0 +1,101 @@
apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
name: blog-main
spec:
params:
- name: git-revision
value: $(body.after)
- name: environment
value: $(extensions.environment)
---
apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerTemplate
metadata:
name: blog-main
spec:
params:
- name: git-revision
- name: environment
resourcetemplates:
- apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
generateName: blog-$(tt.params.environment)-
labels:
app.kubernetes.io/name: blog
app.kubernetes.io/part-of: blog-ci
spec:
pipelineRef:
name: blog-$(tt.params.environment)
params:
- name: git-revision
value: $(tt.params.git-revision)
taskRunTemplate:
serviceAccountName: blog-pipeline
podTemplate:
nodeSelector:
kubernetes.io/arch: arm64
securityContext:
fsGroup: 1000
fsGroupChangePolicy: OnRootMismatch
workspaces:
- name: source
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce
storageClassName: local-path
resources:
requests:
storage: 10Gi
- name: gitea-credentials
secret:
secretName: blog-gitea
items:
- key: username
path: username
- key: password
path: password
- name: harbor-dockerconfig
secret:
secretName: blog-harbor
items:
- key: .dockerconfigjson
path: config.json
timeouts:
pipeline: 90m
tasks: 85m
---
apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:
name: blog-main
spec:
serviceAccountName: blog-event-listener
triggers:
- name: branch-push
interceptors:
- ref:
name: github
params:
- name: secretRef
value:
secretName: blog-webhook
secretKey: secretToken
- name: eventTypes
value:
- push
- ref:
name: cel
params:
- name: filter
value: body.repository.full_name == 'dahyeon/blog' && body.ref in ['refs/heads/staging', 'refs/heads/prod'] && body.after.matches('^[0-9a-f]{40}$') && body.after != '0000000000000000000000000000000000000000'
- name: overlays
value:
- key: environment
expression: "body.ref.split('/')[2]"
bindings:
- ref: blog-main
template:
ref: blog-main