Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jenkins pipeline sh adding new line

My pipeline sh block:

 sh "set +e; /terraform/terraform plan -var aws_access_key=${aws_access_key} -
 var aws_secret_key=${aws_secret_key} -var aws_ami=${ami_id} -var 
 aws_instance_type=${instance_type} -var aws_elb_security_group=${elb_sg} -var 
 aws_ec2_security_group=${ec2_sg} -detailed-exitcode; echo \$? > status"
              exitCode = readFile('status').trim()
              echo "Terraform Plan Exit Code: ${exitCode}"

output :

+ set +e
+ /terraform/terraform plan -var aws_access_key=**** -var aws_secret_key=**** -var aws_ami=ami-xxxxxxx
+ -var aws_instance_type=t2.medium -var aws_elb_security_group=sg-xxxx
/terraform/selectdev/int/mp-frontend@tmp/durable-6c57c14c/script.sh: line 3: -var: command not found
+ -var aws_ec2_security_group=sg-axxx
 /terraform/selectdev/int/mp-frontend@tmp/durable-6c57c14c/script.sh: line 4: -var: command not found
+ -detailed-exitcode
/terraform/selectdev/int/mp-frontend@tmp/durable-6c57c14c/script.sh: line 5: 
 -detailed-exitcode: command not found
+ echo 127

I'm not sure why new line is being added to the command and If I do single quotes like sh '', variables are blank. what am I doing wrong ?

I tried to do like below but it too adding new lines

def command = $/....../$
res = sh(returnStdout: true, script: command)
like image 440
user6481062 Avatar asked Feb 05 '18 20:02

user6481062


2 Answers

First, FYI: single quotes skip variable interpolation in groovy

If you want to have a multiple line script in a string, you need to escape endlines in a multi line variable.

You need three things:

  1. Use triple double strings """. This allows you to have multi-line strings with interpolation (triple single quoted strings ''' let you do the same thing without interpolation).
  2. Escape endlines with \. This lets you insert newlines to format a long command.
  3. Wrap variables with double quotes (valid within triple double quotes, but you can also just escape the double quotes otherwise: \")

For example as follows: (one argument per line for readability)

sh("""set +e; /terraform/terraform plan \
-var aws_access_key="${aws_access_key}" \
-var aws_secret_key="${aws_secret_key}" \
-var aws_ami="${ami_id}" \
-var aws_instance_type="${instance_type}" \
-var aws_elb_security_group="${elb_sg}" \
-var aws_ec2_security_group="${ec2_sg}" \
-detailed-exitcode; echo \$? > status""")
like image 51
Florian Castellane Avatar answered Oct 05 '22 06:10

Florian Castellane


The variables I'm using are from other stages and have new line.. had to use .trim()

like image 38
user6481062 Avatar answered Oct 05 '22 07:10

user6481062