Hossein Fallah
Hossein Fallah

Reputation: 2609

Is it possible to use GitHub secrets inside my shell file?

This is my simple Action on my GitHub repo:

name: CI

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Get /my_account/my_infra
        run: |
          sudo mkdir /my_account
          sudo chmod -R 777 /my_account
          cd /my_account
          git clone https://github.com/my_account/my_infra

      - name: Get /my_account/my_repo
        run: |
          cd /my_account
          git clone https://github.com/my_account/my_repo

      - name: Run my build script
        run: |
          cd /my_account/my_infra
          ./build.sh /my_account/my_repo

Since GitHub does not provide a way to reuse actions across multiple similar repos, I came up with the idea of creating a base repo, then download that base alongside the current repo, then run a custom shell script from that base repo, passing my current repo as a parameter.

This works perfect. This way I can reuse my base repo across many similar repositories. And I can reuse near 500 lines of build script instead of repeating myself for 50 repositors (which means 25000 lines of CI/CD code).

However, now I need to access some resources (like login into my docker hub account) to pull and push stuff.

Is it possible to use GitHub secrects in my build.sh?

Upvotes: 14

Views: 12315

Answers (2)

Berimbolinho
Berimbolinho

Reputation: 566

When you set env in your workflow, doc here, they are set as environment variables in your containerised workflow.

This means that if you set a secret in your repository, can be found under settings=> secrets and then assign it to an env in your workflow, they can then be accessed in your build.sh

example:

name: CI

on:
  push:
    branches: [ main ]

env:
  super_secret: ${{ secrets.my_secret }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Get /my_account/my_infra
        run: |
          sudo mkdir /my_account
          sudo chmod -R 777 /my_account
          cd /my_account
          git clone https://github.com/my_account/my_infra

      - name: Get /my_account/my_repo
        run: |
          cd /my_account
          git clone https://github.com/my_account/my_repo

      - name: Run my build script
        run: |
          cd /my_account/my_infra
          ./build.sh /my_account/my_repo

In this case your build.sh can do something like:

#!/bin/bash

npm run build $super_secret

Upvotes: 13

kofemann
kofemann

Reputation: 4423

Yes, you just need to assign them to a variable, like

env:
      ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
run: build.sh

Then you can refer to ACCESS_TOKEN variable in the shell script.

Upvotes: 3

Related Questions