8

I have a IAM user that is created by Terraform. Keys are stored in Hashicrop Vault and apps read them from there.

I have developed ansible code/bash scripts to rotate the keys periodically successfully.

But the issue is terraform doesn't like when the keys are rotated. Whenever we try to run terraform it tries to re-create the key

Is there any way to manage the key rotation via terraform? or can we ignore this in terraform. Any help with examples would be really helpful.

sjm
  • 415
  • 1
  • 9
  • 23
  • Terraform should be reading the key from Vault instead of attempting to manage it directly. Also, you should probably look into rotating the keys with Vault intrinsically instead of managing them with multiple components. – Matthew Schuchard May 21 '19 at 14:15
  • Keys are for service users. Users are created via terrafor and credentials stored in vault. When we rotate the keys in AWS and Vault; terraform start complaining that it needs to recreate the users's key. Need a way to force terraform to ignore chagnes in iam keys after creation. `lifecycle and ignore` are not working for me – sjm May 21 '19 at 14:36
  • Just for anyone else benefit So far i couldn't find a way to manage key rotation via terraform. What i have gathered is that it's not recommended to use terraform for this purpose. Instead create user with terraform without creating IAM Keys and manage them externally – sjm May 22 '19 at 09:20

2 Answers2

11

Key rotation in terraform is possible by using terraform apply -replace=<resource address>, which replaces the resource immediately or terraform taint <resource address>, which replaces the resource on the next apply for version below v0.15.2. See https://www.terraform.io/docs/cli/commands/taint.html for more information.

When using these commands it makes sense to set the lifecycle of the resources to replace to create_before_destroy to avoid downtime. So in the case of AWS access keys, that would be

resource "aws_iam_access_key" "my_user" {
  user = "my_user_name"
  lifecycle {
    create_before_destroy = true
  }
}

Given this configuration one can simply run terraform apply -replace=aws_iam_access_key.my_user to rotate the keys. One only has to make sure that downstream applications that use the keys take notice of the changes and are restarted if necessary to make use of the new keys.

Jarno
  • 6,243
  • 3
  • 42
  • 57
2

We have managed to solve the problem by removing key generation initially via terraform when the user is created.

We are using some ansible and bash scripts to now generate and rotate keys and then vault api to update secrets in Vault.

sjm
  • 415
  • 1
  • 9
  • 23