DisplayName
DisplayName

Reputation: 649

Escape sed command in Jenkins bash script

I have a Bash script working fine locally, now I am trying to put it in Jenkinsfile to run as its pipeline:

    stage('Update Cloudfront'){
      steps {
        sh '''
            #!/bin/bash
            YAML_FILE="path/to/values.yaml"
            DATE="$(date '+%d-%m-%Y')"
            wget https://www.cloudflare.com/ips-v4 && wget https://www.cloudflare.com/ips-v6
            CLOUDFLARE_NEW=$(awk '{printf fmt,$1}' fmt="%s\n" ips-v4 ips-v6 | paste -sd, -)
            CLOUDFLARE_OLD=$(yq -r .controller.config.proxy-real-ip-cidr $YAML_FILE | sed -E 's/\,37\.16\.11\.30\/32//')
            if [[ "$CLOUDFLARE_NEW" == "$CLOUDFLARE_OLD" ]]; then
              echo "No need to do anything"
            else
              echo "Cloudflare IP ranges change detected, updating Nginx value file"
              CLOUDFLARE_NEW=$(awk '{printf fmt,$1}' fmt="%s\n" ips-v4 ips-v6 | paste -sd, -) yq e '.controller.config.proxy-real-ip-cidr = env(CLOUDFLARE_NEW)' -i $YAML_FILE
              echo "Add third party IP range"
              yq e '.controller.config.proxy-real-ip-cidr +=",1.2.3.4/32"' -i $YAML_FILE
            fi
        '''
      }
    }//end stage('Update Cloudfront')

Unfortunately it won't work:

WorkflowScript: 73: unexpected char: '\' @ line 73, column 113.
   cidr $YAML_FILE | sed -E \\"s/\,37\.16\.
                                 ^

I've tried to escape it with \\"s/\,37\.16\.11\.30\/32//\\" etc. but it doesn't work either. I've tried with double and single quotes with no luck.

Upvotes: 0

Views: 171

Answers (1)

miken32
miken32

Reputation: 42711

You can avoid all the escaping by using a character class and different regex delimiters, like so:

sed -e 's#,37[.]16[.]11[.]30/32##'

In the event you do need to escape something though, simply doubling the backslash should do it:

sed -e 's/,37\\.16\\.11\\.30\\/32//'

Though, given the number of levels involved here, it might need double escaping:

sed -e 's/,37\\\\.16\\\\.11\\\\.30\\\\/32//'

Upvotes: 2

Related Questions