简体   繁体   中英

Github Actions | conditional based on branch name

I am currently looking into github actions for the first time.

I have a process where I build a docker image and publish it to Docker Hub.

This all seems to be working perfectly, however when I push to master it builds and tags with master branch however, I would like this to tag with the latest branch?

I know you can do conditionals in the .yml file inside of the steps such as:

step:
  if: github.ref == 'refs/heads/master'

but I was wondering if I could do it inline so I could essentially say

build . docker-image-name:${{ github.ref == 'refs/head/master' ? 'latest' : github.ref }}

I know this isn't the syntax but that's the idea,

You can do this with a small amount of shell scripting. Assuming that you know the ref will always be set (that is, you're always working with a branch or tag), you can write the following:

build . docker-image-name:$(ref=${GITHUB_REF%refs/heads/master};echo ${ref:=latest})

Or, if you want something less compact, but easier to read:

build . docker-image-name:$([ "$GITHUB_REF" = refs/heads/master ] && echo "latest" || echo "$GITHUB_REF")

The GITHUB_REF environment variable should be set by your action automatically, provided you're working with a ref.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM