GitHub Actions is a powerful automation tool that allows you to automate, customize, and execute your software workflows right in your repository. One of the critical aspects of using GitHub Actions is securely managing sensitive information such as API keys, tokens, and other credentials. This guide will walk you through how to use secrets in GitHub Actions, ensuring that your workflows are secure and efficient.
Secrets in GitHub Actions are encrypted environment variables that you can store in your repository or organization settings. These secrets are then accessible by your workflows during runtime. Using secrets helps prevent sensitive information from being hard-coded into your workflow files, reducing the risk of security breaches.
To create a repository secret:
To create an organization secret:
To create an environment secret:
Once you have created your secrets, you can use them in your GitHub Actions workflows. Here’s how:
Secrets are accessed using the secrets context in your workflow files. For example, if you have a secret named MY_SECRET, you can access it like this:
steps:
- name: Use Secret
run: echo ${{ secrets.MY_SECRET }}
Here’s an example of a GitHub Actions workflow that uses a secret to authenticate with a third-party API:
name: Deploy to Production
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Deploy to Production
env:
API_KEY: ${{ secrets.PRODUCTION_API_KEY }}
run: |
curl --header "Authorization: Bearer $API_KEY" \
--data '{"key":"value"}' \
https://api.example.com/deploy
In this example, the PRODUCTION_API_KEY secret is used to authenticate a deployment request to a third-party API.
Using secrets in GitHub Actions is a crucial step in securing your workflows and protecting sensitive information. By following the best practices outlined in this guide, you can ensure that your GitHub Actions are both secure and efficient. Remember to regularly review and update your secrets to maintain optimal security posture.