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}")
}
}
}
}
}
}
Related
I am trying to use the credentials parameter for a git clone. But i am getting the error that the variables are not found
Param definition
credentials (credentialType: 'Username with password', defaultValue: 'fcb2d7c3-4b35-4ef2-bdf0-24fc4ff1137c', description: 'Git credential', name: 'git_credential', required: true)
Usage in stage
withCredentials([usernamePassword(credentialsId: params.git_credential, passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
sh 'git reset --hard; git clone https://${DOCKER_USERNAME}:${DOCKER_PASSWORD}#repo_url/scm/${params.repository}.git --branch master'
Error: Wrong variable used
This works for me:
pipeline {
agent any
parameters {
// credentials : defaultValue is Credentials ID
credentials(name: 'git_credential', description: 'Git credential', defaultValue: 'fcb2d7c3-4b35-4ef2-bdf0-24fc4ff1137c', credentialType: "Username with password", required: true )
}
stages {
stage('Print') {
steps {
withCredentials([usernamePassword(
credentialsId: '${git_credential}',
usernameVariable: 'DOCKER_USERNAME',
passwordVariable: 'DOCKER_PASSWORD',
)]) {
sh """
echo id:${DOCKER_USERNAME} pw:${DOCKER_PASSWORD}
"""
}
}
}
}
}
In my pipeline I have this:
steps {
script
{
def TAG_NAME = env.GIT_BRANCH.split("/")[1]
}
sshagent(credentials: ["<snip>"]) {
sh """
git tag -a "v.${TAG_NAME}.${env.BUILD_NUMBER}" -m "Add tag"
git push --tags
"""
}
}
But when this runs, I see that TAG_NAME is 'null.'
How do I make it so that I can see it in the sshagent.
A declarative pipeline example to set and get variables across the stages in a different ways .
def x
pipeline {
agent any;
stages {
stage('stage01') {
steps {
script {
x = 10
}
}
}
stage('stage02') {
steps {
sh "echo $x"
echo "${x}"
script {
println x
}
}
}
}
}
on your example, it could be
def TAG_NAME
pipeline {
agent any;
stages {
stage('stageName') {
steps {
script {
TAG_NAME = env.GIT_BRANCH.split("/")[1]
}
sshagent(credentials: ["<snip>"]) {
sh """
git tag -a "v.${TAG_NAME}.${env.BUILD_NUMBER}" -m "Add tag"
git push --tags
"""
}
}
}
}
}
How can I populate choice parameter from the URL?
I'm able to download and save values inside environment variable but if I try to use it I get error:
if I replace choicesFoo with choicesURL in parameters section, I get error.
Here is my pipeline:
def choicesFoo = ['x','y']
pipeline{
agent {
node {
label 'LinuxOpt'
}
}
environment{
choicesUrl = sh(script: "curl http://example.com/foo.txt", returnStdout: true)
}
parameters {
choice(name: 'CHOICE', choices: choicesFoo, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}
You can try preparing your choices before declaring a pipeline, e.g. like this:
def choicesUrl
node('Prepare Choices') {
stage('Get Choices') {
choicesUrl = sh(
script: "curl http://example.com/foo.txt",
returnStdout: true).trim()
}
}
pipeline{
agent { node { label 'LinuxOpt' } }
parameters {
choice(name: 'CHOICE', choices: choicesUrl, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}
I'd like to pass environment variables by publish stage based on the branch that the multi-pipeline job is processing.
While this example below works, I don't like how I'm ending up with additional stages, one per branch. Because I'm using the withCredentials plugin, I need to have the MY_CREDENTIALS variable set before that block. Is there a more elegant approach to solve this?
pipeline {
agent {
dockerfile true
}
stages {
stage("Config vars for staging") {
when {
branch 'staging'
}
environment {
MY_CREDENTIALS = 'creds-staging'
MY_ENVIRONMENT = 'production'
}
steps {
sh "echo MY_ENVIRONMENT: $MY_ENVIRONMENT"
}
}
stage("Config vars for production") {
when {
branch 'master'
}
environment {
MY_CREDENTIALS = 'creds-prod'
MY_ENVIRONMENT = 'staging'
}
steps {
sh "echo MY_ENVIRONMENT: $MY_ENVIRONMENT"
}
}
stage("Publish") {
steps {
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.MY_CREDENTIALS, accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {
sh 'make takecareofit'
}
}
}
}
}
Use switch statement. In example below I forced FAILURE if branch is not master or staging:
pipeline {
agent {
dockerfile true
}
stages {
stage("Config vars") {
steps {
script {
switch(branch) {
case 'staging':
MY_CREDENTIALS = 'creds-staging'
MY_ENVIRONMENT = 'production'
break
case "master":
MY_CREDENTIALS = 'creds-prod'
MY_ENVIRONMENT = 'staging'
break
default:
println("Branch value error: " + branch)
currentBuild.getRawBuild().getExecutor().interrupt(Result.FAILURE)
}
}
}
}
stage("Publish") {
steps {
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.MY_CREDENTIALS, accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {
sh 'make takecareofit'
}
}
}
}
}
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
}