1

From this answer I learned, how to set the variable B to 1 if the env.BRANCH_NAME is 'f1', otherwise set it to 2.

name: ****

on:
  push:

env:
  BRANCH_NAME: ${{ github.head_ref || github.ref_name }}

jobs:
  job1:
    name: *****
    runs-on: *****

    steps:
      - name: *****
        uses: some-action@some-version
        with:
          A: 1
          B: ${{ env.BRANCH_NAME == 'f1' && 1 || 2 }}  # <-- I need a change here

I want to change the condition such that the variable is set to 1 if env.BRANCH_NAME is either of 'f1' or 'f2', otherwise it is set to 2.

In Python, I would do env.BRANCH in ['f1', 'f2'].

How should it be done here?

Azeem
  • 11,148
  • 4
  • 27
  • 40
Amin Ba
  • 1,603
  • 1
  • 13
  • 38
  • See [`contains`](https://docs.github.com/en/actions/learn-github-actions/expressions#contains) function. – Azeem Apr 20 '23 at 17:42
  • 1
    Example: `B: ${{ contains(fromJSON('["f1", "f2"]'), env.BRANCH_NAME) && 1 || 2 }}` – Azeem Apr 20 '23 at 17:43
  • what if I wanted to do `if env.BRANCH_NAME is f1 then B is 1, if f2 then B is 2, else B is 3 ` how would I do this? – Amin Ba Apr 20 '23 at 17:52
  • For that, you can use logical grouping with`()` [operator](https://docs.github.com/en/actions/learn-github-actions/expressions#operators) and create complex expressions. – Azeem Apr 21 '23 at 06:08

1 Answers1

1

You can use the contains function along with fromJSON like this:

B: ${{ contains(fromJSON('["f1", "f2"]'), env.BRANCH_NAME) && 1 || 2 }}
Azeem
  • 11,148
  • 4
  • 27
  • 40
  • seems like it does not work if I need `B: ${{ contains(fromJSON('["f1", "f2"]'), env.BRANCH_NAME) && '' || 2 }}`. right? – Amin Ba May 12 '23 at 20:49
  • @AminBa: Why not? Any error/issue? See a similar example here: https://github.com/iamazeem/security-headers-action/blob/8254020bbb97a8e1b7bf4e6fc7e1e0a35739508d/action.yml#L61 – Azeem May 13 '23 at 06:26
  • I dont know. in both cases it is returning `2`. your example is different. your example first is `2` then `''`. decided to use instead `${{ fromJSON('[2, ""]')[contains(fromJson('["f1", "f2"]'), env.BRANCH_NAME)] }}` – Amin Ba May 13 '23 at 11:15
  • @AminBa: I have used it in reverse order too. Never had an issue. An [MCVE](https://meta.stackoverflow.com/questions/366988/what-does-mcve-mean) would be helpful to identify the exact issue in a new question. – Azeem May 13 '23 at 12:06
  • will work on MVCE (nice abbreviation I just learned) and will share – Amin Ba May 13 '23 at 12:19