Skip to main content

Esta versión de GitHub Enterprise Server se discontinuó el 2023-09-25. No se realizarán lanzamientos de patch, ni siquiera para problemas de seguridad críticos. Para obtener rendimiento mejorado, seguridad mejorada y nuevas características, actualice a la versión más reciente de GitHub Enterprise Server. Para obtener ayuda con la actualización, póngase en contacto con el soporte técnico de GitHub Enterprise.

Using secrets in GitHub Actions

Secrets allow you to store sensitive information in your organization, repository, or repository environments.

Tool navigation

Nota: Actualmente los ejecutores hospedados en GitHub no se admiten en GitHub Enterprise Server. Puede ver más información sobre la compatibilidad futura planeada en GitHub public roadmap.

About secrets

Secrets are variables that you create in an organization, repository, or repository environment. The secrets that you create are available to use in GitHub Actions workflows. GitHub Actions can only read a secret if you explicitly include the secret in a workflow.

Para los secretos almacenados a nivel organizacional, peudes utilizar las políticas de acceso para controlar qué repositorios pueden utilizar secretos organizacionales. Los secretos a nivel organizacional te permiten compartir secretos entre repositorios múltiples, lo cual reduce la necesidad de crear secretos duplicados. El actualizar un secreto de organización en una ubicación también garantiza que el cambio tome efecto en todos los flujos de trabajo del repositorio que lo utilicen.

For secrets stored at the environment level, you can enable required reviewers to control access to the secrets. A workflow job cannot access environment secrets until approval is granted by required approvers.

Note: Si tus flujos de trabajo de GitHub Actions necesitan acceder a los recursos de un proveedor de servicios en la red que sea compatible con OpenID Connect (OIDC), puedes configurarlos para que se autentiquen directamente con dicho proveedor. Esto te permitirá dejar de almacenar estas credenciales como secretos de duración larga y te proporcionará otros beneficios de seguridad. Para más información, consulta "Acerca del fortalecimiento de seguridad con OpenID Connect".

Naming your secrets

The following rules apply to secret names:

  • Los nombres solo pueden contener caracteres alfanuméricos ([a-z], [A-Z], [0-9]) o caracteres de subrayado (_). No se permiten espacios.

  • Los nombres no deben comenzar con el prefijo GITHUB_.

  • Los nombres no deben comenzar con un número.

  • Los nombres no distinguen mayúsculas de minúsculas.

  • Los nombres deben ser únicos en el nivel en el que se hayan creado.

    For example, a secret created at the environment level must have a unique name in that environment, a secret created at the repository level must have a unique name in that repository, and a secret created at the organization level must have a unique name at that level.

    Si existe un secreto con el mismo nombre en varios niveles, tiene preferencia el del nivel más bajo. Por ejemplo, si un secreto a nivel de organización tiene el mismo nombre que un secreto a nivel de repositorio, entonces el secreto a nivel de repositorio tomará precedencia. Similarly, if an organization, repository, and environment all have a secret with the same name, the environment-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

To make a secret available to an action, you must set the secret as an input or environment variable in the workflow file. Review the action's README file to learn about which inputs and environment variables the action expects. For more information, see "Sintaxis del flujo de trabajo para Acciones de GitHub."

You can use and read secrets in a workflow file if you have access to edit the file. For more information, see "Permisos de acceso en GitHub."

Advertencia: GitHub censura automáticamente los secretos impresos en el registro, pero debe evitar imprimirlos en el registro de manera intencionada.

Organization and repository secrets are read when a workflow run is queued, and environment secrets are read when a job referencing the environment starts.

You can also manage secrets using the REST API. For more information, see "Acciones."

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, select the fewest scopes necessary.

Instead of using a personal access token, consider using a GitHub App, which uses fine-grained permissions and short lived tokens. Unlike a personal access token, a GitHub App is not tied to a user, so the workflow will continue to work even if the user who installed the app leaves your organization. For more information, see "Realización de solicitudes de API autenticadas con una aplicación de GitHub en un flujo de trabajo de Acciones de GitHub."

Note: Users with collaborator access to a repository can use the REST API to manage secrets for that repository, and users with admin access to an organization can use the REST API to manage secrets for that organization. For more information, see "Acciones."

Creating secrets for a repository

Para crear secretos en GitHub para un repositorio de una cuenta personal, debes ser propietario del repositorio. Para crear secretos en GitHub para un repositorio de una organización, debes tener acceso de admin. Por último, para crear secretos para un repositorio de cuentas personales o un repositorio de una organización a través de la API REST, es preciso tener acceso de colaborador.

  1. En tu instancia de GitHub Enterprise Server, navega a la página principal del repositorio.
  2. En el nombre del repositorio, haz clic en Configuración. Si no puedes ver la pestaña "Configuración", selecciona el menú desplegable y, a continuación, haz clic en Configuración. Captura de pantalla de un encabezado de repositorio en el que se muestran las pestañas. La pestaña "Configuración" está resaltada con un contorno naranja oscuro.
  3. En la sección "Seguridad" de la barra lateral, selecciona Secretos, después, haz clic en Acciones.
  4. Click New repository secret.
  5. In the Name field, type a name for your secret.
  6. In the Secret field, enter the value for your secret.
  7. Click Add secret.

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

Para más información sobre GitHub CLI, consulta "Acerca del CLI de GitHub".

To add a repository secret, use the gh secret set subcommand. Replace secret-name with the name of your secret.

gh secret set SECRET_NAME

The CLI will prompt you to enter a secret value. Alternatively, you can read the value of the secret from a file.

gh secret set SECRET_NAME < secret.txt

To list all secrets for the repository, use the gh secret list subcommand.

Creating secrets for an environment

Para crear secretos para un entorno en un repositorio de una cuenta personal, el repositorio debe ser de tu propiedad. Para crear secretos para un entorno en un repositorio de una organización, debes tener acceso a admin. Para obtener más información sobre los entornos, consulta "Utilizar ambientes para el despliegue".

  1. En tu instancia de GitHub Enterprise Server, navega a la página principal del repositorio.
  2. En el nombre del repositorio, haz clic en Configuración. Si no puedes ver la pestaña "Configuración", selecciona el menú desplegable y, a continuación, haz clic en Configuración. Captura de pantalla de un encabezado de repositorio en el que se muestran las pestañas. La pestaña "Configuración" está resaltada con un contorno naranja oscuro.
  3. En la barra lateral de la izquierda, haz clic en Entornos.
  4. Click on the environment that you want to add a secret to.
  5. Under Environment secrets, click Add secret.
  6. Type a name for your secret in the Name input box.
  7. Enter the value for your secret.
  8. Click Add secret.

To add a secret for an environment, use the gh secret set subcommand with the --env or -e flag followed by the environment name.

gh secret set --env ENV_NAME SECRET_NAME

To list all secrets for an environment, use the gh secret list subcommand with the --env or -e flag followed by the environment name.

gh secret list --env ENV_NAME

Creating secrets for an organization

Cuando creas un secreto o una variable en una organización, puedes usar una política para limitar el acceso por repositorio. Por ejemplo, puedes otorgar acceso a todos los repositorios, o limitarlo a solo los repositorios privados o a una lista específica de estos.

Para crear secretos en el nivel de organización, debes ser un dueño de la organización.

  1. En tu instancia de GitHub Enterprise Server, ve a la página principal de la organización.

  2. En el nombre de la organización, haz clic en Configuración. Si no puedes ver la pestaña "Configuración", selecciona el menú desplegable y, a continuación, haz clic en Configuración.

    Captura de pantalla de la barra de navegación horizontal de una organización. La pestaña "Configuración" se destaca en naranja oscuro.

  3. En la sección "Seguridad" de la barra lateral, selecciona Secretos, después, haz clic en Acciones.

  4. Click New organization 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. Click Add secret.

Note: By default, GitHub CLI authenticates with the repo and read:org scopes. To manage organization secrets, you must additionally authorize the admin:org scope.

gh auth login --scopes "admin:org"

To add a secret for an organization, use the gh secret set subcommand with the --org or -o flag followed by the organization name.

gh secret set --org ORG_NAME SECRET_NAME

By default, the secret is only available to private repositories. To specify that the secret should be available to all repositories within the organization, use the --visibility or -v flag.

gh secret set --org ORG_NAME SECRET_NAME --visibility all

To specify that the secret should be available to selected repositories within the organization, use the --repos or -r flag.

gh secret set --org ORG_NAME SECRET_NAME --repos REPO-NAME-1, REPO-NAME-2"

To list all secrets for an organization, use the gh secret list subcommand with the --org or -o flag followed by the organization name.

gh secret list --org ORG_NAME

Reviewing access to organization-level secrets

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

  1. En tu instancia de GitHub Enterprise Server, ve a la página principal de la organización.

  2. En el nombre de la organización, haz clic en Configuración. Si no puedes ver la pestaña "Configuración", selecciona el menú desplegable y, a continuación, haz clic en Configuración.

    Captura de pantalla de la barra de navegación horizontal de una organización. La pestaña "Configuración" se destaca en naranja oscuro.

  3. En la sección "Seguridad" de la barra lateral, selecciona Secretos, después, haz clic en Acciones.

  4. The list of secrets includes any configured permissions and policies. For more details about the configured permissions for each secret, click Update.

Using secrets in a workflow

Notes:

  • Con la excepción de GITHUB_TOKEN, los secretos no se pasan al ejecutor cuando se desencadena un flujo de trabajo desde un repositorio bifurcado.

  • Secrets are not automatically passed to reusable workflows. For more information, see "Reutilización de flujos de trabajo."

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 "Contextos" and "Sintaxis del flujo de trabajo para Acciones de GitHub."

steps:
  - name: Hello world action
    with: # Set the secret as an input
      super_secret: ${{ secrets.SuperSecret }}
    env: # Or as an environment variable
      super_secret: ${{ secrets.SuperSecret }}

Secrets cannot be directly referenced in if: conditionals. Instead, consider setting secrets as job-level environment variables, then referencing the environment variables to conditionally run steps in the job. For more information, see "Contextos" and jobs.<job_id>.steps[*].if.

If a secret has not been set, the return value of an expression referencing the secret (such as ${{ secrets.SuperSecret }} in the example) will be an empty string.

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. For example:

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%"

Limits for secrets

You can store up to 1,000 organization secrets, 100 repository secrets, and 100 environment secrets.

A workflow created in a repository can access the following number of secrets:

  • All 100 repository secrets.
  • If the repository is assigned access to more than 100 organization secrets, the workflow can only use the first 100 organization secrets (sorted alphabetically by secret name).
  • All 100 environment secrets.

Secrets are limited to 48 KB in size. To store larger secrets, see the "Storing large secrets" workaround below.

Storing large secrets

To use secrets that are larger than 48 KB, you can use a workaround to store secrets in your repository and save the decryption passphrase as a secret on GitHub. For example, you can use gpg to encrypt a file containing your secret locally before checking the encrypted file in to your repository on GitHub. For more information, see the "gpg manpage."

Warning: Be careful that your secrets do not get printed when your workflow runs. When using this workaround, GitHub does not redact secrets that are printed in logs.

  1. Run the following command from your terminal to encrypt the file containing your secret using gpg and the AES256 cipher algorithm. In this example, my_secret.json is the file containing the secret.

    gpg --symmetric --cipher-algo AES256 my_secret.json
    
  2. You will be prompted to enter a passphrase. Remember the passphrase, because you'll need to create a new secret on GitHub that uses the passphrase as the value.

  3. Create a new secret that contains the passphrase. For example, create a new secret with the name LARGE_SECRET_PASSPHRASE and set the value of the secret to the passphrase you used in the step above.

  4. Copy your encrypted file to a path in your repository and commit it. In this example, the encrypted file is my_secret.json.gpg.

    Warning: Make sure to copy the encrypted my_secret.json.gpg file ending with the .gpg file extension, and not the unencrypted my_secret.json file.

    git add my_secret.json.gpg
    git commit -m "Add new secret JSON file"
    
  5. Create a shell script in your repository to decrypt the secret file. In this example, the script is named decrypt_secret.sh.

    Shell
    #!/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. Ensure your shell script is executable before checking it in to your repository.

    chmod +x decrypt_secret.sh
    git add decrypt_secret.sh
    git commit -m "Add new decryption script"
    git push
    
  7. In your GitHub Actions workflow, use a step to call the shell script and decrypt the secret. To have a copy of your repository in the environment that your workflow runs in, you'll need to use the actions/checkout action. Reference your shell script using the run command relative to the root of your repository.

    name: Workflows with large secrets
    
    on: push
    
    jobs:
      my-job:
        name: My Job
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - name: Decrypt large secret
            run: ./decrypt_secret.sh
            env:
              LARGE_SECRET_PASSPHRASE: ${{ secrets.LARGE_SECRET_PASSPHRASE }}
          # This command is just an example to show your secret being printed
          # Ensure you remove any print statements of your secrets. GitHub does
          # not hide secrets that use this workaround.
          - name: Test printing your secret (Remove this step in production)
            run: cat $HOME/secrets/my_secret.json
    

Storing Base64 binary blobs as secrets

You can use Base64 encoding to store small binary blobs as secrets. You can then reference the secret in your workflow and decode it for use on the runner. For the size limits, see "Using secrets in GitHub Actions."

Note: Note that Base64 only converts binary to text, and is not a substitute for actual encryption.

  1. Use base64 to encode your file into a Base64 string. For example:

    base64 -i cert.der -o cert.base64
    
  2. Create a secret that contains the Base64 string. For example:

    $ gh secret set CERTIFICATE_BASE64 < cert.base64
    ✓ Set secret CERTIFICATE_BASE64 for octocat/octorepo
    
  3. To access the Base64 string from your runner, pipe the secret to base64 --decode. For example:

    name: Retrieve Base64 secret
    on:
      push:
        branches: [ octo-branch ]
    jobs:
      decode-secret:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - name: Retrieve the secret and decode it to a file
            env:
              CERTIFICATE_BASE64: ${{ secrets.CERTIFICATE_BASE64 }}
            run: |
              echo $CERTIFICATE_BASE64 | base64 --decode > cert.der
          - name: Show certificate information
            run: |
              openssl x509 -in cert.der -inform DER -text -noout
    

Note: Using another shell might require different commands for decoding the secret to a file. On Windows runners, we recommend using a bash shell with shell: bash to use the commands in the run step above.