Kay
Kay

Reputation: 19670

How to replace a variable in yml file with a gitlab ci pipeline variable using sed

I want to replace a variable in my .yml file with a variable from the gitlab ci pipeline.

gitlab-ci.yml

deploy_test:
  stage: deploy
  script:
    - sed -i 's/$TAG/$CI_COMMIT_REF_NAME/g' deploy/test.yml
    - kubectl apply -f deploy/test.yml
  when: manual
  only:
    - master
    - tags

This says within the deploy/test.yml file it should replace $TAG with the value of $CI_COMMIT_REF_NAME?

deploy/test.yml

image: git.<removed>.com:5005/eng/my-group/my-image:$TAG

Upvotes: 12

Views: 33938

Answers (3)

allkenang
allkenang

Reputation: 1645

Use double quotes(") instead of single quotes (') in sed and also take note that forward slashes (/) need to be escaped too (like \/).

so given the following (assuming you are using docker hub)

$CI_COMMIT_REF_NAME=docker_user/repo:v1

You will firstly need to escape the '/' character first, like so

$CI_COMMIT_REF_NAME=docker_user\/repo:v1

Then finally use double quotes in the sed command

sed -i "s/$TAG/$CI_COMMIT_REF_NAME/g" deploy/test.yml

Note: In addition to this you can also prefer using | instead of / if there's too many escapes.

Like:

sed -i "s|$TAG|$CI_COMMIT_REF_NAME|g" deploy/test.yml

Upvotes: 11

Mahmoud Triki
Mahmoud Triki

Reputation: 1

- sed -i "s|TAG|${CI_COMMIT_REF_NAME}|g" deploy/test.yml

and for simpler situation remove the $ from $TAG, so the deploy/test.yml:

image: git.<removed>.com:5005/eng/my-group/my-image:TAG

Upvotes: 0

Dishant Pandya
Dishant Pandya

Reputation: 13

If your string consists of / , as a workaroud you can use different delimiting character instead of / for example,

sed -i -E "s%BASE_URL: '.*'%BASE_URL: '\$BACKEND_URL'%g" $FRONTEND_PATH/app/config/index.js

Here I am using % as delimiting character as none of my strings has that character, you can use any other depending on the symbols used in your strings.

Upvotes: 0

Related Questions