Publicamos atualizações frequentes em nossa documentação, e a tradução desta página ainda pode estar em andamento. Para obter as informações mais recentes, acesse a documentação em inglês. Se houver problemas com a tradução desta página, entre em contato conosco.

Creating and storing encrypted secrets

Encrypted secrets allow you to store sensitive information in your repository or organization.

GitHub Actions is available with GitHub Free, GitHub Pro, GitHub Free for organizations, GitHub Team, GitHub Enterprise Cloud, and GitHub One. GitHub Actions is not available for private repositories owned by accounts using legacy per-repository plans. For more information, see "GitHub's products."

Neste artigo

About encrypted secrets

Secrets are encrypted environment variables that you create in a repository or organization. The secrets you create are available to use in GitHub Actions workflows. GitHub uses a libsodium sealed box to help ensure that secrets are encrypted before they reach GitHub, and remain encrypted until you use them in a workflow.

For secrets stored at the organization-level, you can use access policies to control which repositories can use organization secrets. Organization-level secrets let you share secrets between multiple repositories, which reduces the need for creating duplicate secrets. Updating an organization secret in one location also ensures that the change takes effect in all repository workflows that use that secret.

Naming your secrets

The following rules apply to secret names:

  • Secret names can only contain alphanumeric characters ([a-z], [A-Z], [0-9]) or underscores (_). Spaces are not allowed.
  • Secret names must not start with the GITHUB_ prefix.
  • Secret names must not start with a number.
  • Secret names must be unique at the level they are created at. For example, a secret created at the organization-level must have a unique name at that level, and a secret created at the repository-level must have a unique name in that repository. If an organization-level secret has the same name as a repository-level secret, then the repository-level secret takes precedence.

To help ensure that GitHub redacts your secret in logs, avoid using structured data as the values of secrets. For example, avoid creating secrets that contain JSON or encoded Git blobs.

Accessing your secrets

Para disponibilizar um segredo para uma ação, você deve configurá-lo como uma entrada ou variável de ambiente no arquivo do fluxo de trabalho. Revise o arquivo LEIAME da ação para saber quais entradas e variáveis de ambientes a ação exige. Para obter mais informações, consulte "Sintaxe de fluxo de trabalho para o GitHub Actions".

You can use and read encrypted secrets in a workflow file if you have access to edit the file. For more information, see "Access permissions on GitHub."

Warning: GitHub automatically redacts secrets printed to the log, but you should avoid printing secrets to the log intentionally.

You can also manage secrets using the REST API. For more information, see "Secrets" in documentação do GitHub Developer.

Limiting credential permissions

When generating credentials, we recommend that you grant the minimum permissions possible. For example, instead of using personal credentials, use deploy keys or a service account. Consider granting read-only permissions if that's all that is needed, and limit access as much as possible. When generating a personal access token (PAT), select the fewest scopes necessary.

Creating encrypted secrets for a repository

To create secrets for a user account repository, you must be the repository owner. To create secrets for an organization repository, you must have admin access.

  1. No GitHub, navegue até a página principal do repositório.
  2. Under your repository name, click Settings.
    Repository settings button
  3. Na barra lateral esquerda, clique em Secrets (Segredos).
  4. Click Add a new secret.
  5. Type a name for your secret in the Name input box.
  6. Enter the value for your secret.
  7. Clique em Add secret (Adicionar segredo).

If your repository can access secrets from the parent organization, then those secrets are also listed on this page.

Creating encrypted secrets for an organization

When creating a secret in an organization, you can use a policy to limit which repositories can access that secret. For example, you can grant access to all repositories, or limit access to only private repositories or a specified list of repositories.

To create secrets at the organization level, you must have admin access.

  1. On GitHub, navigate to the main page of the organization.
  2. Under your organization name, click Settings.
    Organization settings button
  3. Na barra lateral esquerda, clique em Secrets (Segredos).
  4. Click New secret.
  5. Type a name for your secret in the Name input box.
  6. Enter the Value for your secret.
  7. From the Repository access dropdown list, choose an access policy.
  8. Clique em Add secret (Adicionar segredo).

Reviewing access to organization-level secrets

You can check which access policies are being applied to a secret in your organization.

  1. On GitHub, navigate to the main page of the organization.
  2. Under your organization name, click Settings.
    Organization settings button
  3. Na barra lateral esquerda, clique em Secrets (Segredos).
  4. The list of secrets includes any configured permissions and policies. Por exemplo:
    Secrets list
  5. For more details on the configured permissions for each secret, click Update.

Using encrypted secrets in a workflow

Com exceção do GITHUB_TOKEN, os segredos não são disponibilizados para o executor quando um fluxo de trabalho é acionado a partir de um repositório bifurcado.

To provide an action with a secret as an input or environment variable, you can use the secrets context to access secrets you've created in your repository. For more information, see "Context and expression syntax for GitHub Actions" and "Workflow syntax for GitHub Actions."

steps:
  - name: Hello world action
    with: # Configura o segredo como uma entrada
      super_secret: ${{ secrets.SuperSecret }}
    env: # Ou como uma variável de ambiente
      super_secret: ${{ secrets.SuperSecret }}

Avoid passing secrets between processes from the command line, whenever possible. Command-line processes may be visible to other users (using the ps command) or captured by security audit events. To help protect secrets, consider using environment variables, STDIN, or other mechanisms supported by the target process.

If you must pass secrets within a command line, then enclose them within the proper quoting rules. Secrets often contain special characters that may unintentionally affect your shell. To escape these special characters, use quoting with your environment variables. Por exemplo:

Example using Bash

steps:
  - shell: bash
    env:
      SUPER_SECRET: ${{ secrets.SuperSecret }}
    run: |
      example-command "$SUPER_SECRET"

Example using PowerShell

steps:
  - shell: pwsh
    env:
      SUPER_SECRET: ${{ secrets.SuperSecret }}
    run: |
      example-command "$env:SUPER_SECRET"

Example using Cmd.exe

steps:
  - shell: cmd
    env:
      SUPER_SECRET: ${{ secrets.SuperSecret }}
    run: |
      example-command "%SUPER_SECRET%"

Limites para segredos

Your workflow can have up to 100 secrets. The names of secret environment variables must be unique in a repository.

Os segredos são limitados a 64 kB. Para usar segredos maiores que 64 kB, você pode armazenar segredos criptografados no seu repositório e salvar a frase secreta de descodificação como um segredo no GitHub. Por exemplo, você pode usar gpg para criptografar suas credenciais localmente antes de colocar o arquivo no repositório do GitHub. Para obter mais informações, consulte a "página do manual gpg".

Aviso: cuide para seus segredos não serem impressos quando a ação é executada. Quando usar essa alternativa, o GitHub não eliminará segredos que estão impressos nos logs.

  1. Execute o seguinte comando no seu terminal para criptografar o arquivo my_secret.json usando gpg e o algoritmo de cifragem AES256.

    $ gpg --symmetric --cipher-algo AES256 my_secret.json
  2. Você receberá a solicitação para inserir a frase secreta. Guarde a frase secreta, pois você precisará criar um novo segredo no GitHub que usa a frase secreta como valor.

  3. Create a new secret that contains the passphrase. Por exemplo, crie um novo segredo com o nome LARGE_SECRET_PASSPHRASE e defina o valor do segredo para a frase secreta que você escolheu na etapa anterior.

  4. Copie o arquivo criptografado no repositório e faça commit. Nesse exemplo, o arquivo criptografado é my_secret.json.gpg.

  5. Crie um script shell para decifrar a senha. Salve o arquivo como decrypt_secret.sh.

    #!/bin/sh
    
    # Decrypt the file
    mkdir $HOME/secrets
    # --batch to prevent interactive command
    # --yes to assume "yes" for questions
    gpg --quiet --batch --yes --decrypt --passphrase="$LARGE_SECRET_PASSPHRASE" \
    --output $HOME/secrets/my_secret.json my_secret.json.gpg
  6. Confirme que o shell script é executável antes de colocá-lo no repositório.

    $ chmod +x decrypt_secret.sh
    $ git add decrypt_secret.sh
    $ git commit -m "Add new decryption script"
    $ git push
  7. A partir de seu fluxo de trabalho, use step para chamar o shell script e decifrar o segredo. To have a copy of your repository in the environment that your workflow runs in, you'll need to use the actions/checkout action. Faça referência ao shell script usando o comando run relativo à raiz do repositório.

    name: Workflows with large secrets
    
    on: push
    
    jobs:
      my-job:
        name: My Job
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v2
          - name: Decrypt large secret
            run: ./.github/scripts/decrypt_secret.sh
            env:
              LARGE_SECRET_PASSPHRASE: ${{ secrets.LARGE_SECRET_PASSPHRASE }}
          # Esse comando é apenas um exemplo para mostrar seu segredo sendo impresso
          # Certifique-se de remover quaisquer declaração de impressão de seus segredos. O GitHub
          # não oculta segredos que usam essa alternativa.
          - name: Test printing your secret (Remove this step in production)
            run: cat $HOME/secrets/my_secret.json
    

Pergunte a uma pessoa

Não consegue encontrar o que procura?

Entrar em contato