4

I created my first pipeline yesterday and I wanted to replace a placeholder in my bundle.gradle file with the CIRCLE_BUILD_NUM environment variable. The only method I found find was writing my own ‘sed’ command and executing the regex in a run statement. This worked fine to get up and running, since there was only one variable to replace, however this method obviously won’t scale, down the road. Is there a CircleCI feature/orb or other method to do a more comprehensive placeholder/envar swap throughout my project?

- run:
    name: Increment build id
    command: sed "s/_buildNum/${CIRCLE_BUILD_NUM}/g" -i build.gradle

EDIT

Looking for a utility/tools/orb/CircleCI best practice similar to what they have in Azure DevOps (Jenkins performs a similar feature as well): simply replace all placeholders in specified files with environment variables matching the same name.

https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens

NealR
  • 10,189
  • 61
  • 159
  • 299
  • For single files, envsubst does the job well. Not very convenient for the whole project though. – taleodor Jun 22 '20 at 16:26
  • @taleodor that's what I'm currently using inside of a bash script. I'd like to know what CircleCI considers best practice for this type of operation though. – NealR Jun 22 '20 at 17:00

2 Answers2

2

There is envtpl tool with myriad of implementation in various languages. It allows for interpolating variables in templates with values set in environment variables.

The following described command installs an implementation in Rust.

commands:
  replace-vars-from-env:
    description: Replace variables in file from environment variables.
    parameters:
       filename:
         type: string
    steps:
      - run:
         name: Replace variables in build.gradle file
    command: |
      if ! [ -x /usr/local/bin/envtpl ]; then
        curl -L https://github.com/niquola/envtpl/releases/download/0.0.3/envtpl.linux > /usr/local/bin/envtpl
        chmod +x /usr/local/bin/envtpl
      fi
      mv <<parameters.filename>> <<parameters.filename>>.tpl 
      cat <<parameters.filename>>.tpl | envtpl > <<parameters.filename>>
      rm <<parameters.filename>>

and use that in other commands or as a part of your jobs. For example,

executors:
  linux:
    machine:
      image: ubuntu-1604:201903-01

jobs:
  build:
    executor: linux
    steps:
      - replace-vars-from-env:
          filename: build.gradle    
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
2

You could use envsubst which provides that basically out of the box.

Depending on your primary container you can install envsubst on top of alpine/your distro, or use some image that has that already, like datasailors/envsubst.

In that case, you would just need to run configure like:

- run:
    name: Increment build id
    command: envsubst < build.gradle.template > build.gradle

And in your template file you can have ${CIRCLE_BUILD_NUM}, as many other variables directly.