I want to pass Kubernetes secret key and value in the Jenkins job using a Declarative pipeline.
I am trying to read the k8s secret values using the pod template. Configured the k8s plugin and the image has environment variables set. I need to overwrite the environment values with the k8s secret.
spec:
containers:
- env:
- name: K8S-SECRET
valueFrom:
secretKeyRef:
key: USERNAME
name: PASSWORD
pipeline {
agent {
kubernetes {
label 'docker'
envVars: [containersecretEnvVar(key: 'USERNAME', value:'PASSWORD')]
}
}
environment {
BRANCH = 'origin/master'
PROJECT_NAME = 'k8s'
}
stages{
stage('print k8s secret'){
steps {
echo "k8s_secret_name: ${env.k8s_secret_name}"
echo "k8s_secret_valie: ${env.k8s_secret_value}"
}
}
}
}
To clarify I am posting the Community wiki answer from comments' section.
To solve that problem Original Poster created the following code:
podTemplate(inheritFrom: 'docker', containers: [
containerTemplate( name: "jnlp", image: "<image_name>",
envVars: [
envVar(key: "NAME", value: "custom_env"),
secretEnvVar(key: "SECRET_ENV", secretName: "K8S-SECRET", secretKey: "USERNAME")
]) ] ){
node(POD_LABEL) {
step {
sh 'echo ${TOKEN}'
...
}
}
In this solution PodTemplates
has been used. In this documentation one can find more info about that:
Pod templates are used to create agents. They can be either configured via the user interface, or in a pipeline, using the
podTemplate
step.
Here you can find how to define a podTemplate to use in the kubernetes plugin.
See also this documentation that describes podTemplate
.
Controllers for workload resources create Pods from a pod template and manage those Pods on your behalf.
PodTemplates are specifications for creating Pods, and are included in workload resources such as Deployments, Jobs, and DaemonSets.
Each controller for a workload resource uses the
PodTemplate
inside the workload object to make actual Pods. ThePodTemplate
is part of the desired state of whatever workload resource you used to run your app.