Using Environment Variables In GitHub Actions - rashinarasheed/github-actions-cert-prep GitHub Wiki

What is an Environment Variable?

An environment variable is a temporary key-value pair that stores information about the environment in which the program is running.

The environment refers to:

  1. System - Windows, Linux, Mac
  2. Runtime - GitHub Actions, Docker, or a server
  3. The settings needed for the program to work

Instead of hardcoding values inside a program, environment variables let you set them outside the code, making them flexible and reusable.

For example, in GitHub Actions, the environment variable include

  • Where your code is checked out (GITHUB_WORKSPACE)
  • Who owns the repository (GITHUB_REPOSITORY)
  • API key or secrets that shouldn't be in the code like secrets.MY_SECRET_KEY

Environment Variables in Workflows

Environment variables in workflows are key-value pairs that can be used to store information that you want to reuse in your workflow steps. They provide flexibility and allow you to customize the behavior of your workflows without hardcoding values.

Environment variables can be declared at different scopes, such as workflow, job, or step level, using the env keyword or the env context. It is used for dynamic values that can change at run time.

Default Environment Variable

The default environment variables that GitHub sets are available to every step in a workflow.

Because default environment variables are set by GitHub and not defined in a workflow, they are not accessible through the env context. However, most of the default variables have a corresponding, and similarly named, context property. For example, the value of the GITHUB_REF variable can be read during workflow processing using the ${{ github.ref }} context property. When you set an environment variable, you cannot use any of the default environment variable names.

To know more about default environment variables, refer to default environment variables

Custom Environment Variables

A custom Environment variable is an Environment variable that you define .It can be scoped at different levels in a workflow: globally at the workflow level, at the job level, or within individual steps.

Ways to define Custom Environment Variables

  1. At the Workflow Level
name: Custom environment variable at workflow level
on: push
env:
    GLOBAL_ENV: "HELLO FROM WORKFLOW LEVEL"

jobs:
    job_1:
        runs-on: ubuntu-latest
        steps:
            - name: Show global environment variable
              run: echo "Workflow variable ${{env.GLOBAL_ENV}}"

  1. At the Job Level