How to pass "Json string" from groovy variable to shell variable with in the groovy function - shell

I am trying to create shared libs for jenkins to build the app. When I am trying to pass the the json string from groovy function to shell block for build command execution. whereas json string passing without quotes. How to retain the quotes.
stage('build app') {
steps {
script {
build project:"TestApp.xcodeproj",
workspace: "TestApp.xcworkspace",
scheme: "Develop",
config: "Debug",
target: "{ "TestApp": { "info_plist": "TestApp/Info.plist", "profile_name": "Test App Debug (January 2021)", "app_id": "com.******.Debug" } }"
}
}
}
def build(Map buildParams) {
sh """#!/bin/bash -l
export XCODE_PROJ="${buildParams.project}"
export XCODE_WORKSPACE="${buildParams.workspace}"
export XCODE_BUILD_SCHEME="${buildParams.scheme}"
export XCODE_BUILD_CONFIGURATION="${buildParams.config}"
export XCODE_TARGET_JSON="${buildParams.target}"
#build App
fastlane build app
"""
}
Expecting the json string as it is in shell block with "Quotes". Whereas getting error expecting '}' found :. When i escape the quotes of json strings, getting, values without "quotes"
{ TestApp: { info_plist: TestApp/Info.plist, profile_name: Test App Debug (January 2021), app_id: com.******.Debug } }
which results fastlane throwing error invalid token. How to retain the quotes in shell block variable

Escaping the quotes in json string with backslash() is worked for me.
'{ "TestApp": { "info_plist": "TestApp/Info.plist", "profile_name": "Test App Debug (January 2021)", "app_id": "com.******.Debug" } }'

Related

Pass a value to a shell script from jenkins pipeline

How to pass values to a shell script from jenkins during the runtime of the pipeline job.
I have a shell script and want to pass the values dynamically.
#!/usr/bin/env bash
....
/some code
....
export USER="" // <--- want to pass this value from pipeline
export password="" //<---possibly as a secret
The jenkins pipeline executes the above shell script
node('abc'){
stage('build'){
sh "cd .."
sh "./script.sh"
}
}
You can do something like the following:
pipeline {
agent any
environment {
USER_PASS_CREDS = credentials('user-pass')
}
stages {
stage('build') {
steps {
sh "cd .."
sh('./script.sh ${USER_PASS_CREDS_USR} ${USER_PASS_CREDS_PSW}')
}
}
}
}
The credentials is from using the Credentials API and Credentials plugin. Your other option is Credentials Binding plugin where it allows you to include credentials as part of a build step:
stage('build with creds') {
steps {
withCredentials([usernamePassword(credentialsId: 'user-pass', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// available as an env variable, but will be masked if you try to print it out any which way
// note: single quotes prevent Groovy interpolation; expansion is by Bourne Shell, which is what you want
sh 'echo $PASSWORD'
// also available as a Groovy variable
echo USERNAME
// or inside double quotes for string interpolation
echo "username is $USERNAME"
sh('./script.sh $USERNAME $PASSWORD')
}
}
}
Hopefully this helps.

Assigning values to Jenkins environment variables is not working

I declared the environment variables in pipeline syntax and I'm trying to assign values to the variables by reading the file from workspace. Assigned values are not reflected in environment variable. my configuration looks like below
pipeline {
agent any
environment {
test = ''
}
stages {
stage('Test') {
script {
writeFile(file: 'hello.txt', text: "hello world")
env.test = readFile(file: 'hello.txt')
echo 'test:'"${env.test}" // coming as null
}
}
}
}
}
Try to remove test from environment block.
Also, you have a problem with '' and "" when you display env.test, try to do this:
echo "test: ${env.test}" // coming as null

Using Function in JenkinsFile Parameter Description

I am trying to add a function in JenkinsFile Declarative pipelines parameter's description but struggling to make it work.
Idea is to have a Jenkins Job specific for the environment. and would like to see the choice parameter to show environment name in the description of the variable.
My pipeline looks like this
def check_env = app_env(ENVS, env.JOB_NAME)
pipeline {
agent { label 'master' }
options {
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
}
parameters{
string(name: 'myVariable', defaultValue: "/", description: 'Enter Path To App e.g / OR /dummy_path for ' {check_env} )
}
stages{
stage('Running App') {
agent {
docker {
image 'myApp:latest'
}
}
steps{
script{
sh label: 'App', script: "echo "App is running in ${check_env} "
}
}
}
}
}
}
I have tried multiple combinations for check_env e.g check_env, check_env(), ${check_env} function but none of them worked.
String Interpolation
I believe this is simply a String Interpolation issue. Notice my use of double quotes below
parameters{
string(name: 'myVariable', defaultValue: "/", description: "Enter Path To App e.g / OR /dummy_path for ${check_env}")
}
Your build page should then interpolate your variable
To test I simply set def check_env = 'live' since I do not have the code for your method

Jenkins custom pipeline and how to add property to be set in jenkinsfile

I'm trying to create a custom pipeline with groovy but I can't find anywhere on the web where it is discussed how to add a property that can be set in the jenkinsfile. I'm trying to add a curl command but need the URL to be set in the jenkinsfile because it will be different for each build.
Can anyone explain how that should be done or links where it has been discussed?
Example Jenkinsfile:
msBuildPipelinePlugin
{
curl_url = "http://webhook.url.com"
}
custom pipeline groovy code:
def response = sh(script: 'curl -i -X POST -H 'Content-Type: application/json' -d '{"text","Jenkins Info.\nThis is more text"}' curl_url, returnStdout: true)
Thanks
If you want to specify the URL as a string during every build, you can do either of the following:
Declarative Pipeline
Use the parameters {} directive:
pipeline {
agent {
label 'rhel-7'
}
parameters {
string(
name: 'CURL_URL',
defaultValue: 'http://www.google.com',
description: 'Enter the URL for file download'
)
}
stages {
stage('download-file') {
steps {
echo "The URL is ${params.CURL_URL}"
}
}
}
}
Scripted Pipeline
Use the properties([parameters([...])]) step:
parameters([
string(
name: 'CURL_URL',
defaultValue: 'http://www.google.com',
description: 'Enter the URL for file download'
)
])
node('rhel-7') {
stage('download-file') {
echo "The URL is ${params.CURL_URL}"
}
}
You can choose to leave the values of defaultValue and description empty.
Job GUI
Either of the above syntax will be rendered in the GUI as:
I got it to work using
//response is just the output of the curl statement
def response = ["curl", "-i", "-v", "-X", "POST", "--data-urlencode", "payload={\"text\":\"message body\"}", "curl url goes here"].execute().text
Thanks

Protractor passing parameters in script run command

I need to pass the credentials in command running a script.
For now, I am using in protractor file following part:
onPrepare: function () {
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: true
}
}));
if (browser.params.Url == 'http://devel/') {
browser.params.webmaster='abc';
browser.params.webmaspass='foo';
}
//(other environments)
else {
console.log('-------------error during log in');
}*/
}
and it was working fine, but I need to change it - I can't pass credentials in this way. I thought about changing it to:
if (browser.params.Url == 'http://devel/') {
browser.params.webmaster='';
browser.params.webmaspass='';
}
and run the script using
npm run dev-script --browser.params.Url='http://devel/' --browser.params.webmaster='abc' --browser.params.webmaspass='foo'
where package.json I have:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev-script": "protractor --params.Url=http://devel/ --browser.params.webmaster='' --browser.params.webmaspass=''"
},
(or any variation) But it fails - I can't update params during running script, I need to write down the credentials in the code (which I find a little unsafe)
I found issues like Protractor needs password for login => insecure? but it about Google Auth problems
Any idea?
You need to remove the variable assignment in the onPrepare. You are overwriting what you are passing in from the command line by setting it to an empty string.
When you pass them in from the command line they will be availble on the params object. There is no need to set them again in your onPrepare. Add a console.log() in your onPrepare and you will see.
Run it from the command line like this: protractor conf.js --params.webmaster=abc --params.webmaspass=foo --params.url=http://devel/
Again, if you log them in your onPrepare you will see that it is working. The way you currently have it you are just overwriting the values you are passing in through the command line.
onPrepare: function () {
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: true
}
}));
if (browser.params.Url == 'http://devel/') {
consoel.log(browser.params.webmaster) //should be abc
console.log(browser.params.webmaspass) //should be foo
}
//(other environments)
else {
console.log('-------------error during log in');
}*/
}
Another way you can do this is to set some environment variables before your test run and then you can access them in your scripts by using process.env.envVariableName or ${envVariableName}. Both ways will work.
set DEVEL_WEBMASTER=abc
set DEVEL_WEBMASPASS=foo
onPrepare: function () {
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: true
}
}));
if (browser.params.Url == 'http://devel/') {
browser.params.webmaster=process.env.DEVEL_WEBMASTER;
browser.params.webmaspass=process.env.DEVEL_WEBMASPASS;
}
//(other environments)
else {
console.log('-------------error during log in');
}*/
}
Just remember that if you use this method you would have to set the variables for each session. If you are planning to automate these tests using a CI environment you can just add them there as secret variables (if you have that option) and they will always be there ready and waiting. There will be no need to set them manually during each build.
What I did it here was create the scripts in my package.json:
scripts: {
"automation-test": "concurrently --raw --kill-others \"./node_modules/.bin/webdriver-manager start\" \"sleep 5 && ./node_modules/.bin/protractor configuration/protractor.config.js\"",
"automation:pending": "TAGS=#pending npm run automation-test"
}
And in my protractor.conf.js I just assign the value to a variable so I can use in my config. Like this:
let tags = process.env.TAGS;
Then the command that I run is just this:
npm run automation:pending
but I could pass the TAGS like this as well:
npm run automation-test TAGS=#pending
I have not seen the configuration file on the parameters of the command line. you must specify the configuration file:
example: protractor config.js --params ......
Do this in your script file: i have added a config file after the command protractor
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev-script": "protractor config.js --params.Url=http://devel/ --browser.params.webmaster='' --browser.params.webmaspass=''"
},

Resources