This example shows how to add a secret to an existing GitHub environment using Terraform.
Do not do this if you are concerned about the secret being stored in the tfstate files. In some scenarios (secret migration from CloudBees -> GitHub) terraform is a reasonable approach to get the job done since it's a one time operation and the state can be thrown away, but for standard long-term secrets management there are other ways to handle it without exposing secrets to state.
- GitHub repository with existing environments (e.g., PROD, STAGING)
- GitHub personal access token with
repo
scope - Terraform installed
# main.tf
# Configure Terraform and required providers
terraform {
required_version = ">= 1.0"
required_providers {
github = {
source = "integrations/github"
version = "~> 6.0"
}
}
}
# Configure the GitHub Provider
provider "github" {
token = var.github_token # Set via environment variable TF_VAR_github_token
}
# Variables
variable "github_token" {
description = "GitHub personal access token with repo scope"
type = string
sensitive = true
}
variable "repository_name" {
description = "Name of the GitHub repository"
type = string
default = "your-repository-name" # Update this
}
variable "secret_value" {
description = "The secret value to store in the PROD environment"
type = string
sensitive = true
}
# Data source to reference the existing repository
data "github_repository" "repo" {
name = var.repository_name
}
# Add secret to existing PROD environment
resource "github_actions_environment_secret" "prod_secret" {
repository = data.github_repository.repo.name
environment = "PROD" # This must match your existing environment name exactly
secret_name = "NEW_SECRET"
plaintext_value = var.secret_value
}
# Output to confirm the secret was created
output "secret_created" {
value = "Secret '${github_actions_environment_secret.prod_secret.secret_name}' created in ${github_actions_environment_secret.prod_secret.environment} environment"
}
-
Set your GitHub token:
export TF_VAR_github_token="ghp_your_personal_access_token"
-
Create a
terraform.tfvars
file (optional):repository_name = "my-actual-repo" secret_value = "my-secret-value"
Or set via environment variables:
export TF_VAR_repository_name="my-actual-repo" export TF_VAR_secret_value="my-secret-value"
-
Initialize and apply:
terraform init terraform plan terraform apply
- The environment ("PROD" in this example) must already exist in your GitHub repository
- The secret value will be stored in the Terraform state file, so ensure your state is stored securely
- You can add multiple secrets by duplicating the
github_actions_environment_secret
resource block - To add secrets to different environments, change the
environment
parameter
- Never commit secret values to version control
- Use environment variables or secure secret management tools
- Store Terraform state files securely (e.g., in Terraform Cloud or encrypted S3)
- Rotate tokens and secrets regularly