arielma
arielma

Reputation: 1398

How to set pipeline variable for list of dictionaries and pass it to groovy

I have the below pipeline code:

stage ("distribution"){
    steps{
        script{
            def rules = [
                [
                    "service_name": "core", 
                    "site_name": "*", 
                    "city_name": "*", 
                    "country_codes": ["*"]
                ]
            ]
            amd_distribution_distribute_bundle distribution_rules: rules
        }
    }
}

In the amd_distribution_distribute_bundle.groovy file I'm trying to print the value of it:

def call(Map parameters) {
    def DISTRIBUTION_RULES= parameters.distribution_rules
    sh '''
        echo ${DISTRIBUTION_RULES}
     '''
}

I'm getting in the console an empty string for it. Do you any idea what's missing?

Upvotes: 1

Views: 3686

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You are using single quotes that do not interpolate ${DISTRIBUTION_RULES} variable from the local variable. If you want to use it with sh step (execute as a shell script) you need to use double quotes to interpolate the value from the local variable.

def call(Map parameters) {
    def DISTRIBUTION_RULES = parameters.distribution_rules
    sh """
        echo ${DISTRIBUTION_RULES}
    """
}

Alternatively, if you want to use single quotes but still access the DISTRIBUTION_RULES value, you would need to assign it to the environment variable. Keep in mind, however, that environment variable casts every value assigned to String. So if you try to assign a map to a env variable, you will get its string representation, not the real map. A shell script has access to all environment variables set in the pipeline.

def call(Map parameters) {
    env.DISTRIBUTION_RULES = parameters.distribution_rules
    sh '''
        echo ${DISTRIBUTION_RULES}
    '''
}

Upvotes: 1

Related Questions