Search code examples
jenkinsjenkins-pipelineshterraform

Evaluate variable in Jenkinsfile - single quotes within single quotes


I am executing the following in a Jenkinsfile:

sh('''
   terraform apply 'var some_list=["foo","bar"]'
   ''')

Now, I would like to place ["foo","bar"] in a variable and feed that to terraform instead, so I do:

sh('''
   export MYVAR=["foo","bar"]
   terraform apply 'var some_list=${MYVAR}'
   ''')

This however, does not work. ${MYVAR} is interpreted as a literal string instead of evaluating it as a variable.

I could do this:

sh('''
   export MYVAR=["foo","bar"]
   terraform apply var some_list=${MYVAR}
   ''')

In this case, ${MYVAR} is correctly intepreted, but then Terraform has trouble interpreting the parameter as a list, so the single quotes are needed.

One could perhaps use double quotes in stead , i.e. sh("""...""") and use Groovy evaluation, but I have several other variables where exactly the opposite problem happens. What I am really looking for is a way to use single quotes within single quotes and have the variable still be evaluated.

Does anyone know how I could achieve this?

EDIT:

By the way terraform apply 'var some_list=${MYVAR}', terraform apply 'var some_list=\${MYVAR}' and terraform apply \'var some_list=${MYVAR}\' all give the exact same result.


Solution

  • So, after more trial and error, I finally found that this will work:

    sh('''
       export MYVAR=["foo","bar"]
       terraform apply 'var some_list='${MYVAR}''
       ''')
    

    i.e. I have to close the inner single quotes before ${MYVAR} and open them again directly thereafter