Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell Terraform to skip the secret manager resource if it exists?

The idea is that I want to use Terraform resource aws_secretsmanager_secret to create only three secrets (not workspace-specified secret), one for the dev environment, one for preprod and the third one for production env.

Something like:

resource "aws_secretsmanager_secret" "dev_secret" {
  name = "example-secret-dev"
}

resource "aws_secretsmanager_secret" "preprod_secret" {
  name = "example-secret-preprod"
}

resource "aws_secretsmanager_secret" "prod_secret" {
  name = "example-secret-prod"
}

But after creating them, I don't want to overwrite them every time I run 'Terraform apply', is there a way to tell Terraform if any of the secrets exist, skip the creation of the secret and do not overwrite?

I had a look at this page but still doesn't have a clear solution, any suggestion will be appreciated.

like image 827
wawawa Avatar asked Nov 30 '25 01:11

wawawa


2 Answers

You could have Terraform generate random secret values for you using:

data "aws_secretsmanager_random_password" "dev_password" {
  password_length     = 16
}

Then create the secret metadata using:

resource "aws_secretsmanager_secret" "dev_secret" {
  name                    = "dev-secret"
  recovery_window_in_days = 7
}

And then by creating the secret version:

resource "aws_secretsmanager_secret_version" "dev_sv" {
  secret_id     = aws_secretsmanager_secret.dev_secret.id
  secret_string = data.aws_secretsmanager_random_password.dev_password.random_password
  lifecycle {
    ignore_changes = [secret_string, ]
  }
}

Adding the 'ignore_changes' lifecycle block to the secret version will prevent Terraform from overwriting the secret once it has been created. I tested this just now to confirm that a new secret with a new random value will be created, and subsequent executions of terraform apply do not overwrite the secret.

like image 91
nblivingston Avatar answered Dec 01 '25 14:12

nblivingston


It will not overwrite the secret if you create it manually in the console or using AWS SDK. The aws_secretsmanager_secret creates only the secret, but not its value. To set value you have to use aws_secretsmanager_secret_version.

Anyway, this is something you can easily test yourself. Just run your code with a secret, update its value in AWS console, and re-run terraform apply. You should see no change in the secret's value.

like image 43
Marcin Avatar answered Dec 01 '25 15:12

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!