3

I am setting up a pipeline to run Cypress automated tests using github actions/workflows on my code anytime there is a push to the repo. I came into a scenario where I want to generate dyanmic .env files depending on the branch , so instead of hard coding variables i created a base64 string and saved that as an secret and accessed that secret inside the code, however when i try to decode i run into issues, let me show you my code

ci.yml

name: Nuxt CI Pipeline
    on:
      push:
        branches: [ Cypress-reconfigure ]
      # pull_request:
      #   branches: [ master ]

jobs: build:

runs-on: ubuntu-latest

strategy:
  matrix:
    node-version: [ 14.x ]
    # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
  uses: actions/setup-node@v2
  with:
    node-version: ${{ matrix.node-version }}
    cache: 'npm'
- name: Generating .env files
  env:
    STAGING_ENV_FILE: ${{ secrets.STAGING_ENV_FILE }}
    PRODUCTION_ENV_FILE: ${{ secrets.PRODUCTION_ENV_FILE }}
  run: |
    [ "$GITHUB_REF_NAME" = Cypress-reconfigure ] && echo $STAGING_ENV_FILE | base64 --decode > .env
    [ "$GITHUB_REF_NAME" = staging ] && echo $PRODUCTION_ENV_FILE | base64 --decode > .env
- run: cat .env 
- run: npm ci
- run: npm run cy:ci

Screenshot

Pipeline error

I followed this answer which was best suited for my scenario Stack Overflow post

As you can see, the error doesnt say anything it just exists! I have very limited knowledge of Devops can someone help me out with what I am doing wrong?

uneeb meer
  • 153
  • 1
  • 4

1 Answers1

2

This is guaranteed to always fail:

      run: |
        [ "$GITHUB_REF_NAME" = Cypress-reconfigure ] && echo $STAGING_ENV_FILE | base64 --decode > .env
        [ "$GITHUB_REF_NAME" = staging ] && echo $PRODUCTION_ENV_FILE | base64 --decode > .env

Why? Depending on the value of $GITHUB_REF_NAME only one of the lines will run. But the other line will return a non-zero return code:

$ [ "a" = "b" ] && true

$ echo $? 1

And GHA is configured to abort on the first command that doesn't return a zero exit code (that's the successful exit code).

To fix, you should use an if-then, rather than the shell one-liner:

      run: |
        if [ "$GITHUB_REF_NAME" = Cypress-reconfigure ]; then echo $STAGING_ENV_FILE | base64 --decode > .env; fi
        if [ "$GITHUB_REF_NAME" = staging ]; then echo $PRODUCTION_ENV_FILE | base64 --decode > .env; fi

Note that I didn't include a different workaround in the shell command of ignoring errors with a || true:

[ "$GITHUB_REF_NAME" = Cypress-reconfigure ] && echo $STAGING_ENV_FILE | base64 --decode > .env || true

because it results in false positives if the command (e.g. base64 --decode) fails.

BMitch
  • 3,568
  • 12
  • 18