257 lines
14 KiB
Groovy
257 lines
14 KiB
Groovy
// Secure delivery pipeline for the Startup Pricing Service (SSW 590, Chapter 6).
|
|
// Runs only on the trusted 'delivery' agent. Release mode: test, scan, build once,
|
|
// publish, deploy staging, verify, human approval, promote the SAME digest.
|
|
// Redeploy mode: deploy a committed release record (rollback / recovery), no build.
|
|
|
|
def deployRecord(String record, String tag = '') {
|
|
// record is validated before this is called (vN-staging.yml / vN-production.yml)
|
|
withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
|
|
dir('pricing') {
|
|
sh """#!/bin/bash -e
|
|
set -o pipefail
|
|
echo "Ansible start \$(date -u +%Y-%m-%dT%H:%M:%SZ) record=${record}"
|
|
\$ANSIBLE/ansible-playbook ansible/deploy.yml --syntax-check
|
|
\$ANSIBLE/ansible-playbook ansible/deploy.yml --private-key "\$DEPLOY_KEY" \\
|
|
-e @releases/${record} | tee ../reports/ansible-${record}${tag}.log
|
|
echo "Ansible end \$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
|
"""
|
|
}
|
|
}
|
|
sh """#!/bin/bash -e
|
|
set -o pipefail
|
|
bash pricing/ci/smoke.sh pricing/releases/${record} | tee reports/smoke-${record}${tag}.log
|
|
"""
|
|
}
|
|
|
|
def approve(String what) {
|
|
def summary = """${what}
|
|
Source commit: ${env.COMMIT}
|
|
Image: ${env.DIGEST_REF}
|
|
Gates: unit tests, pip-audit, Trivy secret scan, Trivy image scan (HIGH/CRITICAL) -> see build artifacts
|
|
Staging: ${env.STAGING_RESULT}"""
|
|
timeout(time: 30, unit: 'MINUTES') {
|
|
env.APPROVER = input(message: summary, ok: 'Approve', submitter: env.APPROVERS,
|
|
submitterParameter: 'APPROVER')
|
|
}
|
|
env.APPROVED_AT = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true).trim()
|
|
writeFile file: 'reports/approval.txt',
|
|
text: "decision=approved\napprover=${env.APPROVER}\napproved_at=${env.APPROVED_AT}\nrequest=${what}\n"
|
|
echo "Approved by ${env.APPROVER} at ${env.APPROVED_AT}"
|
|
}
|
|
|
|
pipeline {
|
|
agent { label 'delivery' }
|
|
options {
|
|
disableConcurrentBuilds()
|
|
buildDiscarder(logRotator(numToKeepStr: '50'))
|
|
timeout(time: 75, unit: 'MINUTES')
|
|
}
|
|
parameters {
|
|
string(name: 'BRANCH', defaultValue: 'main',
|
|
description: 'Branch to build. Only main is published and deployed.')
|
|
choice(name: 'MODE', choices: ['release', 'redeploy'],
|
|
description: 'release: full gated delivery. redeploy: deploy a committed release record (rollback/recovery).')
|
|
string(name: 'RECORD', defaultValue: '',
|
|
description: 'redeploy only: file in pricing/releases, e.g. v1-production.yml')
|
|
}
|
|
environment {
|
|
REGISTRY = 'git.ssw590.abrdns.com'
|
|
IMAGE = 'git.ssw590.abrdns.com/startupteam/pricing'
|
|
ANSIBLE = '/opt/ansible-venv/bin'
|
|
PIPAUDIT = '/opt/pip-audit-venv/bin/pip-audit'
|
|
PROXY_NET = 'startup_private'
|
|
STAGING_URL = 'https://staging.ssw590.abrdns.com'
|
|
PROD_URL = 'https://app.ssw590.abrdns.com'
|
|
APPROVERS = 'sbhayana,sdevanahally'
|
|
ANSIBLE_CONFIG = "${WORKSPACE}/pricing/ansible.cfg"
|
|
}
|
|
stages {
|
|
stage('Identify source') {
|
|
steps {
|
|
script {
|
|
env.COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
|
|
env.STAGING_RESULT = 'not run'
|
|
}
|
|
sh '''
|
|
rm -rf reports && mkdir -p reports
|
|
git log -1 --format='commit %H%nauthor %an%ndate %cI%nsubject %s' | tee reports/source.txt
|
|
echo "branch ${BRANCH} mode ${MODE} build ${BUILD_URL}" | tee -a reports/source.txt
|
|
{ docker version --format 'docker client {{.Client.Version}} server {{.Server.Version}}'
|
|
python3 --version; trivy --version | head -1; $PIPAUDIT --version
|
|
$ANSIBLE/ansible --version | head -1
|
|
$ANSIBLE/ansible-galaxy collection list community.docker 2>/dev/null | tail -1; } | tee reports/tools.txt
|
|
'''
|
|
withCredentials([usernamePassword(credentialsId: 'gitea-status-token', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_TOKEN')]) {
|
|
sh 'bash pricing/ci/gitea_status.sh pending "Jenkins delivery pipeline running" || echo "status post failed (non-fatal)"'
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------- release mode: gates ----------------
|
|
stage('Unit tests') {
|
|
when { expression { params.MODE == 'release' } }
|
|
steps {
|
|
dir('pricing/app') {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
python3 -m venv .venv && . .venv/bin/activate
|
|
pip install --quiet --require-hashes -r requirements.txt
|
|
python -m py_compile app.py test_app.py
|
|
python -m unittest -v 2>&1 | tee ../../reports/unittest.log
|
|
'''
|
|
}
|
|
}
|
|
}
|
|
stage('Dependency audit') {
|
|
when { expression { params.MODE == 'release' } }
|
|
steps {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
$PIPAUDIT --disable-pip --require-hashes --strict -r pricing/app/requirements.txt \
|
|
--format columns 2>&1 | tee reports/pip-audit.log
|
|
'''
|
|
}
|
|
}
|
|
stage('Secret scan') {
|
|
when { expression { params.MODE == 'release' } }
|
|
steps {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
trivy fs --scanners secret --exit-code 1 --no-progress \
|
|
--skip-dirs .git --skip-dirs pricing/app/.venv --skip-dirs reports . 2>&1 | tee reports/trivy-secrets.log
|
|
'''
|
|
}
|
|
}
|
|
stage('Build image') {
|
|
when { expression { params.MODE == 'release' } }
|
|
steps {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
docker build --build-arg APP_COMMIT="$COMMIT" -t "$IMAGE:$COMMIT" pricing/app 2>&1 | tee reports/docker-build.log
|
|
docker image inspect "$IMAGE:$COMMIT" --format 'local image id {{.Id}} arch {{.Architecture}}' | tee -a reports/docker-build.log
|
|
'''
|
|
}
|
|
}
|
|
stage('Image scan') {
|
|
when { expression { params.MODE == 'release' } }
|
|
steps {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
IGNORE=""
|
|
[ -s pricing/security/trivyignore.yaml ] && IGNORE="--ignorefile pricing/security/trivyignore.yaml"
|
|
# Policy gate: any HIGH or CRITICAL vulnerability blocks (fixed or not) unless a
|
|
# documented, time-limited exception exists in pricing/security/trivyignore.yaml.
|
|
trivy image --scanners vuln --severity HIGH,CRITICAL --exit-code 1 --no-progress --show-suppressed $IGNORE \
|
|
"$IMAGE:$COMMIT" 2>&1 | tee reports/trivy-image-gate.log
|
|
# Full report of all severities for the record (does not gate).
|
|
trivy image --scanners vuln --no-progress --skip-db-update --format json \
|
|
--output reports/trivy-image-all.json "$IMAGE:$COMMIT"
|
|
'''
|
|
}
|
|
}
|
|
|
|
// ---------------- release mode: publish (main only) ----------------
|
|
stage('Publish image') {
|
|
when { allOf { expression { params.MODE == 'release' }; expression { params.BRANCH == 'main' } } }
|
|
steps {
|
|
withCredentials([usernamePassword(credentialsId: 'gitea-registry-write',
|
|
usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) {
|
|
sh '''#!/bin/bash -e
|
|
set -o pipefail
|
|
export DOCKER_CONFIG="$WORKSPACE/.docker-publish"
|
|
printf '%s' "$REG_TOKEN" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin
|
|
# Releases are immutable: never overwrite an existing tag (see Chapter 6, rollback incident).
|
|
if docker manifest inspect "$IMAGE:$COMMIT" >/dev/null 2>&1; then
|
|
echo "ERROR: $IMAGE:$COMMIT is already published; releases are immutable. Use MODE=redeploy with the committed record." >&2
|
|
docker logout "$REGISTRY"; exit 1
|
|
fi
|
|
docker push "$IMAGE:$COMMIT" 2>&1 | tee reports/docker-push.log
|
|
docker rmi "$IMAGE:$COMMIT"
|
|
docker pull "$IMAGE:$COMMIT" 2>&1 | tee reports/docker-pull.log
|
|
docker image inspect "$IMAGE:$COMMIT" --format '{{range .RepoDigests}}{{println .}}{{end}}' \
|
|
| grep "^$IMAGE@sha256:" | head -1 > reports/image-digest.txt
|
|
docker logout "$REGISTRY"; rm -rf "$DOCKER_CONFIG"
|
|
echo "Published $(cat reports/image-digest.txt)"
|
|
'''
|
|
}
|
|
sh 'python3 pricing/ci/write_release.py'
|
|
script {
|
|
env.APP_VERSION = sh(script: "sed -n 's/^APP_VERSION=//p' reports/release.env", returnStdout: true).trim()
|
|
env.EXPECTED_TOTAL = sh(script: "sed -n 's/^EXPECTED_TOTAL=//p' reports/release.env", returnStdout: true).trim()
|
|
env.DIGEST_REF = sh(script: "sed -n 's/^DIGEST_REF=//p' reports/release.env", returnStdout: true).trim()
|
|
}
|
|
}
|
|
}
|
|
stage('Deploy staging') {
|
|
when { allOf { expression { params.MODE == 'release' }; expression { params.BRANCH == 'main' } } }
|
|
steps {
|
|
script { deployRecord("${env.APP_VERSION}-staging.yml") }
|
|
}
|
|
}
|
|
stage('Staging idempotence') {
|
|
when { allOf { expression { params.MODE == 'release' }; expression { params.BRANCH == 'main' } } }
|
|
steps {
|
|
script {
|
|
deployRecord("${env.APP_VERSION}-staging.yml", '-rerun')
|
|
def recap = sh(script: "grep -E '^startup +:' reports/ansible-${env.APP_VERSION}-staging.yml-rerun.log",
|
|
returnStdout: true).trim()
|
|
if (!recap.contains('changed=0 ')) { error "Second Ansible run was not idempotent: ${recap}" }
|
|
env.STAGING_RESULT = "${env.STAGING_URL} healthy, ${env.APP_VERSION}, total ${env.EXPECTED_TOTAL}, rerun ${recap}"
|
|
writeFile file: 'reports/staging-result.txt', text: env.STAGING_RESULT + '\n'
|
|
}
|
|
}
|
|
}
|
|
stage('Approve production') {
|
|
when { allOf { expression { params.MODE == 'release' }; expression { params.BRANCH == 'main' } } }
|
|
steps {
|
|
script { approve("Promote ${env.APP_VERSION} (${env.COMMIT.substring(0, 10)}) to PRODUCTION ${env.PROD_URL}?") }
|
|
}
|
|
}
|
|
stage('Deploy production') {
|
|
when { allOf { expression { params.MODE == 'release' }; expression { params.BRANCH == 'main' } } }
|
|
steps {
|
|
script { deployRecord("${env.APP_VERSION}-production.yml") }
|
|
}
|
|
}
|
|
|
|
// ---------------- redeploy mode: rollback / recovery ----------------
|
|
stage('Redeploy committed record') {
|
|
when { expression { params.MODE == 'redeploy' } }
|
|
steps {
|
|
script {
|
|
if (params.BRANCH != 'main') { error 'Redeploy only from reviewed main' }
|
|
if (!(params.RECORD ==~ /^v[0-9]+-(staging|production)\.yml$/)) { error "Bad RECORD '${params.RECORD}'" }
|
|
def path = "pricing/releases/${params.RECORD}"
|
|
if (!fileExists(path)) { error "${path} is not committed on main" }
|
|
def cfg = sh(script: "awk '\$1==\"config_commit:\"{print \$2}' ${path}", returnStdout: true).trim()
|
|
if (!(cfg ==~ /^[0-9a-f]{40}$/)) { error "Record has no valid config_commit" }
|
|
// Restore the deployment configuration that was reviewed with this release.
|
|
sh "git checkout ${cfg} -- pricing/ansible && git log -1 --format='config %H %s' ${cfg} | tee reports/config.txt"
|
|
env.DIGEST_REF = sh(script: "awk '\$1==\"release_image:\"{print \$2}' ${path}", returnStdout: true).trim()
|
|
env.STAGING_RESULT = 'redeploy of a committed record (no new build)'
|
|
if (params.RECORD.contains('production')) {
|
|
approve("REDEPLOY ${params.RECORD} to PRODUCTION (rollback/recovery)?")
|
|
}
|
|
deployRecord(params.RECORD)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
post {
|
|
success {
|
|
withCredentials([usernamePassword(credentialsId: 'gitea-status-token', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_TOKEN')]) {
|
|
sh 'bash pricing/ci/gitea_status.sh success "Jenkins: all gates passed" || true'
|
|
}
|
|
}
|
|
unsuccessful {
|
|
withCredentials([usernamePassword(credentialsId: 'gitea-status-token', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_TOKEN')]) {
|
|
sh 'bash pricing/ci/gitea_status.sh failure "Jenkins: a gate failed or approval was not given" || true'
|
|
}
|
|
}
|
|
always {
|
|
sh 'date -u +"finished %Y-%m-%dT%H:%M:%SZ" >> reports/source.txt; ls pricing/releases/ > reports/records.txt'
|
|
archiveArtifacts artifacts: 'reports/**, pricing/releases/v*.yml', allowEmptyArchive: true, fingerprint: true
|
|
}
|
|
}
|
|
}
|