Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkinsfile: error with adding variables to shell commands


This piece of code that I have is failing,

groovy_parameters ="""${params.is_destroy == true ? ' -destroy': ''} \
                                    -var 'client=${params.client}' \
                                    -var 'region=$region' \
                                    -var 'cluster=${params.cluster}' \
                                    -var 'vpc_name=${params.vpc}' \
                                    -var 'app_name=$app_name' \
                                    -var 'consul_url=${env.CONSUL_URL}' \
                                    -var 'kv_path=$consul_path' 
                                    """
                                    
                        
sh "${terraformBinaryName} import ${groovy_parameters} module.resources.aws_s3_bucket.antivirus_bucket[\"definitions\"] < bucket_name >"

with the jenkins executing:

terraform1-29 import -var client=*** -var region=ap-southeast-2 -var cluster=*** -var vpc_name=*** -var app_name=*** -var consul_url=*** -var kv_path=***

So, it's adding all the groovy_params variable to the shell command but it's not adding the parts after it.

Which is why I get this terraform import error:

The import command expects two arguments.

Any help on fixing this would be appreciated!

Edit: adding screenshot from Jenkins: enter image description here


Solution

  • There is an extra newline character in the end of the groovy_parameters variable. This newline character splits the command so that sh step thinks that parameters after groovy_parameters are a new separate command. The separate command is not visible in console output because Jenkins by default uses -xe shell flags in sh steps and thus stops executing commands on first failing command.

    Either add \ to the last row of the multi-line string or end the multi-line string before the last new line character:

    groovy_parameters ="""${params.is_destroy == true ? ' -destroy': ''} \
        -var 'client=${params.client}' \
        -var 'region=$region' \
        -var 'cluster=${params.cluster}' \
        -var 'vpc_name=${params.vpc}' \
        -var 'app_name=$app_name' \
        -var 'consul_url=${env.CONSUL_URL}' \
        -var 'kv_path=$consul_path'"""