Interview › Scripting (Bash, Groovy)
How do you use environment variables and credentials in a Groovy pipeline? [Advanced]
Answer
I use the environment block for non-secret environment variables and withCredentials for secrets. Jenkins credentials should be scoped to the smallest required block and never printed or interpolated into logs unnecessarily.
Technical explanation
environment variables in Declarative Pipeline are available to steps in the pipeline or stage scope.
withCredentials binds secrets temporarily and masks them in logs when used correctly.
Avoid Groovy string interpolation of secrets in command strings; prefer single-quoted shell scripts so expansion happens in the shell with masking.
Hands-on example
pipeline {
agent any
environment {
REGISTRY = 'registry.example.com'
}
stages {
stage('Push') {
steps {
withCredentials([usernamePassword(credentialsId: 'registry-creds', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
sh 'echo "$PASS" | docker login "$REGISTRY" -u "$USER" --password-stdin'
}
}
}
}
}Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Scripting (Bash, Groovy) interview questions
- How do you handle errors and retries in a Groovy pipeline (try/catch, retry, timeout)? [Advanced]
- How do you run stages in parallel in a Jenkins Groovy pipeline? [Advanced]
- What is the difference between Groovy and Java for scripting purposes? [Advanced]
- How do you define and call a function (or step) in a Jenkins Groovy pipeline? [Advanced]
- How do you write a dry-run mode into an automation script, and why is it valuable? [Advanced]
- How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
- What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]