How to call variables in shell for declarative pipeline?

pipeline {
    agent {
        label "kubeagent"
    }
    parameters {
        choice(name: 'ENVIRONMENT', choices: ['Dev', 'Test', 'Preprod', 'Prod'], description: 'Select Environment')
        choice(name: 'SERVICE', choices: ['admin-portal', 'shop', 'analytics', 'profile'], description: 'Select Service')
    }
    environment {
        SHOP_CONFIGMAP_DEV = credentials('SHOP-SECRET-DEV')
    }
    stages {
        stage("Copy Env File") {
            when {
                anyOf {
                    equals expected: 'shop', actual: "${SERVICE}"
                }
            }
            steps {
                script {
                    if(params.SERVICE == 'shop'){
                        if(params.ENVIRONMENT == 'Dev'){
                           def configFile = "${params.SERVICE.toUpperCase()}_CONFIGMAP_${params.ENVIRONMENT.toUpperCase()}"
			               echo "ConfigFile Name: ${configFile}"
                           sh '''
                           echo "${configFile}"
                           cp  env."$configFile" "$WORKSPACE/secret.yaml"
                           echo File Copied Successfully
                           '''
                        } else {
                            echo "Invalid Env"
                        }
                    } 
                }
            }
        }
    }
}

Hey all,

So the issue I’m having is calling the environment variable into my shell.

What am I trying to achieve?

As you can see there’s multiple environments and services, so I’m trying to get the secret.yaml files copied when the user selects the parameters, without having to use multiple if statements.

What’s not working out?

The echo "${configFile}" which lives inside the shell output is ā€˜ā€™ (blank). However the echo "ConfigFile Name: ${configFile}" which lives outside the shell seems to output the value as expected which is ā€œSHOP_CONFIGMAP_DEVā€.

Now SHOP_CONFIGMAP_DEV is a credential in Jenkins which is of type secret file. And I’m trying to copy this to my $WORKSPACE path.

Syntaxes I’ve tried so far.

  • cp env.ā€œ$configFileā€
  • cp ā€œ${configFile}ā€
  • cp ā€œ${env[configFile]}ā€

None of these seem to seemed to work and I was wondering if there’s a way to get the variable set and then copy the file associated to that variable into my Job workspace.

You’re using triple single quotes, which disables groovy string interpolation.
When you use triple double quotes it will work

sh """
echo "${configFile}"
"""
1 Like

Wow :man_facepalming:

I did not expect that. I was on this for some time. Thanks a million ā€œmawinter69ā€ :sweat_smile:

The final syntax I used to copy the file was.

sh """
cp  \${${configFile}} "$WORKSPACE/secret.yaml"
echo File Copied Successfully
"""