Files
Scrap-Web/Jenkinsfile
samahk13 927df037b0
Scrap-Web/pipeline/pr-main This commit looks good
Scrap-Web/pipeline/head There was a failure building this commit
Add semantic versioning, LaTeX manual stage and versioned ZIP
2026-11-29 20:24:54 -05:00

341 lines
16 KiB
Groovy

// Scrap-Web pipeline: Chapter 4 CI checks + Chapter 6 secure delivery.
//
// Trust boundary:
// * Every build (branches and pull requests) runs the Chapter 4 checks on the
// controller's built-in node. No credentials, no Docker socket.
// * Delivery stages run only for trusted branches, on the 'delivery' agent,
// which holds the Docker socket and the registry/deploy credentials.
// TODO before submission: remove the feature branch from TRUSTED_BRANCH so
// only reviewed code on main can deliver.
//
// Release version: major.minor.changelist = 1.0.<Jenkins build number>,
// shown as the build name and used for the image tag, ZIP, and manual PDF.
//
// Two kinds of run:
// * Normal run (DEPLOY_RECORD empty): test, scan, build once, publish, deploy
// staging, prove idempotence, human approval, promote the SAME digest.
// * Redeploy run (DEPLOY_RECORD = a committed release record, e.g.
// releases/v1-production.yml): no build; redeploys exactly that record with
// this commit's Ansible files. Used for rollback and failed-deploy recovery.
// Production redeploys need the same approval.
def TRUSTED_BRANCH = 'main|feature/issue-24-delivery'
// Jenkins user IDs allowed to approve production. Anonymous users cannot.
def APPROVERS = 'samahk,kaylah7'
// Semantic version: bump MAJOR_MINOR by hand for a feature or breaking release;
// the changelist part is the Jenkins build number, so every build is unique.
def MAJOR_MINOR = '1.0'
def deployRecord(String record) {
withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
withEnv(["RECORD=${record}"]) {
sh '''
export PATH=/opt/ansible-venv/bin:$PATH
ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check
ansible-playbook -i ansible/inventory.ini ansible/deploy.yml \
--private-key "$DEPLOY_KEY" -e @"$RECORD"
'''
}
}
}
pipeline {
agent none
parameters {
string(name: 'DEPLOY_RECORD', defaultValue: '',
description: 'Leave EMPTY for a normal release. For rollback/recovery, the path of a committed release record, e.g. releases/v1-production.yml')
}
options {
skipDefaultCheckout()
disableConcurrentBuilds() // no competing releases
timeout(time: 60, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '50'))
}
environment {
REGISTRY = 'git.ssw590-08.me'
IMAGE = 'git.ssw590-08.me/ssw-590-08/pricing'
}
stages {
// ---------------- Chapter 4 CI (all builds, controller) ----------------
stage('CI checks') {
agent { label 'built-in' }
steps {
checkout scm
sh 'git rev-parse HEAD'
sh 'python3 --version'
sh 'python3 -m py_compile pricing.py tests/test_pricing.py'
sh 'python3 -m unittest discover -s tests -v'
}
}
// ---------------- Chapter 6 delivery (trusted branches, agent) ---------
stage('Delivery') {
when {
beforeAgent true
branch pattern: TRUSTED_BRANCH, comparator: 'REGEXP'
expression { (params.DEPLOY_RECORD ?: '').trim() == '' }
}
agent { label 'delivery' }
stages {
stage('Checkout') {
steps {
checkout scm
script {
env.APP_COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
env.IMAGE_TAG = "${env.IMAGE}:${env.APP_COMMIT}"
env.SEMVER = "${MAJOR_MINOR}.${env.BUILD_NUMBER}"
env.SEMVER_TAG = "${env.IMAGE}:${env.SEMVER}"
currentBuild.displayName = "#${env.BUILD_NUMBER} v${env.SEMVER}"
}
echo "Source commit: ${env.APP_COMMIT}"
echo "Release version: ${env.SEMVER}"
}
}
stage('Unit tests') {
steps {
dir('pricing') {
sh '''
python3 -m venv .venv
.venv/bin/pip install -q --require-hashes -r requirements.txt
.venv/bin/python -m py_compile app.py test_app.py
.venv/bin/python -m unittest -v
'''
}
}
}
// LaTeX: compile the IT manual on the Droplet, in the same TeX Live
// image the Gitea Actions workflow uses (manual/ci/Dockerfile).
// The agent talks to the host's Docker daemon, so files are copied
// into and out of the container instead of bind-mounted.
stage('Compile manual (LaTeX)') {
steps {
sh '''
docker build -q -t ssw590/manual-latex:1 manual/ci
cid=$(docker create -w /work ssw590/manual-latex:1 latexmk devopsAssignment.tex)
docker cp manual/. "$cid":/work
if docker start -a "$cid"; then rc=0; else rc=$?; fi
docker cp "$cid":/work/devopsAssignment.pdf "manual-$SEMVER.pdf" || true
docker rm "$cid" > /dev/null
[ "$rc" -eq 0 ] && [ -s "manual-$SEMVER.pdf" ] || { echo "Manual build failed"; exit 1; }
echo "Manual compiled: manual-$SEMVER.pdf"
'''
archiveArtifacts artifacts: "manual-${env.SEMVER}.pdf", fingerprint: true
}
}
// 6.4.5: dependency and secret checks on the source. Fails closed:
// a missing script, a scanner error, or a finding stops the run.
stage('Security scan: source') {
steps { sh 'bash security/scan.sh source' }
post { always { archiveArtifacts artifacts: 'security-reports/**', allowEmptyArchive: true } }
}
stage('Build image') {
steps {
dir('pricing') {
sh 'docker build --build-arg APP_COMMIT="$APP_COMMIT" -t "$IMAGE_TAG" -t "$SEMVER_TAG" .'
}
}
}
// 6.4.5: image vulnerability scan before publishing. Fails closed.
stage('Security scan: image') {
steps { sh 'bash security/scan.sh image "$IMAGE_TAG"' }
post { always { archiveArtifacts artifacts: 'security-reports/**', allowEmptyArchive: true } }
}
stage('Publish') {
steps {
withCredentials([usernamePassword(credentialsId: 'gitea-registry-push',
usernameVariable: 'REG_USER',
passwordVariable: 'REG_TOKEN')]) {
// Push, then delete the local copy and pull it back from the
// registry, so the recorded digest is the registry's, not a local ID.
sh '''
printf '%s' "$REG_TOKEN" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin
docker push "$IMAGE_TAG"
docker push "$SEMVER_TAG"
docker image rm "$IMAGE_TAG" "$SEMVER_TAG"
docker pull "$IMAGE_TAG"
docker logout "$REGISTRY"
docker image inspect "$IMAGE_TAG" --format '{{index .RepoDigests 0}}' > image-digest.txt
echo "Published: $(cat image-digest.txt)"
'''
}
script { env.IMAGE_DIGEST = readFile('image-digest.txt').trim() }
writeFile file: 'build-record.txt', text: """version: ${env.SEMVER}
source_commit: ${env.APP_COMMIT}
version_tag: ${env.SEMVER_TAG}
image_tag: ${env.IMAGE_TAG}
image_digest: ${env.IMAGE_DIGEST}
jenkins_build: ${env.BUILD_URL}
"""
archiveArtifacts artifacts: 'image-digest.txt, build-record.txt', fingerprint: true
}
}
// Deployment-ready ZIP named with the semantic version.
stage('Package') {
steps {
sh '''
rm -rf dist && mkdir -p "dist/pricing-$SEMVER"
cp pricing/app.py pricing/requirements.txt pricing/Dockerfile "dist/pricing-$SEMVER/"
cp -r ansible "dist/pricing-$SEMVER/ansible"
cp build-record.txt "dist/pricing-$SEMVER/"
printf '%s\n' "$SEMVER" > "dist/pricing-$SEMVER/VERSION"
cd dist && python3 -m zipfile -c "pricing-$SEMVER.zip" "pricing-$SEMVER"
python3 -m zipfile -l "pricing-$SEMVER.zip"
'''
archiveArtifacts artifacts: "dist/pricing-${env.SEMVER}.zip", fingerprint: true
}
}
// 6.4.6: deploy the digest just published to staging with Ansible,
// then rerun unchanged and require changed=0 (idempotence).
stage('Deploy staging') {
steps {
script {
// Expected behaviour comes from the source, not from config.
env.APP_VERSION = sh(script: "sed -n 's/^VERSION = \"\\(.*\\)\"/\\1/p' pricing/app.py", returnStdout: true).trim()
def unit = sh(script: "sed -n 's/^UNIT_PRICE = //p' pricing/app.py", returnStdout: true).trim()
env.EXPECTED_TOTAL = "${3 * (unit as Integer)}"
writeFile file: "release-${env.APP_VERSION}-staging.yml", text: """target_env: staging
release_image: ${env.IMAGE_DIGEST}
expected_version: ${env.APP_VERSION}
expected_commit: ${env.APP_COMMIT}
expected_total: ${env.EXPECTED_TOTAL}
release_version: ${env.SEMVER}
public_url: https://staging.ssw590-08.me
proxy_network: gitea-net
"""
}
archiveArtifacts artifacts: "release-${env.APP_VERSION}-staging.yml", fingerprint: true
deployRecord("release-${env.APP_VERSION}-staging.yml")
}
}
stage('Staging idempotence') {
steps {
withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
sh '''
export PATH=/opt/ansible-venv/bin:$PATH
ansible-playbook -i ansible/inventory.ini ansible/deploy.yml \
--private-key "$DEPLOY_KEY" -e @release-$APP_VERSION-staging.yml | tee rerun.log
grep -E 'startup +: .*changed=0 +unreachable=0 +failed=0' rerun.log \
|| { echo "Second run changed something: not idempotent"; exit 1; }
'''
}
}
}
// 6.4.7: restricted human approval, then promote the SAME digest.
stage('Approve production') {
steps {
script {
def scan = fileExists('security-reports/image-summary.txt') ?
readFile('security-reports/image-summary.txt').trim() : 'see security-reports'
// Only APPROVERS can approve; Abort or the timeout stops the run.
timeout(time: 30, unit: 'MINUTES') {
env.APPROVER = input(
message: """Promote ${env.APP_VERSION} (release ${env.SEMVER}) to production (https://app.ssw590-08.me)?
Source commit: ${env.APP_COMMIT}
Image digest: ${env.IMAGE_DIGEST}
Security scans: source and image gates PASSED (fixable HIGH/CRITICAL block).
${scan}
Staging: deployed, HTTPS health/version/commit/total ${env.EXPECTED_TOTAL} passed, rerun changed=0.""",
ok: 'Approve and deploy to production',
submitter: APPROVERS,
submitterParameter: 'APPROVER')
}
env.APPROVED_AT = sh(script: 'date -Is', returnStdout: true).trim()
echo "APPROVED by ${env.APPROVER} at ${env.APPROVED_AT}"
}
}
}
stage('Deploy production') {
steps {
// Same digest and commit as staging; only environment and URL change. No rebuild.
writeFile file: "release-${env.APP_VERSION}-production.yml", text: """target_env: production
release_image: ${env.IMAGE_DIGEST}
expected_version: ${env.APP_VERSION}
expected_commit: ${env.APP_COMMIT}
expected_total: ${env.EXPECTED_TOTAL}
release_version: ${env.SEMVER}
public_url: https://app.ssw590-08.me
proxy_network: gitea-net
approved_by: ${env.APPROVER}
approved_at: ${env.APPROVED_AT}
"""
archiveArtifacts artifacts: "release-${env.APP_VERSION}-production.yml", fingerprint: true
deployRecord("release-${env.APP_VERSION}-production.yml")
}
}
}
}
// ---------------- Rollback / recovery: redeploy a committed record -----
stage('Redeploy release record') {
when {
beforeAgent true
branch pattern: TRUSTED_BRANCH, comparator: 'REGEXP'
expression { (params.DEPLOY_RECORD ?: '').trim() != '' }
}
agent { label 'delivery' }
stages {
stage('Load record') {
steps {
checkout scm
script {
env.RECORD = params.DEPLOY_RECORD.trim()
if (!(env.RECORD ==~ /releases\/[A-Za-z0-9._-]+\.yml/) || !fileExists(env.RECORD)) {
error "No committed release record at ${env.RECORD}"
}
env.TARGET_ENV = sh(script: 'sed -n "s/^target_env: //p" "$RECORD"', returnStdout: true).trim()
env.CONFIG_COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
}
echo "Redeploying ${env.RECORD} to ${env.TARGET_ENV} with configuration commit ${env.CONFIG_COMMIT}"
sh 'cat "$RECORD"'
archiveArtifacts artifacts: "${env.RECORD}", fingerprint: true
}
}
stage('Approve redeploy') {
when { environment name: 'TARGET_ENV', value: 'production' }
steps {
script {
timeout(time: 30, unit: 'MINUTES') {
env.APPROVER = input(
message: "Redeploy ${env.RECORD} to PRODUCTION (configuration commit ${env.CONFIG_COMMIT})?",
ok: 'Approve redeploy',
submitter: APPROVERS,
submitterParameter: 'APPROVER')
}
echo "APPROVED by ${env.APPROVER} at ${sh(script: 'date -Is', returnStdout: true).trim()}"
}
}
}
stage('Redeploy') {
steps {
sh 'echo "Redeploy start: $(date -Is)"'
deployRecord(env.RECORD)
sh 'echo "Redeploy verified: $(date -Is)"'
}
}
}
}
}
post {
success { echo 'All stages passed.' }
failure { echo 'A stage failed: see the stage view for which one.' }
}
}