Generic way to rotate secrets and passwords irrespective of any public cloud provider.

BootLabs's photo
BootLabs
·Jul 4, 2022·

2 min read

Nowadays everybody is shifting their infrastructure to cloud environments either from on premise or from cloud to cloud due to cost, scalability, higher availability or maybe for other 100s of benefit.

And to manage all the infrastructure under a hood one can use terraform for the purpose.

Problem statement: When we think of implementing the secrets and passwords rotation, we usually see the solutions that are cloud specific like rotation in aws secret manager, azure vault etc. These solutions work only when the infrastructure secrets is in one specific cloud.

So to tackle this situation we can create the secrets through terraform with the below resource blocks:

resource "random_password" "create_password” {
  length = 10
  upper  = true
  lower  = true
  special          = true
  override_special = "!#&-_+?"
  keepers = { 
     time = time_rotating.example.id 
  }
}

The random_password block will create the password as per our required parameters like password length, using special character etc. Keepers: keepers block hold the time_rotating resource reference in the random resource block.

resource "time_rotating" "example" {
  rotation_days = 2 
}

With above resource you can setup the rotation on monthly, hourly or minutes basis.

Please check for other required rotation options from official documentation page. registry.terraform.io/providers/hashicorp/t..

resource "aws_secretsmanager_secret" "rds_postgress" {
  name        = "test"
  description = "temp secret"
}
resource "aws_secretsmanager_secret_version" "rds_postgress_passwd" {
  secret_id     = aws_secretsmanager_secret.rds_postgress.id
  secret_string = <<EOF
{
  "username": "${random_password.create_password.result}"
}
EOF
}

This block will create the secret in AWS secret manager service. You can use any other service to setup the random passwords as well as per your requirements.

From the above example passwords will be rotated after 2 days and to make this possible please run the Terraform apply command again after 2 days as the password will change only after running the terraform apply command or setup the terraform apply in the respective scheduled pipelines.

Hope the above example gives clarity on rotating passwords using terraform.

Thank You…

Mohit Huria

Mohit-LinkedIn

Bootlabs

 
Share this