Instead of writing a secret directly into the source code, you should define an alternative mechanism for obtaining the secret at the places where it is used, such as using environment variables or local files not under version control, or relaying to an external secret vault (aka secret manager). These are the most common options:
Environment Variables or Configuration files
Taking secrets from environment variables or configuration files works for any programming language and operating system.
Environment variables are not hard-coded, but they should be given the value somewhere. Application code and scripts may read the environment variable, but environment variables must be set before the application or script runs.
With local files, you may need to enforce that the exclude patterns in .gitignore or .dockerignore configurations are properly excluding the secret-holding files
With environment variables, it is more difficult to accidentally leak secrets, but be aware that the software may write environment variables for debugging to standard output/error, potentially disclosing the value in publicly available logs.
A popular way to setup environment variables is to load them from an .env file, but remember: that file should never be under version control.
A template.env file containing only the variable names with empty/blank values, and comments explaining which is the secret and how it is used, is a good technique for documenting the secrets needed and for inventory of the secrets used.
If that innocuous template.env file is under version control and .env in .gitignore, users can copy template.env to .env, and then edit the git-ignored .env with the real secrets.
The following are examples for how to get a secret from .env file for each ecosystem. Replace the name of the environment variable SECRET_VAR and <path> to the .env file accordingly.
Code examples below are illustrative and simplified, with no error handling and configuration.
using dotenv.net;
using System;
DotEnv.Load(options: new DotEnvOptions(envFilePaths: new[] {"<path>/.env"}));
string secret = Environment.GetEnvironmentVariable("SECRET_VAR");
// alternative: load map instead of setting env vars
var secrets = DotEnv.Read(options: new DotEnvOptions(envFilePaths: new[] {"<path>/.env"}));
string secret = secrets["SECRET_VAR"];
Using SCM Secrets
Collaboration platforms (aka Source Code Management Systems, SCM) and CI/CD tools often provide Secret Management, so CI/CD pipelines may get the secret securely.
GitHub
Secrets in GitHub are variables set in an organization, repository, or repository environment, available to use in GitHub Actions workflows.
For secrets stored at the organization-level, access policies control which repositories can use organization secrets. Organization-level secrets let secrets be shared 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.
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.
Once a secret is registered, it can be referenced in a CI/CD workflow using a {{ secret.SECRET }} expression. But if possible, do not pass the secret value to the command to be executed. The command should read the environment variable instead. In the following example, a secret named API_KEY is passed to the workflow step in the environment variable API_KEY, but its value is then hard-coded in the command line, so it will be visible in the process table:
steps:
- name: Hello world action
shell: bash
env: # pass the secret as environment variable
API_KEY: ${{ secrets.API_KEY }}
run: |
# Not recommended! ps will show the clear-text secret
my-command --key="$API_KEY" ...
# my-command must read environment variable API_KEY
GitLab
GitLab provides support for external secret management providers:
job_using_vault:
id_tokens:
VAULT_ID_TOKEN:
aud: https://vault.example.com # use your own
secrets:
SECRET:
# translates to secret `ops/data/production/db`, field `password`
vault: production/db/password@ops
file: false
token: $VAULT_ID_TOKEN
This stores the value of the secret fetched from the vault into the SECRET variable.
Using Cloud Secret Management Services
AWS Secrets Manager
import {
GetSecretValueCommand,
SecretsManagerClient,
} from "@aws-sdk/client-secrets-manager";
export const getSecretValue = async (secretName: string) => {
const client = new SecretsManagerClient();
const response = await client.send(
new GetSecretValueCommand({
SecretId: secretName,
}),
);
console.log(response);
if (response.SecretString) {
return response.SecretString;
} else if (response.SecretBinary) {
return response.SecretBinary;
}
};
let secret = await get_secret("SECRET")
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
string keyVaultName = "your-key-vault-name";
string kvUri = $"https://{keyVaultName}.vault.azure.net";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
var secret = client.GetSecret("SECRET").Value;
using Google.Cloud.SecretManager.V1;
using System;
using System.Threading.Tasks;
public static async Task<string> AccessSecretAsync(string projectId, string secretId, string versionId)
{
var client = await SecretManagerServiceClient.CreateAsync();
var secretVersionName = SecretVersionName.FromProjectSecretVersion("<project_id>", "SECRET", "latest");
var result = await client.AccessSecretVersionAsync(secretVersionName);
return result.Payload.Data.ToStringUtf8();
}
var secret = await AccessSecretAsync();
Using a Third-Party Secret Vault
HashiCorp Vault
In what follows, we assume a mount point of "secret" and a vault path of "SECRET", and the secret is stored under key "value".
import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
var config = new VaultConfig()
.address(System.getenv("VAULT_URL"))
.token(System.getenv("VAULT_TOKEN"))
.build();
Vault vault = new Vault(config);
String secret = vault.logical().read("secret/SECRET").getData().get("value");
import (
"os"
vault "github.com/hashicorp/vault/api"
)
config := vault.DefaultConfig()
config.Address = os.Getenv("VAULT_URL")
client, err := vault.NewClient(config)
if err != nil {...}
client.SetToken( os.Getenv("VAULT_TOKEN") )
// default mount point secret. Secret data with string keyed by "value"
resp, err := client.Logical().Read("secret/SECRET")
if err != nil {...}
if resp == nil {...}
secret, ok := resp.Data["value"].(string)
using System;
using VaultSharp;
using VaultSharp.V1.AuthMethods.Token;
using VaultSharp.V1.Commons;
// recommendation: get url and token from environment
string vaultUrl = Environment.GetEnvironmentVariable("VAULT_URL");
string token = Environment.GetEnvironmentVariable("VAULT_TOKEN");
var settings = new VaultClientSettings(vaultUrl, new TokenAuthMethodInfo(token));
var client = new VaultClient(settings);
Secret<SecretData> res = await client.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "SECRET", mountPoint: "secret").Result;
string secret = res.Data.Data["value"];
CyberArk Conjur
The following show how to fetch a secret from CyberArk Conjur for popular programming languages. The environment variables CONJUR_APPLIANCE_URL, CONJUR_ACCOUNT, CONJUR_USERNAME and CONJUR_APIKEY contain the configuration needed to authenticate for fetching the secret.
import com.cyberark.conjur.api.Conjur;
String conjurUrl = System.getenv("CONJUR_APPLIANCE_URL");
String conjurAccount = System.getenv("CONJUR_ACCOUNT");
String conjurUsername = System.getenv("CONJUR_USERNAME");
String conjurApikey = System.getenv("CONJUR_APIKEY");
var credentials = new Credentials(conjurUsername, conjurApikey);
var conjur = new Conjur(credentials);
String secret = conjur.variables().retrieveSecret("SECRET");
import (
"os"
"github.com/cyberark/conjur-api-go/conjurapi"
"github.com/cyberark/conjur-api-go/conjurapi/authn"
)
// Assumes CONJUR_APPLIANCE_URL and CONJUR_ACCOUNT passed as environment variables
config, err := conjurapi.LoadConfig()
if err != nil {...}
conjur, err := conjurapi.NewClientFromKey(config,
authn.LoginPair{
Login: os.Getenv("CONJUR_USERNAME"),
APIKey: os.Getenv("CONJUR_APIKEY"),
},
)
if err != nil {...}
// Retrieve a secret into []byte.
secretValue, err := conjur.RetrieveSecret(variableIdentifier)
if err != nil {...}
secret = string(secretValue)
// Retrieve a secret into io.ReadCloser, then read into []byte.
// Alternatively, you can transfer the secret directly into secure memory, vault, keychain, etc.
secretResponse, err := conjur.RetrieveSecretReader("SECRET")
if err != nil {...}
secret, err = conjurapi.ReadResponseBody(secretResponse)
using System;
using Conjur;
string conjurUrl = Environment.GetEnvironmentVariable("CONJUR_APPLIANCE_URL");
string conjurAccount = Environment.GetEnvironmentVariable("CONJUR_ACCOUNT");
string conjurUsername = Environment.GetEnvironmentVariable("CONJUR_USERNAME");
string conjurApikey = Environment.GetEnvironmentVariable("CONJUR_APIKEY");
Client client = new Client("https://myorg.com", account);
string token = client.Login(conjurUsername, conjurApikey);
Variable variable = new Variable(client, "SECRET");
var secret = variable.GetValue();
See for full details.
See for full details.
See for full details.
See for full details.
Although GitHub Actions automatically redacts ("obfuscates") the contents of all GitHub secrets that are printed to workflow logs, this is not fail-proof. Only a are recognized.
Read creating secrets , , or for details on how to register a secret for GitHub Actions at a given scope.
GitLab provides as a convenient wau to store and reuse data in a CI/CD pipeline, but they can be exposed by accidental pipeline misconfiguration.
.
.
.
After , you may use vault secrets in a GitLab CI job:
Read for full details.
is the secret vault service in Amazon Web Services platform. The following are examples of how to use the official libraries for getting a secret using different programming languages:
See for further details.
The following uses , the official Python interface maintained by AWS.
See for further details.
The is the official Java library for accessing AWS Secrets Manager
The package provides the official API client, operations, and parameter types for AWS Secrets Manager, using the .
For full details, proceed with .
The is the secrets management service in Azure. The following shows how to retrieve a secret using the official libraries for some popular languages.
The following shows how to use the package.
The is the official Python library for accessing the Key Vault.
Read documentation for full details.
The following fetches a secret from Key Vault using .
The following shows how to fetch a secret using the .
is Google Cloud’s storage system for API keys, passwords, certificates, and other sensitive data.
In the following, <project_id> represents your Google Cloud Project ID, and SECRET is the name of the secret to fetch. It is assumed that the latest version of the secret is fetched. Examples can be found in the page.
The is the official JavaScript library for Secret Manager. The following example shows how to fetch a secret.
See .
See .
See .
See .
is a centralized secrets management system that provides secure storage of sensitive information, such as password, API keys, access tokens or cryptographic keys, encrypted in transit and at rest. It permits dynamic generation for temporary, on-demand credentials, and advanced features like automated key rotation and leasing/renewal of secrets, plus some built-in support for secret revocation.
See , unofficial NPM package for Vault.
The following uses , a Python client for Vault and other secret managers.
The example uses the (unofficial) .
The following example uses the official Go library.
The following example uses , .NET library for Vault.
is an open-source security tool for managing secrets and credentials in modern IT environments.
Go to or for further detail.
The following code uses the official library.
The following code uses the official library.
The following example retrieves a secret using the community-supported Go module.