How to set up envVars in container in Jenkins pipeline with Kubernetes plugin - kubernetes

I'm setting up a Jenkins pipeline with Kubernetes, there is an option to set environment variables for a container in containerTemplate. Is there some option to override those values in container i.e.:
container(
name: 'my-container',
envVars: [
envVar(key: $KEY, value: $VALUE)
]) {
...
}
because some variables are derived during build stages and cannot be set up in podTemplate. The example above unfortunately does not work.

Note that as of this writing as per the docs:
The container statement allows to execute commands directly into each container. This feature is considered ALPHA as there are still some problems with concurrent execution and pipeline resumption
I believe there is not an option. However, you can try setting the variables in the sh command. For example:
def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(label: label, containers: [
containerTemplate(name: 'maven', image: 'maven:3.3.9-jdk-8-alpine', ttyEnabled: true, command: 'cat'),
containerTemplate(name: 'golang', image: 'golang:1.8.0', ttyEnabled: true, command: 'cat')
]) {
node(label) {
stage('Get a Maven project') {
git 'https://github.com/jenkinsci/kubernetes-plugin.git'
container('maven') {
stage('Build a Maven project') {
sh 'MYENV1=value1 MYEVN2=value2 mvn -B clean install'
}
}
}
stage('Get a Golang project') {
git url: 'https://github.com/hashicorp/terraform.git'
container('golang') {
stage('Build a Go project') {
sh """
mkdir -p /go/src/github.com/hashicorp
ln -s `pwd` /go/src/github.com/hashicorp/terraform
MYENV1=value1 MYEVN2=value2 cd /go/src/github.com/hashicorp/terraform && make core-dev
"""
}
}
}
}
}

Related

Deploy docker image from Nexus registry

I have this Jenkinsfile which I want to use to build a pipeline:
pipeline {
agent any
environment {
NEXUS_VERSION = "nexus3"
NEXUS_PROTOCOL = "http"
NEXUS_URL = "you-ip-addr-here:8081"
NEXUS_REPOSITORY = "maven-nexus-repo"
NEXUS_CREDENTIAL_ID = "nexus-user-credentials"
}
stages {
stage('Download Helm Charts') {
steps {
sh "echo 'Downloading Helm Charts from Bitbucket repository...'"
// configure credentials under http://192.168.1.28:8080/user/test/credentials/ and put credentials ID
// not sure do I need to point the root folder of the Helm repository or only the single chart
checkout scmGit(
branches: [[name: 'master']],
userRemoteConfigs: [[credentialsId: 'c2672602-dfd5-4158-977c-5009065c867e',
url: 'http://192.168.1.30:7990/scm/jen/helm.git']])
}
}
stage('Test Kubernetes version') {
steps {
sh "echo 'Checking Kubernetes version..'"
// How to do remote test of kubernetes version
}
}
stage('Push Helm Charts to Kubernetes') {
steps {
sh "echo 'building..'"
// push here helm chart from Jenkins server to Kubernetes cluster
}
}
stage('Build Image') {
steps {
sh "echo 'building..'"
// configure credentials under http://192.168.1.28:8080/user/test/credentials/ and put credentials ID
git credentialsId: 'bitbucket-server:50001e738fa6dafbbe7e336853ced1fcbc284fb18ea8cda8b54dbfa3a7bc87b9', url: 'http://192.168.1.30:7990/scm/jen/spring-boot-microservice.git', branch: 'master'
// execute Java -jar ... and build docker image
./gradlew build && java -jar build/libs/gs-spring-boot-docker-0.1.0.jar
docker build -t springio/gs-spring-boot-docker .
}
}
stage('Push Image into Nexus registry') {
steps {
sh "echo 'building..'"
// push compiled docker image into Nexus repository
script {
pom = readMavenPom file: "pom.xml";
filesByGlob = findFiles(glob: "target/*.${pom.packaging}");
echo "${filesByGlob[0].name} ${filesByGlob[0].path} ${filesByGlob[0].directory} ${filesByGlob[0].length} ${filesByGlob[0].lastModified}"
artifactPath = filesByGlob[0].path;
artifactExists = fileExists artifactPath;
if(artifactExists) {
echo "*** File: ${artifactPath}, group: ${pom.groupId}, packaging: ${pom.packaging}, version ${pom.version}";
nexusArtifactUploader(
nexusVersion: NEXUS_VERSION,
protocol: NEXUS_PROTOCOL,
nexusUrl: NEXUS_URL,
groupId: pom.groupId,
version: pom.version,
repository: NEXUS_REPOSITORY,
credentialsId: NEXUS_CREDENTIAL_ID,
artifacts: [
[artifactId: pom.artifactId,
classifier: '',
file: artifactPath,
type: pom.packaging],
[artifactId: pom.artifactId,
classifier: '',
file: "pom.xml",
type: "pom"]
]
);
} else {
error "*** File: ${artifactPath}, could not be found";
}
}
}
}
stage('Deploy Image from Nexus registry into Kubernetes') {
steps {
sh "echo 'building..'"
}
}
stage('Test'){
steps {
sh "echo 'Testing...'"
// implement a check here is it deployed sucessfully
}
}
}
}
How I can deploy the docker image build by Jenkins server and pushed in Nexus repository? If possible I want to use service account with token?
Instead of using 'nexusArtifactUploader', why don´t you use docker push, like you do to build the image?
I guess nexusArtifactUploader uses Nexus API and doesn´t work with docker images, but you can access the registry using docker and the exposed port (defaults to 5000)
withCredentials([string(credentialsId: NEXUS_CREDENTIAL_ID, variable: 'registryToken')]) {
sh 'docker push --creds default:${registryToken} your-registry-url/image-name:image-tag'
}
You may also change docker build command to build the image using your registry name (or tag it after building, see How to push a docker image to a private repository)

Bitbucket pipeline fails with mongo service

I'm trying to setup test for my backend in Bitbucket Pipelines. But when I set jest.config with jest-mongodb the tests doesn't even start and exit with this error.
The tests are working perfectly fine on local.
Here's my pipeline configuration part that doesn't work:
image: node:18.12.0
definitions:
services:
mongo:
image: mongo
caches:
nodeall: ./node_modules
yarn: /usr/local/share/.cache/yarn
steps:
- step: &Quality-Check
name: Code Quality Checks 🎀
script:
- echo Fixing code quality and format 🔎
- yarn install
- yarn run lint:fix
- yarn format:fix
- step: &Testing
name: Testing 🧪
caches:
- nodeall
script:
- yarn install
# - yarn run test
- echo Checking test coverage and generating report 📜
- yarn run test:coverage
artifacts:
- coverage/**
services:
- mongo
pipelines:
branches:
main:
- step:
name: Install dependencies
caches:
- nodeall
script:
- yarn install
- step: *Quality-Check
- step: *Testing
When i search for this error i'm headed to mongo-memory-server but i don't use this package in the code. And couldn't find anything.
I've tried changing anchors, calling mongo service earlier, changing mongo docker image but no success.
I'm expecting that the test and pipeline pass
EDIT
I tried 3 different Jest.configs and realise that the one that was on the project actually use memory-server.
Here are the 3 configs i tried
const { defaults: tsjPreset } = require('ts-jest/presets')
//Custom config with files
// module.exports = {
// preset: 'ts-jest',
// globalSetup: './mongo-memory-server/globalSetup.ts',
// globalTeardown: './mongo-memory-server/globalTeardown.ts',
// setupFilesAfterEnv: ['./mongo-memory-server/setupFile.ts'],
// }
//Config for mongo-memory-db
module.exports = {
preset: '#shelf/jest-mongodb',
transform: tsjPreset.transform,
}
// Basic config
// module.exports = {
// preset: 'ts-jest',
// testEnvironment: 'node',
// setupFiles: ['dotenv/config'],
// }

run my test in docker mongo instance using jenkins pipeline

I would like to run my tests against a Docker MongoDB instance using Jenkins pipeline. I have got it working kind of. My problem is the tests are running within the Mongo container. I just want it to load up a container and my tests for it to connect to the Monogo container. At the moment it downloads Gradle within the container and takes about 5 min to run. Hope that makes sense. Here is my JenkinsFile
#!/usr/bin/env groovy
pipeline {
environment {
SPRING_PROFILES_ACTIVE = "jenkins"
}
agent {
node {
label "jdk8"
}
}
parameters {
choice(choices: 'None\nBuild\nMinor\nMajor', description: '', name: 'RELEASE_TYPE')
string(defaultValue: "refs/heads/master:refs/remotes/origin/master", description: 'gerrit refspec e.g. refs/changes/45/12345/1', name: 'GERRIT_REFSPEC')
choice(choices: 'master\nFETCH_HEAD', description: 'gerrit branch', name: 'GERRIT_BRANCH')
}
stages {
stage("Test") {
stages {
stage("Initialise") {
steps {
println "Running on ${NODE_NAME}, release type: ${params.RELEASE_TYPE}"
println "gerrit refspec: ${params.GERRIT_REFSPEC}, branch: ${params.GERRIT_BRANCH}, event type: ${params.GERRIT_EVENT_TYPE}"
checkout scm
sh 'git log -n 1'
}
}
stage("Verify") {
agent {
dockerfile {
filename 'backend/Dockerfile'
args '-p 27017:27017'
label 'docker-pipeline'
dir './maintenance-notifications'
}
}
steps {
sh './gradlew :maintenance-notifications:backend:clean'
sh './gradlew :maintenance-notifications:backend:check :maintenance-notifications:backend:test'
}
post {
always {
junit 'maintenance-notifications/backend/build/test-results/**/*.xml'
}
}
}
}
}
stage("Release") {
when {
expression {
return params.RELEASE_TYPE != '' && params.RELEASE_TYPE != 'None';
}
}
steps {
script {
def gradleProps = readProperties file: "gradle.properties"
def isCurrentSnapshot = gradleProps.version.endsWith("-SNAPSHOT")
def newVersion = gradleProps.version.replace("-SNAPSHOT", "")
def cleanVersion = newVersion.tokenize(".").collect{it.toInteger()}
if (params.RELEASE_TYPE == 'Build') {
newVersion = "${cleanVersion[0]}.${cleanVersion[1]}.${isCurrentSnapshot ? cleanVersion[2] : cleanVersion[2] + 1}"
} else if (params.RELEASE_TYPE == 'Minor') {
newVersion = "${cleanVersion[0]}.${cleanVersion[1] + 1}.0"
} else if (params.RELEASE_TYPE == 'Major') {
newVersion = "${cleanVersion[0] + 1}.0.0"
}
def newVersionArray = newVersion.tokenize(".").collect{it.toInteger()}
def newSnapshot = "${newVersionArray[0]}.${newVersionArray[1]}.${newVersionArray[2] + 1}-SNAPSHOT"
println "release version: ${newVersion}, snapshot version: ${newSnapshot}"
sh "./gradlew :maintenance-notifications:backend:release -Prelease.useAutomaticVersion=true -Prelease.releaseVersion=${newVersion} -Prelease.newVersion=${newSnapshot}"
}
}
}
}
}
and here is my Dockerfile
FROM centos:centos7
ENV container=docker
RUN mkdir -p /usr/java; curl http://configuration/yum/thecloud/artifacts/java/jdk-8u151-linux-x64.tar.gz|tar zxC /usr/java && ln -s /usr/java/jdk1.8.0_151/bin/j* /usr/bin
RUN mkdir -p /usr/mongodb; curl http://configuration/yum/thecloud/artifacts/mongodb/mongodb-linux-x86_64-3.4.10.tgz|tar zxC /usr/mongodb && ln -s /usr/mongodb/mongodb-linux-x86_64-3.4.10/bin/* /usr/bin
ENV JAVA_HOME /usr/java/jdk1.8.0_151/
ENV SPRING_PROFILES_ACTIVE jenkins
RUN yum -y install git.x86_64 && yum clean all
# Set up directory requirements
RUN mkdir -p /data/db /var/log/mongodb /var/run/mongodb
VOLUME ["/data/db", "/var/log/mongodb"]
# Expose port 27017 from the container to the host
EXPOSE 27017
CMD ["--port", "27017", "--pidfilepath", "/var/run/mongodb/mongod.pid"]
# Start mongodb
ENTRYPOINT /usr/bin/mongod

How to execute a database script after deploying a Postgresql image to openshift with Jenkins?

I have a git repo with the Jenkins pipeline and the official template of postgresql:
kind: "BuildConfig"
apiVersion: "v1"
metadata:
name: "postgresql-pipeline"
spec:
strategy:
jenkinsPipelineStrategy:
jenkinsfile: |-
pipeline {
agent any
environment {
DATABASE_NAME = 'sampledb'
DATABASE_USER = 'root'
DATABASE_PASSWORD = 'root'
}
stages {
stage('Clone git') {
steps {
git 'https://bitbucket.org/businnessdata_db/postgresql-test.git'
}
}
stage('Deploy db') {
steps {
sh 'oc status'
sh 'oc delete secret/postgresql'
sh 'oc delete pvc/postgresql'
sh 'oc delete all -l "app=postgresql-persistent"'
sh 'oc new-app -f openshift/templates/postgresql-persistent.json'
}
}
stage('Execute users script') {
steps {
sh 'oc status'
}
}
stage('Execute update script') {
steps {
sh 'oc status'
}
}
}
}
type: JenkinsPipeline<code>
What i have to put in the last 2 steps to run a script against the new generated database?
You can either install psql on your Jenkins container and then run the script through the shell command.
sh """
export PGPASSWORD=<password>
psql -h <host> -d <database> -U <user_name> -p <port> -a -w -f <file>.sql
"""
Or, since Jenkinsfiles are written in Groovy, use Groovy to execute your statements. Here's the Groovy documentation for working with databases.

How to pass jenkins build environment into pod using kubernetes plugin?

Env: Jenkins 2.73.1 & Kubernetes plugin 1.0
Inside the container, I like to get the normal jenkins build environment variable like BUILD_NUMBER
podTemplate(label: 'mypod', containers: [
containerTemplate(name: 'python', image: 'python:2.7.8', ttyEnabled: true)
]) {
node("mypod") {
echo sh(returnStdout: true, script: 'env')
container('python') {
stage('Checkout') {
sh "env"
}
}
}
}
So far in the code above, inside python, it doesn't have the traditional build variable.
Any solution to get those variables inside container?
You can use env.BUILD_NUMBER
i.e.
node{
echo env.BUILD_NUMBER
}
Also if you want a list of all the env vars that are available you can run
node{
echo "${env.getEnvironment()}"
}
These are the default jenkins plugins env vars but you can also set env vars for your kubernetes plugin build pods in the pod template, for example..
envVars: [
envVar(key: 'GOPATH', value: '/home/jenkins/go')
]),
FWIW here's that code being used https://github.com/fabric8io/fabric8-pipeline-library/blob/3834f0f/vars/goTemplate.groovy#L27
More details here