DEV Community

Cover image for Reading GitHub secrets from GitHub actions using Golang
Chilarai
Chilarai

Posted on

Reading GitHub secrets from GitHub actions using Golang

Sometimes while doing CI/CD with GitHub Actions, you need to read environment variables stored in GitHub Secrets for your tests. Here I demonstrate how you can access GitHub Secrets stored in GitHub while doing CI/CD.

Steps

  • Go to GitHub Repository > Settings. From the left menu, selection Secrets > Actions

Actions link

  • Select New repository secret and add a key-value pair. For our example, we have used the key name as T1 and Value as Hello world. Then save it

Save actions secret

  • Once you save it, it should be visible on the screen

Secrets list

  • Now you need to add the secret in your GitHub Actions Workflow file. You need to call the secret using
env:
    T1: ${{secrets.T1}}
Enter fullscreen mode Exit fullscreen mode

Here is my Github Actions workflow

name: Go

on:
    push:
        branches: ["master"]
    pull_request:
        branches: ["master"]

env:
    T1: ${{secrets.T1}}

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v3

            - name: Set up Go
              uses: actions/setup-go@v3
              with:
                  go-version: 1.18

            - name: Build
              run: go build -v ./...

            - name: Test
              run: go test -v ./...

            - name: Environment list
              run: env

Enter fullscreen mode Exit fullscreen mode

Once you do that, you should access this in your unit tests and code as

env1, err1 := os.LookupEnv("T1")
log.Println(env1, err1)
Enter fullscreen mode Exit fullscreen mode

Download source code

Top comments (0)