Replacing string with variable in Jenkinsfile using SED command

Viewed 6445

I have a Jenkinsfile in which I am fetching a value from AWS console ; and storing in a variable my_es_host , and there is a parameter in my terraform.tfvars file i.e. es_host="". I am trying to insert the value of variable my_es_host in the terraform file. Below is the sed command I am using in the Jenkinsfile:

sh 'sed -i "s/es_host=\"\"/es_host=\"$my_es_host\"/g" terraform.tfvars

This is working as expected in Linux terminal. However, this sed command does not work in a Jenkinsfile. Can someone help me on this please ?

2 Answers

I believe that nothing is substituted, because it may not match the pattern. Jenkins itself will consume one quoting backslash, so you need to double them, e.g.:

pipeline {
    agent any
    environment {
        my_es_host = 'whatever'
    }
    stages {
        stage('sed') {
            steps {
                sh 'echo es_host=\\"\\" > terraform.tfvars'
                sh 'cat terraform.tfvars'
                sh 'sed -i "s/es_host=\\"\\"/es_host=\\"$my_es_host\\"/g" terraform.tfvars'
                sh 'cat terraform.tfvars'
            }
        }
    }
}

Output:

[Pipeline] sh
+ echo es_host=""
[Pipeline] sh
+ cat terraform.tfvars
es_host=""
[Pipeline] sh
+ sed -i s/es_host=""/es_host="whatever"/g terraform.tfvars
[Pipeline] sh
+ cat terraform.tfvars
es_host="whatever"

Another way to do that is using HCLQ (command line tool for querying and manipulating HashiCorp HCL) here are some examples

cat terraform.tfvars | hclq set 'es_host' $my_es_host | tee terraform.tfvars  

or you can get this value

cat terraform.tfvars | hclq get 'es_host'
Related