I'm building a microservice, using continuous delivery pipeline.
stage('package') makes the serviceImage variable, but how do I get and use it at stage('deploy')?
main.groovy
def call(body) {
def config = [ : ]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
stage('package') {
if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
echo 'Packaging...'
sh "docker pull ciregistry.i-counting.cn:8443/pilipa/openjdk:1.8"
sh "docker tag ciregistry.i-counting.cn:8443/pilipa/openjdk:1.8 pilipa/openjdk:1.8"
sh returnStdout: true, script: 'mkdir -p build/libs & cp -f src/main/docker/Dockerfile build/libs'
script {
serviceImage = dockerImageBuild {
imageName = "${config.serviceName}:${config.tagId}"
contextPath = "build/libs/"
}
}
}
}
stage('deploy') {
if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
echo 'Deploying...'
script {
dockerImageDeploy {
imageTag = "${config.tagId}"
}
}
}
}
} catch (err) {
currentBuild.result = 'FAILED'
throw err
}
}
package.groovy
def call(body) {
def config = [
registry: "https://ciregistry.i-counting.cn:8443",
]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
docker.withRegistry(config.registry) {
serviceImage = docker.build(config.imageName, config.contextPath)
}
}
deploy.groovy
def call(body) {
def config = [
registry: "https://ciregistry.i-counting.cn:8443",
]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
docker.withRegistry(config.registry) {
serviceImage.push(config.imageTag)
serviceImage.push('latest')
}
}
You need to declare the serviceImage variable inside the call function but outside of stages code, like this:
def call(body) {
//Variable for your use
def serviceImage = ""
def config = [ : ]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
stage('package') {
if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
echo 'Packaging...'
sh "docker pull ciregistry.i-counting.cn:8443/pilipa/openjdk:1.8"
sh "docker tag ciregistry.i-counting.cn:8443/pilipa/openjdk:1.8 pilipa/openjdk:1.8"
sh returnStdout: true, script: 'mkdir -p build/libs & cp -f src/main/docker/Dockerfile build/libs'
script {
serviceImage = dockerImageBuild {
imageName = "${config.serviceName}:${config.tagId}"
contextPath = "build/libs/"
}
}
}
}
stage('deploy') {
//You can use your serviceImage variable
if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
echo 'Deploying...'
script {
dockerImageDeploy {
imageTag = "${config.tagId}"
}
}
}
}
} catch (err) {
currentBuild.result = 'FAILED'
throw err
}
Related
I have this code:
#Library('cm-library') _
def GITOPS_GITHUB_TOKEN = credentials('someToken')
def GITOPS_GITHUB_BRANCH = "dev"
def X_GW_IMS_ORG_ID = "someId"
def SPRING_PROFILES_ACTIVE = "dev"
def GITOPS_INPUT_JOBSTORUN = "someJobToRun"
def IMG = "someImage"
def GITOPS_IMS_CLIENT_SECRET = ""
def GITOPS_IMS_CLIENTCODE = ""
def ARTIFACTORY_API_TOKEN = ""
pipeline {
agent any
stages {
stage('Prepare Variables') {
steps {
script {
dockerRegistryVaultAuth("some-vault.com", "dev") {
def configuration = [$class : 'VaultConfiguration',
vaultUrl : "some-vault.com",
vaultCredentialId: env.VAULT_ROLE]
def secrets = [
[
$class: 'VaultSecret', path: "${env.VAULT_PATH}/keys", secretValues:
[
[$class: 'VaultSecretValue', envVar: 'GITOPS_IMS_CLIENT_SECRET', vaultKey: 'someKey'],
[$class: 'VaultSecretValue', envVar: 'GITOPS_IMS_CLIENTCODE', vaultKey: 'someOtherKey'],
[$class: 'VaultSecretValue', envVar: 'ARTIFACTORY_API_TOKEN', vaultKey: 'someToken']
]
]
]
wrap([$class: 'VaultBuildWrapper', vaultSecrets: secrets, configuration: configuration]) {
sh "echo working"
}
}
}
}
}
stage('Build and push docker') {
steps {
echo "stage 2!!!"
echo "---------env.GITOPS_IMS_CLIENTCODE=$env.GITOPS_IMS_CLIENTCODE"
echo "---------GITOPS_IMS_CLIENT_SECRET=$GITOPS_IMS_CLIENT_SECRET"
sh "docker run -it -e GITOPS_GITHUB_BRANCH=${GITOPS_GITHUB_BRANCH} \
-e GITOPS_GITHUB_TOKEN=${GITOPS_GITHUB_TOKEN} \
-e GITOPS_IMS_CLIENT_SECRET=${GITOPS_IMS_CLIENT_SECRET} \
-e GITOPS_IMS_CLIENTCODE=${GITOPS_IMS_CLIENTCODE} \
-e X_GW_IMS_ORG_ID=${X_GW_IMS_ORG_ID} \
-e ARTIFACTORY_API_TOKEN=${ARTIFACTORY_API_TOKEN} \
-e REGION_NAME=local \
${IMG}"
}
}
stage('Stage 3') {
steps {
echo 'stage three here!'
}
}
}
}
I'm trying to make a docker container run from my Jenkins platform.
It seems like the variable values aren't being transferred from one stage to another. I also doubt the script I'm trying to run is right, but that's another problem.
Anyone any clue how to fix it?
When you declare a variable with the def keyword, it will be bound to the scope it's declared in. So simply remove the def keyword from the declaration.
pipeline {
agent any
stages {
stage('11') {
steps {
script {
vr = "test"
}
}
}
stage('22') {
steps {
script {
echo "$vr"
}
}
}
}
}
How to place a condition in node for select an agent master or stage?
def curNode = "${env.Environment}"
node(curNode === 'prod' ? 'master' : 'stage') { <= "error this"
try {
dir(env.Environment) {
stage("Clone repository") {
echo "clong success"
}
}
} catch (e) {
echo 'Error occurred during build process!'
echo e.toString()
currentBuild.result = 'FAILURE'
}
}
If you need to compare two strings, you need to use ==. When you use === it checked whether the objects are identical. Hence update your Script like the below.
def curNode = "${env.Environment}"
node(curNode == 'prod' ? 'master' : 'stage') { <= "error this"
try {
dir(env.Environment) {
stage("Clone repository") {
echo "clong success"
}
}
} catch (e) {
echo 'Error occurred during build process!'
echo e.toString()
currentBuild.result = 'FAILURE'
}
}
I would like to create a Pipeline in Jenkins which get the value of a command executed with sshCommand.
I've got a file like this on a remote server :
VALUE 11
Here is my Pipeline :
pipeline {
agent any
stages {
stage('Get Init') {
steps {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'xxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
script {
def remote = [:]
remote.name = 'xxxxxx'
remote.host = 'xxxxxx'
remote.user = USERNAME
remote.port = 22
remote.password = PASSWORD
remote.allowAnyHosts = true
sshCommand remote: remote, command: "init=\$(cat /var/log/myFile | grep VALUE | awk '{print \$2}')"
}
}
}
}
stage("Test") {
steps {
script {
test = sh(script "echo $init")
}
}
}
}
}
}
I want to get the "11" in a variable to compare it later in my Jenkinsfile. How to do this ?
You can use in below way :
Example:
def Result = sshCommand remote: remote, command: "<Your command>"
# Declare variable init
def init
pipeline {
agent any
stages {
stage('Get Init') {
steps {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'xxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
script {
def remote = [:]
remote.name = 'xxxxxx'
remote.host = 'xxxxxx'
remote.user = USERNAME
remote.port = 22
remote.password = PASSWORD
remote.allowAnyHosts = true
# Execute your command and take return value in the init variable
init= sshCommand remote: remote, command: "cat /var/log/myFile | grep VALUE | awk '{print \$2}')"
echo "Initial Value: " + init
}
}
}
}
stage("Test") {
steps {
script {
test = sh(script "echo ${init}")
}
}
}
}
}
}
In jenkins I have a choice:
choice(name: 'SERVICE', choices: ['SERVICE1', 'SERVICE2', 'SERVICE3', 'SERVICE4', 'SERVICE5', 'SERVICE6'], description: 'service')
Is there a way to set a variables depending of the above choice?
Something like this:
IF SERVICE == SERVICE1 then SERVICE_ID == SERVICE1_ID
IF SERVICE == SERVICE2 then SERVICE_ID == SERVICE2_ID
I'm struggling to find a plugin for this but I don't mind hardcoding in into jenkinsfile like above.
Done it
pipeline {
agent any
parameters {
choice(name: 'SERVICE', choices: ['Service1', 'Service2', 'Service3', 'Service4', 'Service5'], description: 'service')
}
stages {
stage('Stage 1') {
steps {
echo "This is Stage 1"
script {
if (env.SERVICE == 'Service1') {
echo 'You selected Service1'
} else {
echo 'You selected Some other service'
}
}
}
}
stage('Stage 2') {
steps {
echo "This is Stage 2"
script {
if (env.SERVICE == 'Service1') {env.SERVICE_ID = 'Service1_ID'}
if (env.SERVICE == 'Service2') {env.SERVICE_ID = 'Service2_ID'}
if (env.SERVICE == 'Service3') {env.SERVICE_ID = 'Service3_ID'}
if (env.SERVICE == 'Service4') {env.SERVICE_ID = 'Service4_ID'}
if (env.SERVICE == 'Service5') {env.SERVICE_ID = 'Service5_ID'}
echo "Service is ${env.SERVICE}"
echo "Service ID is ${env.SERVICE_ID}"
// Here goes some script you want to run
// For example:
// container('docker') {
// sh """
// some bash command with ${env.SERVICE_ID}
// """
// }
}
}
}
stage('Stage 3') {
steps {
echo "This is Stage 3"
}
}
stage ('Stage 4') {
steps {
echo "This is Stage 4"
}
}
}
}
Im readind a shell script file /tmp/cmd_list.sh with groove script and creating a dynamic stage to build.
The content of /tmp/cmd_list.sh is:
ls
pwd
aaaaaa
who
Only "aaaaaa" mut fail to execute (exit code 127).
My problem is, all stages are marked as failed, but when i see the log, comands such as "ls", "pwd" and "who" work fine fine and return code is 0.
I tried to foce stage status for box, but without sucess ...
My Groove script (Jenkinsfile):
import hudson.model.Result
node('master') {
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
def status;
try {
node{
stage(CMDRUN) {
println "Building ..."
status = sh(returnStatus: true, script: CMDRUN )
println "---> EX CODE: "+ status
if(status == 0){
currentBuild.result = 'SUCCESS'
currentBuild.rawBuild.#result = hudson.model.Result.SUCCESS
}
else{
currentBuild.result = 'UNSTABLE'
currentBuild.rawBuild.#result = hudson.model.Result.UNSTABLE
}
def e2e = build job:CMDRUN, propagate: false
}
}
}
catch (e) {
println "===> " + e
currentBuild.result = 'UNSTABLE'
println "++++> EX CODE: "+ status
if(status == 0){
println "++++> NEW STATUS: "+ status
currentBuild.rawBuild.#result = hudson.model.Result.SUCCESS
currentBuild.result = 'SUCCESS'
}
else{
println "++++> NEW STATUS: "+ status
currentBuild.rawBuild.#result = hudson.model.Result.UNSTABLE
}
}
}
}
And the result is:
Anyone can help me to show right status?
Thank you!
I changed my script and now work as expected!
new code:
node('master') {
def build_ok = true
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
try {
stage(CMDRUN) {
println "Building ..."
sh CMDRUN
}
}
catch (e) { build_ok = false }
}
if(build_ok) { currentBuild.result = "SUCCESS" }
else { currentBuild.result = "FAILURE" }
}
expected Result
Small improvement on waldir's answer
node('master') {
def build_ok = true
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
stage(CMDRUN) {
println "Building ..."
sh CMDRUN
}
}
}
if(build_ok) { currentBuild.result = "SUCCESS" }
else { currentBuild.result = "FAILURE" }
}