ticktockhouse
ticktockhouse

Reputation: 599

Jenkins Parameterised Job with Terraform map variable

I'm trying to feed user-defined parameters from Jenkins into a job which runs terraform. I have a set of simple key/value vars, which I'm passing into the Terraform like this:

sh "terraform plan -var 'var1=${params.Var1}' -var 'var2=${params.Var2}' ...." 

However, I also have a map var:

tags = {
  Cluster     = "mycluster"
  Environment = "myenv"
  Owner       = "owner"
  Product     = "myproduct"
}

and I would like to feed some String Parameters into this map var. It looks like I need to define a groovy map and then render the map as JSON, so that I can have e.g. terraform -var 'tags={"Cluster":"mycluster","Environment":"dev"...}

My job is currently of the form:

pipeline {

    agent {
    ...
    }

    options {
    ...
    }

    environment {
    ...
    }
    stages {

        stage('MyStage') {
            steps {
              script {
                sh "terraform ..."
              }
            }
        }
    }
}

I'me very new to Jenkinsfiles, so where would I define a map, if that's what was needed..?

Upvotes: 1

Views: 1355

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28739

Your attempt in the question is close, but Maps in Groovy are constructed with [:]. Therefore, you can construct a Jenkins Pipeline Map type output in JSON to be passed to a Terraform Map type like the following:

terraform -var "tags=${JsonOutput.toJson(['Cluster':'mycluster', 'Environment':'dev'...])}"

Given your use of the sh step method above, you will also need to escape your quotes to properly cast your strings appropriately as well.

Upvotes: 1

Related Questions