Nhiệm vụ của CI không phải là "deploy". Nhiệm vụ của nó là biến một commit thành một artifact đáng tin cậy — đã test, đã quét, đã gắn tag bất biến — rồi ghi ý định deploy vào Git. Việc đưa lên cluster là của ArgoCD. Tách hai việc này là điểm then chốt.
Mười mục: nguyên lý và ranh giới CI/CD (1) → Jenkins trên Kubernetes (2) → Jenkinsfile đầy đủ (3) → build theo runtime (4) → cổng chất lượng (5) → ECR và cập nhật GitOps (6) → shared library (7) → credentials (8) → GitHub Actions / GitLab CI (9) → checklist (10).
kubectl apply và không gọi
helm upgrade vào production. Nó build, test, quét, push ảnh, rồi commit một dòng
vào repo cấu hình. ArgoCD thấy commit đó và đồng bộ cluster.
Jenkins gọi helm upgrade | Jenkins commit vào Git, ArgoCD sync |
|---|---|
| Jenkins cần credential có quyền ghi vào cluster production. Jenkins bị chiếm quyền là cluster bị chiếm quyền. | Jenkins chỉ cần quyền ghi vào một repo Git. Không có credential cluster nào trong Jenkins. |
Không biết cluster đang chạy gì. Ai đó sửa bằng kubectl thì không ai phát
hiện. |
Git là nguồn sự thật. ArgoCD liên tục so sánh và báo sai lệch. |
| Rollback là chạy lại job cũ — mà job cũ có thể đã không còn tái lập được. | Rollback là git revert. Luôn tái lập được. |
| Lịch sử deploy nằm trong log Jenkins, bị xoá theo retention. | Lịch sử deploy là git log của repo cấu hình. Vĩnh viễn, có review, có người phê duyệt. |
| Tạo lại cluster từ đầu phải chạy lại hàng chục job theo đúng thứ tự. | Trỏ ArgoCD vào repo là cluster tự dựng lại. |
order-service/ ← repo CODE. Developer làm việc ở đây.
├── src/
├── pom.xml
├── Dockerfile
└── Jenkinsfile ← pipeline CI
gitops-config/ ← repo CẤU HÌNH. Jenkins và người vận hành ghi vào.
├── apps/
│ └── order-service/
│ ├── base.yaml
│ ├── dev.yaml ← Jenkins tự bump image.tag ở đây
│ ├── staging.yaml ← Jenkins bump sau khi test staging xong
│ └── prod.yaml ← người phê duyệt bump, qua pull request
└── argocd/
└── applicationset.yaml
prod.yaml.[skip ci] và logic loại trừ — phức tạp và dễ sai.| Nguyên tắc | Lý do |
|---|---|
| Fail nhanh | Xếp bước nhanh và hay fail lên trước: lint, unit test, quét secret. Đừng để developer chờ 15 phút mới biết sai một dấu phẩy. |
| Build một lần | Một artifact đi qua mọi môi trường. Build lại cho từng môi trường là mất ý nghĩa của việc test. |
| Tag bất biến | Git SHA. Không bao giờ deploy latest. |
| Pipeline là code | Jenkinsfile trong repo, review qua pull request. Không cấu hình job bằng giao diện
web — không ai biết ai đổi gì lúc nào. |
| Không trạng thái | Agent động, build xong là xoá. Build không được phụ thuộc vào thứ gì còn lại từ build trước. |
| Idempotent | Chạy lại cùng commit phải ra cùng kết quả. Dùng lockfile, ghim phiên bản base image. |
helm upgrade?Agent tĩnh (một VM cài sẵn mọi SDK) là mô hình cũ và gây nhiều vấn đề: phiên bản SDK lệch nhau, build này làm bẩn build khác, phải trả tiền cho VM rỗi. Trên EKS, dùng agent động: mỗi build một pod mới, chạy xong là xoá.
controller:
image:
tag: "2.479.1-lts-jdk21"
resources:
requests: { cpu: 500m, memory: 2Gi }
limits: { cpu: 2000m, memory: 4Gi }
# Cài plugin khai báo được — không cài tay qua giao diện
installPlugins:
- kubernetes:4296.v20a_7e4d78a_a_7
- workflow-aggregator:600.vb_57cdd26fdd7
- git:5.6.0
- configuration-as-code:1850.va_a_c5e0e9f6e9
- credentials-binding:687.v619cb_15e923f
- pipeline-utility-steps:2.18.0
- sonar:2.17.2
- warnings-ng:11.9.0
- junit:1301.vc0e86c0b_cb_4b
- pipeline-stage-view:2.34
- matrix-auth:3.2.6
- job-dsl:1.87
# Dùng IRSA để Jenkins gọi được ECR và Secrets Manager mà không cần access key
serviceAccount:
create: true
name: jenkins
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/jenkins-controller
ingress:
enabled: true
ingressClassName: alb
annotations:
alb.ingress.kubernetes.io/scheme: internal # KHÔNG phơi Jenkins ra internet
alb.ingress.kubernetes.io/target-type: ip
hostName: jenkins.internal.example.com
# Jenkins Configuration as Code — toàn bộ cấu hình nằm trong Git
JCasC:
defaultConfig: true
configScripts:
agent-pod-templates: |
jenkins:
clouds:
- kubernetes:
name: eks
serverUrl: https://kubernetes.default
namespace: jenkins-agents
jenkinsUrl: http://jenkins.jenkins.svc.cluster.local:8080
containerCapStr: "30"
podRetention: never
templates:
- name: default
label: default
yamlMergeStrategy: merge
security: |
jenkins:
authorizationStrategy:
roleBased:
roles:
global:
- name: admin
permissions: ["Overall/Administer"]
assignments: ["platform-team"]
- name: developer
permissions:
- "Overall/Read"
- "Job/Build"
- "Job/Read"
- "Job/Cancel"
assignments: ["developers"]
unclassified: |
location:
url: https://jenkins.internal.example.com/
persistence:
enabled: true
storageClass: gp3
size: 50Gi
agent:
enabled: true
namespace: jenkins-agents
podRetention: Never
resources:
requests: { cpu: 200m, memory: 512Mi }
limits: { cpu: 1000m, memory: 1Gi }
helm repo add jenkins https://charts.jenkins.io
helm upgrade --install jenkins jenkins/jenkins \
-n jenkins --create-namespace \
-f jenkins-values.yaml
scheme: internal, truy cập qua VPN hoặc SSO với MFA. Và bật
Role-Based Authorization — mặc định "logged-in users can do anything" là không chấp nhận được
cho production.
Cách rõ ràng nhất là khai pod agent ngay trong Jenkinsfile. Mỗi container
là một công cụ; step chạy trong container nào thì chỉ thấy công cụ của container đó.
pipeline {
agent {
kubernetes {
defaultContainer 'jnlp'
yaml """
apiVersion: v1
kind: Pod
spec:
serviceAccountName: jenkins-agent # IRSA để gọi ECR
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
# Ưu tiên node spot cho agent CI — build lại được nên chịu được gián đoạn
nodeSelector:
karpenter.sh/capacity-type: spot
tolerations:
- key: workload
operator: Equal
value: ci
effect: NoSchedule
containers:
# --- Build Java ---
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['sleep']
args: ['infinity']
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '4', memory: 4Gi }
volumeMounts:
- { name: m2, mountPath: /root/.m2 }
# --- Build image: Kaniko, KHÔNG cần Docker daemon ---
- name: kaniko
image: gcr.io/kaniko-project/executor:v1.23.2-debug
command: ['sleep']
args: ['infinity']
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '2', memory: 4Gi }
# --- Công cụ: aws, kubectl, helm, yq, git, trivy ---
- name: tools
image: 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/ci-tools:v3
command: ['sleep']
args: ['infinity']
resources:
requests: { cpu: 200m, memory: 512Mi }
limits: { cpu: '1', memory: 1Gi }
volumes:
# PVC dùng chung để cache .m2 giữa các build
- name: m2
persistentVolumeClaim:
claimName: jenkins-m2-cache
"""
}
}
// ...
}
| Cách | Cần privileged? | Đánh đổi |
|---|---|---|
| Kaniko khuyến nghị |
Không | Build trong userspace, không cần daemon. An toàn nhất. Cache qua registry. Nhược điểm: chậm hơn
BuildKit, và không hỗ trợ RUN --mount=type=cache. |
| BuildKit nhanh nhất |
Rootless được | Nhanh nhất, hỗ trợ đầy đủ cache mount và multi-arch. Triển khai buildkitd như
Deployment với PVC để dùng chung cache giữa các agent. |
| Docker-in-Docker | Có | Cần privileged: true — pod có quyền gần như root trên node. Tránh trong môi
trường nhiều đội dùng chung. |
| Docker socket mount | Tương đương | Mount /var/run/docker.sock. Tệ hơn DinD: build có thể can thiệp vào container khác
trên cùng node. Không dùng. |
apiVersion: apps/v1
kind: Deployment
metadata:
name: buildkitd
namespace: jenkins-agents
spec:
replicas: 2
selector:
matchLabels: { app: buildkitd }
template:
metadata:
labels: { app: buildkitd }
spec:
containers:
- name: buildkitd
image: moby/buildkit:v0.17.2-rootless
args:
- --addr=tcp://0.0.0.0:1234
- --oci-worker-no-process-sandbox
securityContext:
seccompProfile: { type: Unconfined }
appArmorProfile: { type: Unconfined }
runAsUser: 1000
runAsGroup: 1000
resources:
requests: { cpu: '2', memory: 4Gi }
limits: { cpu: '4', memory: 8Gi }
volumeMounts:
- { name: cache, mountPath: /home/user/.local/share/buildkit }
volumes:
- name: cache
persistentVolumeClaim:
claimName: buildkit-cache
Pipeline declarative hoàn chỉnh cho service Java trên EKS. Mỗi stage có chú thích lý do. Phiên bản cho Python và .NET ở mục 4.
@Library('platform-pipeline-lib@v2') _
def IMAGE_TAG = ''
def ECR_REGISTRY = '123456789012.dkr.ecr.ap-southeast-1.amazonaws.com'
def ECR_REPO = 'order-service'
def GITOPS_REPO = 'git@github.com:myorg/gitops-config.git'
pipeline {
agent {
kubernetes {
defaultContainer 'maven'
yamlFile 'ci/agent-pod.yaml' // tách pod template ra file riêng cho gọn
}
}
options {
// Giới hạn lịch sử để Jenkins không phình đĩa
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '10'))
// Không cho hai build của cùng nhánh chạy song song — tránh tranh chấp tag
disableConcurrentBuilds()
timeout(time: 45, unit: 'MINUTES')
timestamps()
ansiColor('xterm')
// Mặc định KHÔNG checkout, để tự kiểm soát ở stage Checkout
skipDefaultCheckout(true)
}
environment {
AWS_REGION = 'ap-southeast-1'
SONAR_HOST = 'https://sonar.internal.example.com'
// Tắt tải phiên bản mới của Maven wrapper, build phải tái lập được
MAVEN_OPTS = '-Dmaven.repo.local=/root/.m2/repository -Xmx3g'
}
stages {
// ---------------------------------------------------------------
stage('Checkout') {
steps {
script {
def scmVars = checkout scm
env.GIT_SHA = scmVars.GIT_COMMIT.take(7)
env.GIT_SHA_FULL = scmVars.GIT_COMMIT
env.GIT_BRANCH_NAME = env.BRANCH_NAME ?: scmVars.GIT_BRANCH
IMAGE_TAG = env.GIT_SHA
// Tên build hiện trong giao diện Jenkins, dễ truy vết
currentBuild.displayName = "#${BUILD_NUMBER} ${env.GIT_BRANCH_NAME}@${env.GIT_SHA}"
}
}
}
// ---------------------------------------------------------------
// Fail nhanh: quét secret TRƯỚC khi làm bất cứ việc gì tốn thời gian
stage('Quét secret') {
steps {
container('tools') {
sh '''
set -euo pipefail
gitleaks detect --source . --redact --no-banner \
--report-format sarif --report-path gitleaks.sarif
'''
}
}
post {
always {
recordIssues(tools: [sarif(pattern: 'gitleaks.sarif', id: 'gitleaks')])
}
}
}
// ---------------------------------------------------------------
stage('Build & Unit test') {
steps {
container('maven') {
sh '''
set -euo pipefail
mvn -B -ntp clean verify \
-Dmaven.test.failure.ignore=false \
-Djacoco.skip=false
'''
}
}
post {
always {
junit testResults: '**/target/surefire-reports/*.xml', allowEmptyResults: false
recordCoverage(tools: [[parser: 'JACOCO', pattern: '**/target/site/jacoco/jacoco.xml']],
qualityGates: [[threshold: 70.0, metric: 'LINE', baseline: 'PROJECT']])
}
}
}
// ---------------------------------------------------------------
stage('Phân tích song song') {
parallel {
stage('SonarQube') {
steps {
container('maven') {
withSonarQubeEnv('sonar-internal') {
sh '''
set -euo pipefail
mvn -B -ntp sonar:sonar \
-Dsonar.projectKey=order-service \
-Dsonar.branch.name="${GIT_BRANCH_NAME}"
'''
}
}
}
}
stage('Quét dependency') {
steps {
container('tools') {
sh '''
set -euo pipefail
# Quét thư viện có lỗ hổng. --ignore-unfixed để không chặn
# vì CVE chưa có bản vá.
trivy fs --scanners vuln,license \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--exit-code 1 \
--format template --template "@/contrib/junit.tpl" \
-o trivy-fs.xml \
.
'''
}
}
post {
always { junit testResults: 'trivy-fs.xml', allowEmptyResults: true }
}
}
}
}
// ---------------------------------------------------------------
stage('Cổng chất lượng Sonar') {
steps {
// Chờ webhook từ Sonar. timeout để không treo pipeline mãi.
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
// ---------------------------------------------------------------
stage('Build image') {
steps {
container('kaniko') {
sh """
set -euo pipefail
/kaniko/executor \
--context "\$(pwd)" \
--dockerfile Dockerfile \
--destination "${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}" \
--destination "${ECR_REGISTRY}/${ECR_REPO}:${env.GIT_BRANCH_NAME.replaceAll('/','-')}" \
--cache=true \
--cache-repo "${ECR_REGISTRY}/${ECR_REPO}-cache" \
--cache-ttl=168h \
--snapshot-mode=redo \
--use-new-run \
--build-arg "GIT_SHA=${env.GIT_SHA_FULL}" \
--label "org.opencontainers.image.revision=${env.GIT_SHA_FULL}" \
--label "org.opencontainers.image.source=https://github.com/myorg/${ECR_REPO}" \
--label "org.opencontainers.image.created=\$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--image-fs-extract-retry 2
"""
}
}
}
// ---------------------------------------------------------------
stage('Quét image') {
steps {
container('tools') {
sh """
set -euo pipefail
aws ecr get-login-password --region ${AWS_REGION} \
| crane auth login --username AWS --password-stdin ${ECR_REGISTRY}
# Chặn pipeline nếu có CVE CRITICAL đã có bản vá
trivy image \
--severity CRITICAL \
--ignore-unfixed \
--exit-code 1 \
"${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}"
# HIGH: chỉ báo cáo, không chặn
trivy image --severity HIGH --ignore-unfixed --exit-code 0 \
--format template --template "@/contrib/junit.tpl" \
-o trivy-image.xml \
"${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}"
# Sinh SBOM để biết image chứa gì
trivy image --format cyclonedx \
-o sbom.json \
"${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}"
"""
}
}
post {
always {
junit testResults: 'trivy-image.xml', allowEmptyResults: true
archiveArtifacts artifacts: 'sbom.json', allowEmptyArchive: true
}
}
}
// ---------------------------------------------------------------
stage('Kiểm tra image') {
steps {
container('tools') {
sh """
set -euo pipefail
IMAGE="${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}"
# Lấy digest — thứ duy nhất bất biến thật sự
DIGEST=\$(crane digest "\$IMAGE")
echo "\$DIGEST" > image-digest.txt
echo "Digest: \$DIGEST"
# Kiểm các bất biến của image (xem chặng 03 mục 7)
CFG=\$(crane config "\$IMAGE")
USER=\$(echo "\$CFG" | jq -r '.config.User // ""')
[ -n "\$USER" ] && [ "\$USER" != "root" ] && [ "\$USER" != "0" ] \
|| { echo "LỖI: image chạy root"; exit 1; }
ENTRYPOINT=\$(echo "\$CFG" | jq -c '.config.Entrypoint // []')
echo "\$ENTRYPOINT" | grep -qE '"(/bin/)?sh","-c"' \
&& { echo "LỖI: ENTRYPOINT dùng shell form, sẽ mất SIGTERM"; exit 1; }
echo "OK: image hợp lệ"
"""
script {
env.IMAGE_DIGEST = readFile('image-digest.txt').trim()
}
}
}
}
// ---------------------------------------------------------------
stage('Render & kiểm Helm') {
steps {
container('tools') {
sh """
set -euo pipefail
rm -rf gitops && git clone --depth 1 ${GITOPS_REPO} gitops
helm lint ./gitops/charts/generic-service \
-f ./gitops/apps/${ECR_REPO}/base.yaml \
-f ./gitops/apps/${ECR_REPO}/prod.yaml \
--strict
# Render ra manifest để kiểm tra, KHÔNG áp dụng
helm template ${ECR_REPO} ./gitops/charts/generic-service \
-f ./gitops/apps/${ECR_REPO}/base.yaml \
-f ./gitops/apps/${ECR_REPO}/prod.yaml \
--set image.tag=${IMAGE_TAG} > rendered-prod.yaml
# Kiểm manifest theo policy (resource bắt buộc, không dùng latest, ...)
kubeconform -strict -summary -output json rendered-prod.yaml || true
kyverno apply ./gitops/policies/ --resource rendered-prod.yaml
"""
}
}
post {
always { archiveArtifacts artifacts: 'rendered-prod.yaml', allowEmptyArchive: true }
}
}
// ---------------------------------------------------------------
// Nhánh nào thì bump môi trường nào
stage('Bump dev') {
when { anyOf { branch 'develop'; branch 'main' } }
steps {
container('tools') {
bumpImageTag(
gitopsRepo: GITOPS_REPO,
app: ECR_REPO,
envFile: 'dev.yaml',
tag: IMAGE_TAG,
digest: env.IMAGE_DIGEST
)
}
}
}
stage('Bump staging') {
when { branch 'main' }
steps {
container('tools') {
bumpImageTag(
gitopsRepo: GITOPS_REPO,
app: ECR_REPO,
envFile: 'staging.yaml',
tag: IMAGE_TAG,
digest: env.IMAGE_DIGEST
)
}
}
}
// ---------------------------------------------------------------
// Production: KHÔNG commit trực tiếp. Mở pull request để có review.
stage('PR cho production') {
when {
allOf {
branch 'main'
expression { return params.PROMOTE_TO_PROD == true }
}
}
steps {
container('tools') {
openPromotionPR(
gitopsRepo: GITOPS_REPO,
app: ECR_REPO,
envFile: 'prod.yaml',
tag: IMAGE_TAG,
digest: env.IMAGE_DIGEST,
reviewers: ['platform-team']
)
}
}
}
}
// ---------------------------------------------------------------
post {
success {
script {
notifySlack(
status: 'success',
message: "${ECR_REPO} ${IMAGE_TAG} đã build và đẩy lên ECR"
)
}
}
failure {
script {
notifySlack(
status: 'failure',
message: "${ECR_REPO} build thất bại ở stage ${env.STAGE_NAME}"
)
}
}
cleanup {
// Agent động sẽ bị xoá, nhưng dọn workspace cho chắc nếu dùng agent tĩnh
cleanWs()
}
}
}
parameters {
booleanParam(
name: 'PROMOTE_TO_PROD',
defaultValue: false,
description: 'Mở pull request bump image tag cho production'
)
}
| Quyết định | Lý do |
|---|---|
disableConcurrentBuilds() |
Hai build cùng nhánh chạy song song có thể push tag chồng nhau và tranh chấp khi commit vào repo GitOps. |
| Quét secret là stage đầu tiên | Nhanh và hay fail. Đừng để developer chờ 15 phút mới biết đã commit một API key. |
skipDefaultCheckout(true) |
Để tự kiểm soát việc checkout và lấy được GIT_COMMIT chính xác vào biến. |
| SonarQube và Trivy chạy song song | Hai việc độc lập, chạy song song tiết kiệm được vài phút mỗi build. |
| CRITICAL chặn, HIGH chỉ báo cáo | Chặn vì mọi thứ khiến cả đội học cách bỏ qua cổng chất lượng. Chọn ngưỡng đủ nghiêm để có ý nghĩa mà không gây tê liệt. |
| Ghi lại digest, không chỉ tag | Digest là thứ duy nhất bất biến tuyệt đối. Ghi vào repo GitOps để truy vết chính xác. |
| Stage "Kiểm tra image" | Bắt hai lỗi gây sự cố nhiều nhất: chạy root và ENTRYPOINT shell form (mất
SIGTERM). |
| Production dùng pull request, không commit trực tiếp | Tạo điểm phê duyệt và bản ghi ai duyệt deploy gì. Dev và staging thì tự động cho nhanh. |
helm template + Kyverno trong CI |
Bắt lỗi manifest trước khi ArgoCD áp vào cluster. Rẻ hơn nhiều so với phát hiện lúc sync. |
when theo nhánh: mô hình ở trên là
develop → dev, main → dev + staging, và production cần
PROMOTE_TO_PROD + pull request. Điều chỉnh theo chiến lược nhánh của bạn, nhưng giữ
nguyên tắc: càng gần production thì càng cần sự can thiệp có ý thức của con người.
Khung pipeline giống nhau; chỉ stage build, test và cache là khác. Mục này cho phần khác biệt đó với Java, Python và .NET.
apiVersion: v1
kind: Pod
spec:
serviceAccountName: jenkins-agent
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
nodeSelector:
karpenter.sh/capacity-type: spot
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['sleep']
args: ['infinity']
env:
- name: MAVEN_CONFIG
value: /root/.m2
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '4', memory: 4Gi }
volumeMounts:
- { name: m2, mountPath: /root/.m2 }
- name: python
image: python:3.12
command: ['sleep']
args: ['infinity']
env:
- name: PIP_CACHE_DIR
value: /cache/pip
- name: UV_CACHE_DIR
value: /cache/uv
resources:
requests: { cpu: '1', memory: 1Gi }
limits: { cpu: '2', memory: 2Gi }
volumeMounts:
- { name: pipcache, mountPath: /cache }
- name: dotnet
image: mcr.microsoft.com/dotnet/sdk:8.0
command: ['sleep']
args: ['infinity']
env:
- name: NUGET_PACKAGES
value: /cache/nuget
- name: DOTNET_CLI_TELEMETRY_OPTOUT
value: '1'
- name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE
value: '1'
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '4', memory: 4Gi }
volumeMounts:
- { name: nuget, mountPath: /cache }
- name: kaniko
image: gcr.io/kaniko-project/executor:v1.23.2-debug
command: ['sleep']
args: ['infinity']
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '2', memory: 4Gi }
- name: tools
image: 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/ci-tools:v3
command: ['sleep']
args: ['infinity']
resources:
requests: { cpu: 200m, memory: 512Mi }
limits: { cpu: '1', memory: 1Gi }
volumes:
- name: m2
persistentVolumeClaim: { claimName: jenkins-m2-cache }
- name: pipcache
persistentVolumeClaim: { claimName: jenkins-pip-cache }
- name: nuget
persistentVolumeClaim: { claimName: jenkins-nuget-cache }
ReadWriteMany trên EFS) là cách đơn giản nhất để agent
động vẫn có cache dependency. Đánh đổi: EFS chậm hơn đĩa cục bộ, và nhiều build ghi đồng thời có thể
xung đột. Với Maven, thêm -Dmaven.artifact.threads=1 nếu gặp lỗi cache hỏng. Phương án
khác: dùng repository manager nội bộ (Nexus, Artifactory) làm proxy — nhanh và ổn định hơn nhưng cần
vận hành thêm một hệ thống.
// Maven
stage('Build & Test') {
steps {
container('maven') {
sh '''
set -euo pipefail
mvn -B -ntp clean verify \
-Dmaven.test.failure.ignore=false \
-Djacoco.skip=false
'''
}
}
post {
always {
junit '**/target/surefire-reports/*.xml'
recordCoverage(
tools: [[parser: 'JACOCO', pattern: '**/target/site/jacoco/jacoco.xml']],
qualityGates: [[threshold: 70.0, metric: 'LINE', baseline: 'PROJECT']]
)
}
}
}
// Gradle
stage('Build & Test') {
steps {
container('gradle') {
sh '''
set -euo pipefail
# --no-daemon: daemon vô nghĩa trong container dùng một lần
# --build-cache: dùng cache để tăng tốc
./gradlew --no-daemon --build-cache build jacocoTestReport
'''
}
}
post {
always {
junit '**/build/test-results/test/*.xml'
recordCoverage(tools: [[parser: 'JACOCO', pattern: '**/build/reports/jacoco/test/jacocoTestReport.xml']])
}
}
}
-B (batch mode) — không hỏi tương tác, log gọn hơn.-ntp (no transfer progress) — bỏ hàng nghìn dòng log tải dependency.-Dmaven.test.failure.ignore=false — tường minh rằng test fail thì build fail.--fail-at-end cho multi-module khi muốn thấy hết lỗi thay vì dừng ở module đầu.stage('Build & Test') {
steps {
container('python') {
sh '''
set -euo pipefail
# uv nhanh hơn pip nhiều lần — đáng dùng trong CI
pip install --quiet uv
uv venv /tmp/venv
. /tmp/venv/bin/activate
uv pip install -r requirements.txt -r requirements-dev.txt
# Lint và format: fail nhanh
ruff check . --output-format=junit --output-file=ruff.xml || true
ruff format --check .
# Kiểm kiểu — bắt được nhiều lỗi mà test không bắt
mypy app/ --junit-xml mypy.xml || true
# Test với coverage
pytest \
--junitxml=pytest.xml \
--cov=app \
--cov-report=xml:coverage.xml \
--cov-report=term \
--cov-fail-under=70 \
-q
'''
}
}
post {
always {
junit testResults: 'pytest.xml, ruff.xml, mypy.xml', allowEmptyResults: true
recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'coverage.xml']])
}
}
}
requirements.txt với
flask>=3.0 sẽ cho phiên bản khác nhau giữa hôm nay và tuần sau — nghĩa là image bạn test
không phải image bạn deploy.
# Sinh lockfile ghim chính xác mọi phiên bản, kể cả dependency gián tiếp
uv pip compile requirements.in -o requirements.txt --generate-hashes
# Trong Dockerfile, cài với --require-hashes để chặn thay thế gói
RUN pip install --no-cache-dir --require-hashes -r requirements.txt
Với Poetry thì commit poetry.lock; với PDM thì pdm.lock.
stage('Build & Test') {
steps {
container('dotnet') {
sh '''
set -euo pipefail
# --locked-mode: fail nếu packages.lock.json không khớp .csproj
dotnet restore --locked-mode
dotnet build --no-restore -c Release
dotnet test --no-build -c Release \
--logger "junit;LogFilePath=TestResults/test-results.xml" \
--collect:"XPlat Code Coverage" \
--results-directory TestResults \
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=cobertura
# Publish với ReadyToRun để giảm thời gian khởi động pod
dotnet publish src/MyApp/MyApp.csproj \
-c Release -o ./publish --no-restore \
/p:PublishReadyToRun=true \
/p:UseAppHost=false
# Kiểm lỗ hổng trong package NuGet
dotnet list package --vulnerable --include-transitive 2>&1 | tee vuln.txt
grep -q "has the following vulnerable packages" vuln.txt \
&& { echo "LỖI: có package chứa lỗ hổng"; exit 1; } || true
# Kiểm package đã lỗi thời (chỉ báo cáo)
dotnet list package --outdated || true
'''
}
}
post {
always {
junit testResults: 'TestResults/**/test-results.xml', allowEmptyResults: true
recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'TestResults/**/coverage.cobertura.xml']])
}
}
}
Sinh lockfile cho .NET: dotnet restore --use-lock-file tạo
packages.lock.json — commit file này. Sau đó --locked-mode trong CI đảm bảo
không ai vô tình nâng phiên bản.
| Việc | Java | Python | .NET |
|---|---|---|---|
| Cài dependency | mvn dependency:go-offline |
uv pip install -r | dotnet restore --locked-mode |
| Lockfile | pom.xml ghim versionhoặc dependency-lock |
requirements.txt từuv pip compile --generate-hashes |
packages.lock.json |
| Thư mục cache | ~/.m2/repository |
~/.cache/pip, ~/.cache/uv |
~/.nuget/packages |
| Test | mvn verify | pytest |
dotnet test |
| Báo cáo test | surefire XML (JUnit) | --junitxml |
--logger junit |
| Coverage | JaCoCo XML | Cobertura XML | Cobertura XML |
| Lint | Checkstyle, SpotBugs | ruff, mypy |
Roslyn analyzers, dotnet format |
| Quét lỗ hổng dep | trivy fs,OWASP dependency-check |
trivy fs, pip-audit |
dotnet list package --vulnerable |
| Thời gian build điển hình | 3–8 phút | 1–3 phút | 2–5 phút |
Cổng chất lượng chỉ có giá trị nếu nó chặn thật và chặn đúng. Cổng chặn vì mọi thứ sẽ bị cả đội tìm cách vòng qua; cổng không chặn gì thì chỉ là trang trí.
| Loại | Kiểm gì | Công cụ | Chặn? |
|---|---|---|---|
| Quét secret | Credential bị commit | gitleaks, trufflehog |
CHẶN luôn — secret vào Git là nằm đó mãi |
| Lint / format | Lỗi cú pháp, chuẩn code | ruff, Checkstyle, dotnet format |
Chặn ở main |
| Unit test | Logic nghiệp vụ | JUnit, pytest, xUnit | CHẶN luôn |
| Coverage | Tỉ lệ code được test | JaCoCo, coverage.py | Chặn nếu GIẢM — xem ghi chú bên dưới |
| SAST | Lỗ hổng trong code của bạn | SonarQube, Semgrep | Chặn CRITICAL |
| SCA | Lỗ hổng trong thư viện | trivy fs, Dependabot |
Chặn CRITICAL có bản vá |
| Quét image | Lỗ hổng trong OS của image | trivy image |
Chặn CRITICAL có bản vá |
| Kiểm manifest | Cấu hình Kubernetes sai | kubeconform, Kyverno, helm lint |
CHẶN luôn — rẻ và bắt được lỗi tốn kém |
| Integration test | Tương tác với DB, API thật | Testcontainers | Chặn ở main |
main.sonar.projectKey=order-service
sonar.projectName=Order Service
sonar.sources=src/main
sonar.tests=src/test
sonar.java.binaries=target/classes
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
# Loại khỏi phân tích những thứ không phải code nghiệp vụ
sonar.exclusions=\
**/generated/**,\
**/*Dto.java,\
**/config/**,\
**/migration/**
# Loại khỏi tính coverage những thứ không đáng test
sonar.coverage.exclusions=\
**/config/**,\
**/*Application.java,\
**/dto/**,\
**/entity/**
# Chỉ áp ngưỡng cho CODE MỚI — cho codebase cũ cải thiện dần
sonar.newCode.referenceBranch=main
// Trong Jenkinsfile — chờ kết quả cổng chất lượng
stage('Cổng chất lượng Sonar') {
steps {
timeout(time: 10, unit: 'MINUTES') {
// abortPipeline: true → cổng đỏ thì build FAIL
waitForQualityGate abortPipeline: true
}
}
}
waitForQualityGate cần webhook từ SonarQube về Jenkins. Thiếu webhook thì step này
treo tới hết timeout. Cấu hình trong SonarQube:
Administration → Configuration → Webhooks, URL
https://jenkins.internal.example.com/sonarqube-webhook/ (dấu gạch chéo cuối là bắt buộc).
Testcontainers chạy DB thật trong container cho test. Trong Kubernetes, nó cần một Docker endpoint — cách sạch là dùng DinD sidecar chỉ trong pod agent, không mount socket của node.
- name: dind
image: docker:27-dind
securityContext:
privileged: true # chỉ pod agent, không ảnh hưởng workload khác
env:
- name: DOCKER_TLS_CERTDIR
value: ""
resources:
requests: { cpu: '1', memory: 2Gi }
limits: { cpu: '2', memory: 4Gi }
volumeMounts:
- { name: dind-storage, mountPath: /var/lib/docker }
volumes:
- name: dind-storage
emptyDir: {}
stage('Integration test') {
when { anyOf { branch 'main'; branch 'develop' } }
steps {
container('maven') {
sh '''
set -euo pipefail
export DOCKER_HOST=tcp://localhost:2375
export TESTCONTAINERS_RYUK_DISABLED=true # Ryuk không hoạt động tốt trong K8s
export TESTCONTAINERS_CHECKS_DISABLE=true
# Chờ Docker daemon sẵn sàng
timeout 60 sh -c 'until docker info >/dev/null 2>&1; do sleep 2; done'
mvn -B -ntp verify -Pintegration-test
'''
}
}
post {
always { junit '**/target/failsafe-reports/*.xml' }
}
}
privileged: true, tức pod có quyền gần như
root trên node. Nếu cluster CI dùng chung cho nhiều đội, đây là rủi ro thật. Các phương án thay thế:
stage('Kiểm manifest') {
steps {
container('tools') {
sh '''
set -euo pipefail
# 1. Render chart
helm template order-service ./gitops/charts/generic-service \
-f ./gitops/apps/order-service/base.yaml \
-f ./gitops/apps/order-service/prod.yaml \
--set image.tag=${GIT_SHA} > rendered.yaml
# 2. Kiểm manifest có hợp lệ với schema Kubernetes
kubeconform -strict -summary \
-schema-location default \
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
rendered.yaml
# 3. Kiểm theo policy nội bộ
kyverno apply ./gitops/policies/ --resource rendered.yaml --detailed-results
# 4. Kiểm thói quen tốt
kube-score score rendered.yaml \
--ignore-test pod-networkpolicy \
--output-format ci
'''
}
}
}
gitops/policies/:
requests và limitslatest, image phải từ ECR của bạnrunAsNonRoot: true và drop: ["ALL"]db hay ready — bắt
được lỗi tốn kém nhất trong KubernetesminAvailable < replicastopologySpreadConstraints theo zoneHai bước cuối của CI, và cũng là nơi ranh giới CI/CD được thực thi: Jenkins ghi ý định vào Git, không ghi vào cluster.
Agent Jenkins lấy quyền ECR qua IRSA. Không có credential nào nằm trong Jenkins.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EcrAuth",
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
},
{
"Sid": "EcrPushPull",
"Effect": "Allow",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage",
"ecr:DescribeImages",
"ecr:ListImages"
],
"Resource": [
"arn:aws:ecr:ap-southeast-1:123456789012:repository/order-service",
"arn:aws:ecr:ap-southeast-1:123456789012:repository/order-service-cache",
"arn:aws:ecr:ap-southeast-1:123456789012:repository/payment-service",
"arn:aws:ecr:ap-southeast-1:123456789012:repository/payment-service-cache"
]
}
]
}
Resource theo đúng repo, đừng dùng *. Nếu agent CI bị chiếm
quyền, kẻ tấn công chỉ push được vào những repo đã liệt kê, không đẩy được ảnh độc vào mọi service.
Chỉ ecr:GetAuthorizationToken buộc phải là * vì nó không gắn với resource.
// Kaniko tự đọc credential từ IRSA qua web identity token.
// Không cần tạo docker config, không cần secret.
container('kaniko') {
sh """
/kaniko/executor \
--context "\$(pwd)" \
--dockerfile Dockerfile \
--destination "${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}" \
--cache=true \
--cache-repo "${ECR_REGISTRY}/${ECR_REPO}-cache" \
--cache-ttl=168h \
--snapshot-mode=redo
"""
}
// Nếu dùng BuildKit daemon dùng chung thì đăng nhập trước
container('tools') {
sh """
aws ecr get-login-password --region ${AWS_REGION} \
| buildctl --addr tcp://buildkitd.jenkins-agents.svc:1234 \
... // hoặc dùng docker buildx với driver remote
"""
}
container('tools') {
sh """
set -euo pipefail
aws ecr get-login-password --region ${AWS_REGION} \
| crane auth login --username AWS --password-stdin ${ECR_REGISTRY}
SRC="${ECR_REGISTRY}/${ECR_REPO}:${IMAGE_TAG}"
# crane tag chỉ thêm tag vào CÙNG digest, không tải và đẩy lại ảnh
crane tag "\$SRC" "${env.GIT_BRANCH_NAME.replaceAll('/','-')}"
crane tag "\$SRC" "build-${BUILD_NUMBER}"
# Chỉ gắn semver khi là tag Git
if [ -n "\${TAG_NAME:-}" ]; then
crane tag "\$SRC" "\${TAG_NAME}"
fi
# Ghi lại digest để dùng ở bước bump
crane digest "\$SRC" | tee image-digest.txt
"""
}
def call(Map cfg) {
// cfg: gitopsRepo, app, envFile, tag, digest
withCredentials([sshUserPrivateKey(
credentialsId: 'gitops-deploy-key',
keyFileVariable: 'SSH_KEY')]) {
sh """
set -euo pipefail
export GIT_SSH_COMMAND="ssh -i \$SSH_KEY -o StrictHostKeyChecking=accept-new"
rm -rf gitops-bump
git clone --depth 1 ${cfg.gitopsRepo} gitops-bump
cd gitops-bump
git config user.email "jenkins@example.com"
git config user.name "Jenkins CI"
FILE="apps/${cfg.app}/${cfg.envFile}"
# yq sửa YAML đúng cách — KHÔNG dùng sed cho YAML
yq -i '.image.tag = "${cfg.tag}"' "\$FILE"
yq -i '.image.digest = "${cfg.digest}"' "\$FILE"
# Không có gì đổi thì thoát sạch, tránh commit rỗng
if git diff --quiet; then
echo "Tag đã là ${cfg.tag}, không có gì để commit."
exit 0
fi
git add "\$FILE"
git commit -m "chore(${cfg.app}): bump ${cfg.envFile} to ${cfg.tag}
Image: ${cfg.app}:${cfg.tag}
Digest: ${cfg.digest}
Source: ${env.GIT_URL}@${env.GIT_SHA_FULL}
Build: ${env.BUILD_URL}"
# Retry khi có build khác vừa push — tránh fail vì race condition
for i in 1 2 3 4 5; do
if git push origin HEAD:main; then
echo "Đã push thành công."
exit 0
fi
echo "Push bị từ chối, rebase rồi thử lại (lần \$i)..."
git pull --rebase origin main
sleep \$((i * 3))
done
echo "LỖI: không push được sau 5 lần thử."
exit 1
"""
}
}
sed để sửa YAML. Nó không hiểu cấu trúc nên dễ sửa sai chỗ:
# values.yaml có hai chỗ chứa chữ "tag"
image:
tag: "abc1234"
sidecar:
image:
tag: "v2.1.0" ← sed sẽ sửa cả dòng này
# sed -i 's/tag: .*/tag: "new"/' values.yaml → phá cả hai
# yq hiểu đường dẫn, chỉ sửa đúng chỗ
yq -i '.image.tag = "new"' values.yaml
Và yq giữ nguyên định dạng, chú thích, thứ tự key — điều quan trọng khi file đó được con
người đọc và review.
non-fast-forward — và pipeline đỏ vì một lý do hoàn toàn không liên quan tới code.
def call(Map cfg) {
withCredentials([
sshUserPrivateKey(credentialsId: 'gitops-deploy-key', keyFileVariable: 'SSH_KEY'),
string(credentialsId: 'github-token', variable: 'GH_TOKEN')
]) {
sh """
set -euo pipefail
export GIT_SSH_COMMAND="ssh -i \$SSH_KEY -o StrictHostKeyChecking=accept-new"
rm -rf gitops-pr
git clone --depth 1 ${cfg.gitopsRepo} gitops-pr
cd gitops-pr
git config user.email "jenkins@example.com"
git config user.name "Jenkins CI"
BRANCH="promote/${cfg.app}-${cfg.tag}"
git checkout -b "\$BRANCH"
FILE="apps/${cfg.app}/${cfg.envFile}"
OLD_TAG=\$(yq '.image.tag' "\$FILE")
yq -i '.image.tag = "${cfg.tag}"' "\$FILE"
yq -i '.image.digest = "${cfg.digest}"' "\$FILE"
if git diff --quiet; then
echo "Production đã ở tag ${cfg.tag}."
exit 0
fi
git add "\$FILE"
git commit -m "promote(${cfg.app}): \$OLD_TAG → ${cfg.tag}"
git push origin "\$BRANCH"
# Mở PR với đủ thông tin để người review quyết định được
gh pr create \
--title "promote(${cfg.app}): \$OLD_TAG → ${cfg.tag}" \
--body "## Thay đổi
- Service: \`${cfg.app}\`
- Môi trường: \`${cfg.envFile}\`
- Tag: \`\$OLD_TAG\` → \`${cfg.tag}\`
- Digest: \`${cfg.digest}\`
## Nguồn
- Commit: ${env.GIT_URL}/commit/${env.GIT_SHA_FULL}
- Build: ${env.BUILD_URL}
- So sánh: ${env.GIT_URL}/compare/\$OLD_TAG...${cfg.tag}
## Đã kiểm
- [x] Unit test và coverage
- [x] Cổng chất lượng SonarQube
- [x] Quét lỗ hổng (CRITICAL = 0)
- [x] Kiểm manifest (kubeconform + Kyverno)
- [x] Đã chạy ở staging
## Người duyệt cần xác nhận
- [ ] Đã kiểm metric của staging sau khi deploy
- [ ] Migration DB (nếu có) tương thích ngược
- [ ] Không trùng khung giờ freeze deploy" \
--reviewer ${cfg.reviewers.join(',')} \
--label "promotion,${cfg.app}"
"""
}
}
# Thiết lập trên GitHub cho nhánh main của gitops-config
gh api -X PUT repos/myorg/gitops-config/branches/main/protection \
--input - <<'JSON'
{
"required_status_checks": {
"strict": true,
"contexts": ["manifest-validation", "policy-check"]
},
"enforce_admins": true,
"required_pull_request_reviews": {
"required_approving_review_count": 1,
"dismiss_stale_reviews": true,
"require_code_owner_reviews": true
},
"restrictions": null,
"allow_force_pushes": false,
"allow_deletions": false
}
JSON
# Dev và staging: đội service tự quản
/apps/*/dev.yaml @myorg/developers
/apps/*/staging.yaml @myorg/developers
# Production: cần đội platform duyệt
/apps/*/prod.yaml @myorg/platform-team
# Chart và policy: chỉ platform
/charts/ @myorg/platform-team
/policies/ @myorg/platform-team
/argocd/ @myorg/platform-team
git revert trên cùng repo đó.
sed để bump image.tag trong values.yaml?Với 20 service, bạn không muốn 20 bản Jenkinsfile dài 300 dòng gần giống
nhau. Shared library cho bạn một pipeline chuẩn, và mỗi service chỉ cần vài dòng.
platform-pipeline-lib/
├── vars/ # hàm global, gọi trực tiếp trong Jenkinsfile
│ ├── standardJavaPipeline.groovy
│ ├── standardPythonPipeline.groovy
│ ├── standardDotnetPipeline.groovy
│ ├── bumpImageTag.groovy
│ ├── openPromotionPR.groovy
│ ├── buildAndPushImage.groovy
│ ├── scanImage.groovy
│ ├── validateManifests.groovy
│ └── notifySlack.groovy
├── src/com/example/ci/ # class Groovy cho logic phức tạp
│ ├── EcrClient.groovy
│ └── VersionUtils.groovy
├── resources/ # file tĩnh, đọc bằng libraryResource
│ ├── agent-pod-java.yaml
│ ├── agent-pod-python.yaml
│ └── agent-pod-dotnet.yaml
└── README.md
@Library('platform-pipeline-lib@v2') _
standardJavaPipeline(
serviceName: 'order-service',
ecrRepo: 'order-service',
javaVersion: '21',
sonarKey: 'order-service',
coverageMin: 70,
// Môi trường nào tự động, môi trường nào cần PR
autoBumpEnvs: ['dev', 'staging'],
prEnvs: ['prod'],
reviewers: ['platform-team'],
// Bật integration test cần DinD
integrationTest: true,
slackChannel: '#team-orders'
)
@Library('platform-pipeline-lib@v2') _
standardPythonPipeline(
serviceName: 'report-worker',
ecrRepo: 'report-worker',
pythonVersion: '3.12',
coverageMin: 65,
autoBumpEnvs: ['dev'],
prEnvs: ['staging', 'prod'],
reviewers: ['data-team'],
slackChannel: '#team-data'
)
def call(Map cfg) {
// Giá trị mặc định — service chỉ khai cái khác biệt
cfg.javaVersion = cfg.javaVersion ?: '21'
cfg.coverageMin = cfg.coverageMin ?: 70
cfg.autoBumpEnvs = cfg.autoBumpEnvs ?: ['dev']
cfg.prEnvs = cfg.prEnvs ?: ['prod']
cfg.integrationTest = cfg.integrationTest ?: false
cfg.region = cfg.region ?: 'ap-southeast-1'
cfg.ecrRegistry = cfg.ecrRegistry ?: '123456789012.dkr.ecr.ap-southeast-1.amazonaws.com'
cfg.gitopsRepo = cfg.gitopsRepo ?: 'git@github.com:myorg/gitops-config.git'
// Kiểm tham số bắt buộc — fail sớm với thông báo rõ
['serviceName', 'ecrRepo'].each { k ->
if (!cfg[k]) {
error "standardJavaPipeline: thiếu tham số bắt buộc '${k}'"
}
}
def podYaml = libraryResource('agent-pod-java.yaml')
.replace('{{JAVA_VERSION}}', cfg.javaVersion)
.replace('{{DIND}}', cfg.integrationTest ? 'true' : 'false')
pipeline {
agent {
kubernetes {
defaultContainer 'maven'
yaml podYaml
}
}
options {
buildDiscarder(logRotator(numToKeepStr: '30'))
disableConcurrentBuilds()
timeout(time: 45, unit: 'MINUTES')
timestamps()
skipDefaultCheckout(true)
}
parameters {
booleanParam(name: 'PROMOTE_TO_PROD', defaultValue: false,
description: 'Mở pull request bump tag cho production')
booleanParam(name: 'SKIP_TESTS', defaultValue: false,
description: 'CHỈ dùng khi khẩn cấp. Bỏ qua test.')
}
stages {
stage('Checkout') {
steps {
script {
def v = checkout scm
env.GIT_SHA = v.GIT_COMMIT.take(7)
env.GIT_SHA_FULL = v.GIT_COMMIT
currentBuild.displayName = "#${BUILD_NUMBER} ${env.BRANCH_NAME}@${env.GIT_SHA}"
}
}
}
stage('Quét secret') {
steps { container('tools') { scanSecrets() } }
}
stage('Build & Test') {
when { expression { !params.SKIP_TESTS } }
steps {
container('maven') {
sh "mvn -B -ntp clean verify -Djacoco.skip=false"
}
}
post {
always {
junit testResults: '**/target/surefire-reports/*.xml', allowEmptyResults: true
recordCoverage(
tools: [[parser: 'JACOCO', pattern: '**/target/site/jacoco/jacoco.xml']],
qualityGates: [[threshold: cfg.coverageMin, metric: 'LINE', baseline: 'PROJECT']]
)
}
}
}
stage('Phân tích') {
when { expression { !params.SKIP_TESTS } }
parallel {
stage('Sonar') {
steps {
container('maven') {
withSonarQubeEnv('sonar-internal') {
sh "mvn -B -ntp sonar:sonar -Dsonar.projectKey=${cfg.sonarKey ?: cfg.serviceName}"
}
}
}
}
stage('SCA') {
steps { container('tools') { scanDependencies() } }
}
}
}
stage('Cổng Sonar') {
when { expression { !params.SKIP_TESTS } }
steps {
timeout(time: 10, unit: 'MINUTES') { waitForQualityGate abortPipeline: true }
}
}
stage('Build & Push image') {
steps {
script {
env.IMAGE_DIGEST = buildAndPushImage(
registry: cfg.ecrRegistry,
repo: cfg.ecrRepo,
tag: env.GIT_SHA
)
}
}
}
stage('Quét image') {
steps {
container('tools') {
scanImage(image: "${cfg.ecrRegistry}/${cfg.ecrRepo}:${env.GIT_SHA}")
}
}
}
stage('Kiểm manifest') {
steps {
container('tools') {
validateManifests(
gitopsRepo: cfg.gitopsRepo,
app: cfg.ecrRepo,
tag: env.GIT_SHA,
envs: cfg.autoBumpEnvs + cfg.prEnvs
)
}
}
}
stage('Bump tự động') {
when { anyOf { branch 'main'; branch 'develop' } }
steps {
container('tools') {
script {
cfg.autoBumpEnvs.each { e ->
bumpImageTag(
gitopsRepo: cfg.gitopsRepo,
app: cfg.ecrRepo,
envFile: "${e}.yaml",
tag: env.GIT_SHA,
digest: env.IMAGE_DIGEST
)
}
}
}
}
}
stage('PR production') {
when {
allOf { branch 'main'; expression { params.PROMOTE_TO_PROD } }
}
steps {
container('tools') {
script {
cfg.prEnvs.each { e ->
openPromotionPR(
gitopsRepo: cfg.gitopsRepo,
app: cfg.ecrRepo,
envFile: "${e}.yaml",
tag: env.GIT_SHA,
digest: env.IMAGE_DIGEST,
reviewers: cfg.reviewers ?: ['platform-team']
)
}
}
}
}
}
}
post {
always {
script {
notifySlack(
channel: cfg.slackChannel,
status: currentBuild.currentResult,
service: cfg.serviceName,
tag: env.GIT_SHA
)
}
}
}
}
}
// Ghim tag — dùng cho production. Thay đổi library không ảnh hưởng tới service
// cho tới khi service chủ động nâng.
@Library('platform-pipeline-lib@v2.3.0') _
// Ghim nhánh ổn định — nhận bản vá nhưng không nhận breaking change
@Library('platform-pipeline-lib@v2') _
// Nhánh chính — chỉ dùng khi đang phát triển chính library
@Library('platform-pipeline-lib@main') _
// Nhiều library cùng lúc
@Library(['platform-pipeline-lib@v2', 'security-lib@v1']) _
@main cho mọi service là rủi ro thật. Một lỗi trong library làm toàn bộ
pipeline của mọi service đỏ cùng lúc — kể cả những service không ai đang chạm vào. Ghim theo tag
(@v2.3.0) hoặc nhánh major (@v2), và nâng có chủ đích.
# Dùng JenkinsPipelineUnit để test logic Groovy mà không cần Jenkins thật
# build.gradle của library
dependencies {
testImplementation 'com.lesfurets:jenkins-pipeline-unit:1.21'
testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0'
}
# Trong CI của library:
# 1. ./gradlew test — test unit cho các hàm
# 2. Replay trên một service thử — chạy thật với nhánh library mới
# 3. Gắn tag và thông báo cho các đội
Jenkins có tính năng Replay cho phép sửa script của một build cũ rồi chạy lại — cách nhanh nhất để thử một thay đổi nhỏ trong pipeline mà không phải commit.
@Library('lib@main')?Jenkins chạy code tuỳ ý — đó là công việc của nó. Nên mọi credential Jenkins giữ đều phải
coi như có thể bị đọc bởi bất kỳ ai viết được Jenkinsfile. Nguyên tắc: giữ càng ít
credential càng tốt, và dùng IRSA thay vì access key.
| Bậc | Cách làm | Vấn đề |
|---|---|---|
| 0 | Secret viết thẳng trong Jenkinsfile |
Nằm trong Git history vĩnh viễn, hiện trong log build, ai đọc repo là có. |
| 1 | Biến môi trường trên node Jenkins | Mọi job dùng chung, không phân quyền được, hiện trong printenv. |
| 2 | Jenkins Credentials với access key AWS | Có phân quyền, nhưng key tồn tại lâu dài và phải luân chuyển tay. Rò rỉ là dùng được ngay. |
| 3 | IRSA cho agent pod | Khuyến nghị. Không có key nào tồn tại. Credential tạm thời, tự hết hạn, phân quyền theo ServiceAccount. |
| 4 | IRSA + Secrets Manager + phê duyệt cho prod | Agent chỉ đọc được secret của đúng môi trường nó phục vụ. |
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EcrAuth",
"Effect": "Allow",
"Action": ["ecr:GetAuthorizationToken"],
"Resource": "*"
},
{
"Sid": "EcrPushPullOnlyOurRepos",
"Effect": "Allow",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage",
"ecr:DescribeImages"
],
"Resource": [
"arn:aws:ecr:ap-southeast-1:123456789012:repository/order-service",
"arn:aws:ecr:ap-southeast-1:123456789012:repository/order-service-cache",
"arn:aws:ecr:ap-southeast-1:123456789012:repository/charts/*"
]
},
{
"Sid": "ReadCiSecretsOnly",
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": "arn:aws:secretsmanager:ap-southeast-1:123456789012:secret:ci/*"
}
]
}
kubectl apply được, không helm upgrade được. Nếu agent bị chiếm quyền, kẻ
tấn công đẩy được ảnh xấu lên ECR nhưng không chạm được vào cluster — vì việc deploy do ArgoCD
làm, dựa trên Git. Đây là lợi ích bảo mật cụ thể của việc tách CI và CD.
# Tạo IAM role liên kết với ServiceAccount qua OIDC của cluster
eksctl create iamserviceaccount \
--cluster prod-eks \
--namespace jenkins-agents \
--name jenkins-agent \
--attach-policy-arn arn:aws:iam::123456789012:policy/JenkinsAgentPolicy \
--approve \
--region ap-southeast-1
# Xác minh ServiceAccount đã có annotation
kubectl get sa jenkins-agent -n jenkins-agents -o yaml | grep role-arn
# Trong agent pod, xác nhận danh tính thật
kubectl run -it --rm test --image=amazon/aws-cli \
--overrides='{"spec":{"serviceAccountName":"jenkins-agent"}}' \
-n jenkins-agents -- sts get-caller-identity
// Cách 1: withCredentials — PHẠM VI HẸP, chỉ tồn tại trong block. Ưu tiên cách này.
withCredentials([
usernamePassword(credentialsId: 'github-app',
usernameVariable: 'GIT_USER',
passwordVariable: 'GIT_TOKEN'),
string(credentialsId: 'sonar-token', variable: 'SONAR_TOKEN'),
file(credentialsId: 'gpg-signing-key', variable: 'GPG_KEY_FILE')
]) {
sh '''
set +x # TẮT echo lệnh trước khi dùng secret
git -c credential.helper='!f(){ echo "username=$GIT_USER"; echo "password=$GIT_TOKEN"; };f' \\
push origin HEAD:main
set -x
'''
}
// Cách 2: environment ở cấp pipeline — tiện nhưng phạm vi RỘNG, mọi stage thấy được
environment {
SONAR_TOKEN = credentials('sonar-token')
}
// Cách 3: đọc trực tiếp từ Secrets Manager bằng IRSA — KHÔNG lưu gì trong Jenkins
container('tools') {
sh '''
export SONAR_TOKEN=$(aws secretsmanager get-secret-value \\
--secret-id ci/sonar-token --query SecretString --output text)
sonar-scanner -Dsonar.token="$SONAR_TOKEN"
'''
}
# 1. set -x in mọi lệnh kèm giá trị biến đã thay thế
sh 'set -x; curl -H "Authorization: Bearer $TOKEN" ...' # TOKEN hiện trong log
# 2. echo để debug
sh 'echo "token=$TOKEN"' # hiển nhiên
# 3. Lệnh tự in cấu hình
sh 'mvn -X deploy' # -X in cả settings.xml
# 4. Thông báo lỗi của công cụ
sh 'curl -v https://$USER:$PASS@registry/...' # -v in cả URL
# CÁCH CHẶN:
# - Dùng withCredentials: Jenkins tự che giá trị bằng **** trong log
# - set +x trước đoạn dùng secret
# - Truyền secret qua stdin hoặc file, KHÔNG qua tham số dòng lệnh
# (tham số dòng lệnh hiện trong `ps aux` của mọi process trên node)
# - Cài plugin Mask Passwords
Lưu ý: Jenkins chỉ che được credential nó biết. Secret đọc từ Secrets Manager bằng
aws CLI thì Jenkins không biết nên không che — phải tự cẩn thận với
set +x.
# SAI — secret hiện trong `ps aux` của mọi process trên node
sh 'docker login -u AWS -p $ECR_PASSWORD registry.example.com'
# ĐÚNG — qua stdin, không bao giờ xuất hiện trong danh sách process
sh 'echo "$ECR_PASSWORD" | docker login -u AWS --password-stdin registry.example.com'
# ĐÚNG — qua file tạm với quyền hẹp, xoá ngay sau khi dùng
sh '''
umask 077
printf '%s' "$SONAR_TOKEN" > .sonar-token
trap 'rm -f .sonar-token' EXIT
sonar-scanner -Dsonar.token="$(cat .sonar-token)"
'''
| Rủi ro | Biện pháp |
|---|---|
Ai cũng sửa được Jenkinsfile và lấy được mọi credential |
Branch protection trên main, bắt buộc review. Và dùng
CODEOWNERS cho Jenkinsfile để đội platform phải phê duyệt. |
| Pull request từ fork chạy được pipeline với credential production | Không chạy pipeline có credential cho PR từ nguồn ngoài. Dùng pipeline riêng, hạn chế quyền, cho PR. |
| Script Groovy tuỳ ý truy cập nội bộ Jenkins | Bật Script Security và sandbox. Chỉ cho phép phương thức đã phê duyệt. |
| Credential production dùng được từ nhánh feature | Phân quyền credential theo folder: credential của prod chỉ nằm trong folder prod, và chỉ pipeline trong folder đó dùng được. |
| Agent của đội A đọc được secret của đội B | Mỗi đội một namespace agent riêng, một ServiceAccount riêng, một IAM role riêng với policy giới hạn theo tiền tố secret. |
prod/ trong Jenkins, đặt credential production ở cấp folder đó thay vì cấp global.
Pipeline nằm ngoài folder sẽ không thấy credential đó — kể cả khi biết chính xác
credentialsId.
// Ghi lại thông tin người kích hoạt vào commit của repo GitOps
script {
def cause = currentBuild.getBuildCauses()
def trigger = cause[0]?.shortDescription ?: 'unknown'
env.TRIGGERED_BY = trigger
}
sh """
git commit -m 'chore(order-service): bump prod image to ${GIT_SHA}
Service: order-service
Image: ${ECR_REPO}:${GIT_SHA}
Commit: ${GIT_COMMIT_FULL}
Build: ${BUILD_URL}
Triggered: ${TRIGGERED_BY}
'
"""
Commit message là bản ghi audit bền nhất: nó không bị xoá theo retention của Jenkins, và nối được từ trạng thái cluster về đúng build và đúng người.
docker login -p $PASSWORD không an toàn ngay cả khi Jenkins che log?Bạn đang dùng Jenkins, nhưng biết bản tương đương hữu ích khi làm việc với repo khác, khi đánh giá chuyển đổi, hoặc khi đọc tài liệu của công cụ bên thứ ba. Logic pipeline giống nhau; chỉ cú pháp và cách cấp quyền AWS khác.
| Jenkins | GitHub Actions | GitLab CI |
|---|---|---|
Jenkinsfile | .github/workflows/*.yml | .gitlab-ci.yml |
pipeline | workflow | toàn bộ file |
stage | job | job với stage |
steps | steps | script |
agent / pod template | runs-on / container | image / tags |
| Shared library | Composite action / reusable workflow | include + extends |
| Credentials plugin | Secrets + OIDC | CI/CD variables + OIDC |
when { branch }} | if: | rules: |
input (phê duyệt) | environment với reviewer | when: manual + protected環境 |
| IRSA cho agent pod | OIDC → AssumeRoleWithWebIdentity | OIDC → AssumeRoleWithWebIdentity |
name: CI
on:
push:
branches: [main, 'release/**']
pull_request:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
AWS_REGION: ap-southeast-1
ECR_REGISTRY: 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com
SERVICE: order-service
permissions:
contents: read
id-token: write # BẮT BUỘC cho OIDC — thiếu là không lấy được credential AWS
jobs:
build:
runs-on: ubuntu-latest
outputs:
image-tag: ${{ steps.meta.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: meta
run: echo "tag=$(git rev-parse --short=7 HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven # thay cho PVC cache .m2 của Jenkins
- name: Build and test
run: mvn -B clean verify
- uses: actions/upload-artifact@v4
if: always()
with:
name: test-reports
path: target/surefire-reports/
# --- Quét secret và dependency ---
- name: Secret scan
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Dependency scan
run: |
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \
| sh -s -- -b /usr/local/bin
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL \
--ignore-unfixed --exit-code 1 .
# --- OIDC: lấy credential AWS tạm thời, KHÔNG dùng access key ---
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-ci
aws-region: ${{ env.AWS_REGION }}
- uses: aws-actions/amazon-ecr-login@v2
id: ecr
- uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.ECR_REGISTRY }}/${{ env.SERVICE }}:${{ steps.meta.outputs.tag }}
${{ env.ECR_REGISTRY }}/${{ env.SERVICE }}:main-${{ steps.meta.outputs.tag }}
cache-from: type=registry,ref=${{ env.ECR_REGISTRY }}/${{ env.SERVICE }}-cache:buildcache
cache-to: type=registry,ref=${{ env.ECR_REGISTRY }}/${{ env.SERVICE }}-cache:buildcache,mode=max
provenance: false
- name: Scan image
run: |
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 \
${{ env.ECR_REGISTRY }}/${{ env.SERVICE }}:${{ steps.meta.outputs.tag }}
# --- Bump repo GitOps cho dev: tự động ---
deploy-dev:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
repository: myorg/gitops-config
token: ${{ secrets.GITOPS_PAT }}
ref: main
- name: Bump image tag
run: |
yq -i '.image.tag = "${{ needs.build.outputs.image-tag }}"' \
apps/${{ env.SERVICE }}/dev.yaml
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git commit -am "chore(${{ env.SERVICE }}): bump dev to ${{ needs.build.outputs.image-tag }}"
git push
# --- Bump cho prod: cần PHÊ DUYỆT qua GitHub Environment ---
deploy-prod:
needs: [build, deploy-dev]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment:
name: production # cấu hình required reviewers ở đây
steps:
- uses: actions/checkout@v4
with:
repository: myorg/gitops-config
token: ${{ secrets.GITOPS_PAT }}
- name: Open PR to bump prod
run: |
BR="bump/${{ env.SERVICE }}-${{ needs.build.outputs.image-tag }}"
git checkout -b "$BR"
yq -i '.image.tag = "${{ needs.build.outputs.image-tag }}"' \
apps/${{ env.SERVICE }}/prod.yaml
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git commit -am "chore(${{ env.SERVICE }}): bump prod to ${{ needs.build.outputs.image-tag }}"
git push origin "$BR"
gh pr create --fill --base main --head "$BR"
env:
GH_TOKEN: ${{ secrets.GITOPS_PAT }}
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:myorg/order-service:ref:refs/heads/main"
}
}
}]
}
sub là thứ quyết định an toàn. Nếu bạn đặt
"repo:myorg/*:*" thì bất kỳ workflow nào ở bất kỳ repo nào của tổ chức — kể cả
nhánh do người ngoài tạo qua pull request — đều assume được role này. Luôn giới hạn tới đúng repo và
đúng ref. Dùng repo:myorg/order-service:environment:production nếu muốn chỉ job có
environment production mới dùng được.
stages: [build, scan, image, deploy]
variables:
AWS_REGION: ap-southeast-1
ECR_REGISTRY: 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com
SERVICE: order-service
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn"
default:
cache:
key:
files: [pom.xml]
paths: [.m2/repository]
# --- Khối dùng lại, tương đương hàm trong shared library ---
.aws_oidc: &aws_oidc
id_tokens:
AWS_ID_TOKEN:
aud: sts.amazonaws.com
before_script:
- |
export $(printf 'AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s' \
$(aws sts assume-role-with-web-identity \
--role-arn "$AWS_ROLE_ARN" \
--role-session-name "gitlab-${CI_PIPELINE_ID}" \
--web-identity-token "$AWS_ID_TOKEN" \
--duration-seconds 3600 \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
--output text))
build:
stage: build
image: maven:3.9-eclipse-temurin-21
script:
- mvn -B clean verify
artifacts:
when: always
paths: [target/*.jar]
reports:
junit: target/surefire-reports/TEST-*.xml
secret-scan:
stage: scan
image: zricethezav/gitleaks:latest
script: [gitleaks detect --source . --redact --exit-code 1]
dependency-scan:
stage: scan
image: aquasec/trivy:latest
script:
- trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 .
image:
stage: image
<<: *aws_oidc
image:
name: gcr.io/kaniko-project/executor:v1.23.2-debug
entrypoint: [""]
variables:
AWS_ROLE_ARN: arn:aws:iam::123456789012:role/gitlab-ci
script:
- export TAG="${CI_COMMIT_SHORT_SHA}"
- /kaniko/executor
--context "$CI_PROJECT_DIR"
--dockerfile "$CI_PROJECT_DIR/Dockerfile"
--destination "${ECR_REGISTRY}/${SERVICE}:${TAG}"
--cache=true
--cache-repo "${ECR_REGISTRY}/${SERVICE}-cache"
rules:
- if: $CI_COMMIT_BRANCH == "main"
deploy-dev:
stage: deploy
image: alpine/git:latest
script:
- apk add --no-cache yq
- git clone https://oauth2:${GITOPS_TOKEN}@gitlab.com/myorg/gitops-config.git cfg
- cd cfg
- yq -i ".image.tag = \"${CI_COMMIT_SHORT_SHA}\"" apps/${SERVICE}/dev.yaml
- git config user.email "ci@example.com" && git config user.name "GitLab CI"
- git commit -am "chore(${SERVICE}): bump dev to ${CI_COMMIT_SHORT_SHA}"
- git push
rules:
- if: $CI_COMMIT_BRANCH == "main"
deploy-prod:
extends: deploy-dev
environment:
name: production # bật protected environment để yêu cầu phê duyệt
script:
- apk add --no-cache yq
- git clone https://oauth2:${GITOPS_TOKEN}@gitlab.com/myorg/gitops-config.git cfg
- cd cfg
- yq -i ".image.tag = \"${CI_COMMIT_SHORT_SHA}\"" apps/${SERVICE}/prod.yaml
- git config user.email "ci@example.com" && git config user.name "GitLab CI"
- git commit -am "chore(${SERVICE}): bump prod to ${CI_COMMIT_SHORT_SHA}"
- git push
when: manual # cần bấm tay
rules:
- if: $CI_COMMIT_BRANCH == "main"
| Công cụ | Mạnh ở | Yếu ở |
|---|---|---|
| Jenkins | Logic phức tạp (Groovy đầy đủ), shared library mạnh, tự chủ hoàn toàn, plugin cho mọi thứ, chạy được trong VPC kín. | Phải tự vận hành và vá. Plugin là nguồn lỗi và nợ kỹ thuật. Cấu hình dễ trôi khỏi Git nếu không kỷ luật dùng JCasC. |
| GitHub Actions | Không phải vận hành gì. Marketplace lớn. OIDC gọn. Tích hợp chặt với pull request. | Tốn tiền theo phút khi dùng nhiều. Logic phức tạp phải viết bằng script. Self-hosted runner lại quay về việc phải vận hành. |
| GitLab CI | Cú pháp gọn và dễ đọc nhất. include/extends đủ mạnh cho phần lớn nhu
cầu. Tích hợp registry và security scanning sẵn. |
Gắn với GitLab. Logic rất phức tạp thì YAML trở nên khó quản. |
"sub": "repo:myorg/*:*". Rủi ro?| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | CI không deploy trực tiếp vào cluster | Jenkins commit vào repo GitOps, ArgoCD sync. Agent không cần credential cluster nào. |
| ☐ | Tách repo code và repo cấu hình | Phân quyền khác nhau, và tránh vòng lặp CI khi bump tag. |
| ☐ | Jenkinsfile nằm trong repo, review qua pull request |
Cấu hình job bằng giao diện web thì không ai biết ai đổi gì lúc nào. |
| ☐ | Jenkins dùng JCasC, plugin khai báo trong Git | Dựng lại được Jenkins từ đầu. Không có cấu hình chỉ tồn tại trong ổ đĩa controller. |
| ☐ | Agent động trên Kubernetes, podRetention: never |
Build không bị ảnh hưởng bởi thứ còn lại từ build trước. |
| ☐ | Jenkins không phơi ra internet | scheme: internal, truy cập qua VPN/SSO. Jenkins chạy code tuỳ ý. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Build một lần, một artifact đi qua mọi môi trường | Build riêng cho từng môi trường làm việc test mất phần lớn giá trị. |
| ☐ | Tag ảnh theo git SHA, không bao giờ deploy latest |
Không có tag bất biến thì không truy vết và không rollback được. |
| ☐ | Dùng Kaniko hoặc BuildKit rootless, không dùng DinD hay mount docker.sock | privileged cho pod quyền gần như root trên node. |
| ☐ | Có registry cache với mode=max |
Agent sạch mỗi lần nên không có cache cục bộ; mode=min không cache stage build. |
| ☐ | Chỉ định --platform tường minh |
Tránh exec format error khi kiến trúc agent khác node. |
| ☐ | Lockfile được commit (Chart.lock, package-lock.json…) |
Để build tái lập được. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Bước nhanh và hay fail xếp lên trước | Lint và quét secret trước, integration test sau. Đừng để developer chờ 15 phút mới biết sai dấu phẩy. |
| ☐ | Quét secret trong source (gitleaks) |
Secret vào Git là nằm đó mãi, kể cả khi xoá ở commit sau. |
| ☐ | Quét image với --ignore-unfixed |
Chặn vì CVE không có bản vá chỉ khiến cả đội học cách bỏ qua cổng chất lượng. |
| ☐ | Ngoại lệ CVE có lý do và ngày hết hạn | Để ngoại lệ không tồn tại vĩnh viễn trong .trivyignore. |
| ☐ | Test report được publish (JUnit), không chỉ nằm trong log | Để thấy test nào fail mà không phải đọc hàng nghìn dòng log. |
| ☐ | helm lint --strict và helm template trong CI |
Bắt lỗi chart trước khi chạm cluster. |
| ☐ | Pull request hiển thị helm diff upgrade |
Người review thấy hệ quả thật của thay đổi values. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Dùng IRSA cho agent, không dùng AWS access key | Không có key tồn tại lâu dài để rò rỉ. Credential tạm thời, tự hết hạn. |
| ☐ | IAM policy của agent giới hạn tới đúng repo ECR và tiền tố secret | Và không có quyền nào với EKS — agent bị chiếm quyền vẫn không chạm được cluster. |
| ☐ | Secret truyền qua stdin hoặc file, không qua tham số dòng lệnh | Tham số dòng lệnh hiện trong ps aux của mọi process trên node. |
| ☐ | set +x quanh đoạn dùng secret |
Jenkins chỉ che được credential nó biết; secret đọc từ Secrets Manager thì không. |
| ☐ | Credential production đặt ở cấp folder, không phải global | Pipeline ngoài folder không thấy được, kể cả khi biết credentialsId. |
| ☐ | Bật Script Security và sandbox cho Groovy | Chặn script tuỳ ý truy cập nội bộ Jenkins. |
| ☐ | Branch protection + CODEOWNERS cho Jenkinsfile |
Ai sửa được pipeline là lấy được mọi credential pipeline đó dùng. |
| ☐ | PR từ fork không chạy pipeline có credential production | Người ngoài không được chạm vào credential của bạn. |
| ☐ | Nếu dùng OIDC: điều kiện sub giới hạn đúng repo và ref |
Wildcard rộng cho phép mọi repo trong tổ chức assume role. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Bump dev tự động, prod qua pull request có phê duyệt |
Lịch sử deploy production có người review và người chịu trách nhiệm. |
| ☐ | Commit message của bump chứa commit gốc, build URL, người kích hoạt | Bản ghi audit bền nhất — không bị xoá theo retention của Jenkins. |
| ☐ | Có timeout ở cấp pipeline và cấp stage |
Build treo chiếm agent và chặn mọi build khác. |
| ☐ | Có retry cho bước phụ thuộc mạng |
Lỗi mạng tạm thời không nên làm pipeline fail. |
| ☐ | disableConcurrentBuilds cho pipeline ghi vào repo GitOps |
Hai build cùng push vào một file gây xung đột merge. |
| ☐ | Có thông báo khi pipeline fail trên nhánh main |
main đỏ mà không ai biết là nợ kỹ thuật tích dần. |
| ☐ | Shared library ghim theo tag cho production, không dùng @main |
Một lỗi trong library làm pipeline của mọi service đỏ cùng lúc. |
latest → không biết đang chạy gì, rollback vô hiệups aux@main → một commit làm đỏ pipeline của tất cả servicedisableConcurrentBuilds → hai build tranh nhau push vào repo GitOps