Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active January 30, 2023 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atheiman/0944ece7399af7dd951b1bfe23fae847 to your computer and use it in GitHub Desktop.
Save atheiman/0944ece7399af7dd951b1bfe23fae847 to your computer and use it in GitHub Desktop.
Generate self-signed TLS cert using Terraform

Generate a private key and self-signed TLS certificate using the Terraform TLS provider.

# Download this terraform file into the current directory
curl -O https://gist.githubusercontent.com/atheiman/0944ece7399af7dd951b1bfe23fae847/raw/main.tf

# Modify "locals" in main.tf as needed

# Generate the key and cert
terraform init -upgrade
terraform apply -auto-approve

# See the local key and certificate files
ls -alh *.pem

# Inspect the TLS certificate
openssl x509 -in *.crt.pem -text -noout
# https://registry.terraform.io/providers/hashicorp/tls/latest/docs
locals {
# first name will be used for cert subject common name
dns_names = ["acme.com", "acme.net"]
cert_subject_organization = "Acme Internal Self-Signed"
}
resource "tls_private_key" "backend_tls" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "tls_self_signed_cert" "backend_tls" {
private_key_pem = tls_private_key.backend_tls.private_key_pem
# Valid for 100 years
validity_period_hours = 24 * 366 * 100
# Terraform will renew if re-applied within one year of expiration
early_renewal_hours = 24 * 366
# Reasonable set of uses for a server SSL certificate.
allowed_uses = [
"key_encipherment",
"digital_signature",
"server_auth",
]
dns_names = local.dns_names
subject {
common_name = local.dns_names[0]
organization = local.cert_subject_organization
}
}
resource "local_file" "key_pem" {
filename = "${path.module}/${tls_self_signed_cert.backend_tls.dns_names[0]}.key.pem"
content = tls_private_key.backend_tls.private_key_pem
}
resource "local_file" "cert_pem" {
filename = "${path.module}/${tls_self_signed_cert.backend_tls.dns_names[0]}.crt.pem"
content = tls_self_signed_cert.backend_tls.cert_pem
}
output "openssl_cert_verify_command" {
value = "openssl x509 -in ${local_file.cert_pem.filename} -text -noout"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment