How to replace slashes in the branch name
Git branches uses names like feature/new-feature, the slash is incompatible with docker image tags so i want to use a regex (or other means) to replace the slash in the $BRANCH_NAME with an underscore. This is possible in bash using the following:
BRANCH_NAME=feature/test echo ${BRANCH_NAME/\//_}
is there any way to create an env variable with the branch name escaped in cloudbuild.yaml?
It looks like this is a possible solution
steps:
- id: test
name: "gcr.io/cloud-builders/docker"
entrypoint: "bash"
args:
- "-exc"
- |
echo ${BRANCH_NAME//\//_}
env:
- "BRANCH_NAME=feature/test"
output:
+ echo feature_test
feature_test
I wonder if anyone knows a better way?
Hi @timini, did you ever find an elegant solution for this problem?
In case anyone is still looking for this, here is a complete example:
steps:
- name: "gcr.io/cloud-builders/docker"
entrypoint: "bash"
args: [ "-c", "_TMP_VAR=`echo $BRANCH_NAME | sed -r 's,/,-,g'`; docker build -t gcr.io/$PROJECT_ID/$REPO_NAME:$_NEW_BRANCH_NAME ."]
substitutions:
_NEW_BRANCH_NAME: $_TMP_VAR
images:
- "gcr.io/$PROJECT_ID/$REPO_NAME"
Hi @jachinte do your answer still works ? I try this but $_NEW_BRANCH_NAME is empty
steps:
- name: "gcr.io/cloud-builders/docker"
entrypoint: "bash"
args: [ "-c", "_TMP_VAR =`echo $BRANCH_NAME | sed -r 's,/,-,g'`; echo '1'; echo $_NEW_BRANCH_NAME; echo '2'; docker build -t gcr.io/$PROJECT_ID/$REPO_NAME:$_NEW_BRANCH_NAME ."]
substitutions:
_NEW_BRANCH_NAME: $_TMP_VAR
I got this logs
1
2
And an error for the build. Do you have any idea ?
@groudjulien I'm not using Cloud Build anymore, so I don't know if it still works. However, the documentation on substitutions seems to be the same on that topic.
Are you triggering the build manually? In that case, you have to specify BRANCH_NAME manually. Have you tried echo $BRANCH_NAME?
No I don't trigger it manually. It's triggering on push. $BRANCH_NAME works fine and display the name of the branch. Thanks for your help, i will continue to search :)
@groudjulien I think the problem is the name of your variable. You're defining _BRANCH_FINAL_NAME in your substitutions but then you use _NEW_BRANCH_NAME.
It's an error of copy/paste in gitHub but in my file, the variable have the good name. (I do the correction in my post)
I am also encountering the same problem that @groudjulien wrote.
With the same Cloud Build settings, the job executed on April 12 was succeed, but the job executed on May 9 was failed.
So during that period, I suspect that there has been some change in the behavior of "substituations" keyword.
@mppk, if you are still running into the same problem, you can use bash style string replacement. There is no need to invoke bash.
substitutions:
_NEW_BRANCH_NAME: ${BRANCH_NAME//\//-}