lfarci / github-actions

Preparation resources for the GitHub Actions certification
0 stars 0 forks source link

Demonstrate how to access encrypted secrets within actions and workflows #70

Closed lfarci closed 3 months ago

lfarci commented 3 months ago

In GitHub Actions, you can access encrypted secrets using the secrets context. Here's an example of how to use secrets in a workflow:

name: Demo workflow
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Run a step with secrets
        run

:

 |
          echo "My Secret: $MY_SECRET"
        env:
          MY_SECRET: ${{ secrets.MY_SECRET }}

In this workflow, the "Run a step with secrets" step uses a secret named MY_SECRET. The secret is accessed using the secrets context (${{ secrets.MY_SECRET }}) and is assigned to an environment variable (MY_SECRET). The environment variable is then used in the run command.

Please note that the actual value of the secret will not be printed in the logs. Instead, GitHub Actions will mask the value of the secret.

Before running this workflow, make sure to add MY_SECRET to your repository's secrets. You can do this in the repository settings under the "Secrets" section.

This workflow will run whenever a push or pull request event occurs. The output of the "Run a step with secrets" step can be viewed in the logs for the workflow run.

lfarci commented 3 months ago

If you're writing a custom action in JavaScript or TypeScript, you can access secrets passed to the action via the inputs in your action.yml file. The secrets are passed as environment variables to the action.

Here's an example of how to define an input for a secret in the action.yml file:

inputs:
  my_secret:
    description: 'My secret'
    required: true

In your action's JavaScript code, you can access this input (and thus the secret) using the core module from the @actions/core package:

const core = require('@actions/core');

try {
  // Get the "my_secret" input
  const mySecret = core.getInput('my_secret', { required: true });

  // Now you can use "mySecret" in your action code
  console.log(`My secret is ${mySecret}`);
} catch (error) {
  core.setFailed(error.message);
}

Please note that the actual value of the secret will not be printed in the logs. Instead, GitHub Actions will mask the value of the secret.

When using this action in a workflow, you would pass the secret like this:


steps

:
  - name: My custom action
    uses: ./.github/actions/my-custom-action
    with:
      my_secret: ${{ secrets.MY_SECRET }}

In this example, MY_SECRET is a secret that you've defined in your repository's settings.