Introduction
Terraform does not have built-in functionality for automatically adding taints to resources based on a time to live (TTL).
An AWS IAM Access Key can be rotated by using the lifecycle
block to force the recreation of aws_iam_access_key
resources based on changes to an external data source.
Expected Outcome
Rotate (re-create) an AWS IAM Access Key using Terraform.
Prerequisites
- Terraform:
>= 1.2
Use Case
Using the replace_triggered_by
argument to replace resources specified within thelifecycle
block.
Procedure
You can use the lifecycle
block to force the recreation of aws_iam_access_key
resources based on an external data source(json format) providing the desired TTL as below:
- Create a data source that returns the desired TTL or expiration duration for access keys(access_key_ttl.json)
{
"ttl_days": 30
}
- Now, in your Terraform configuration, you can define a data source to read this JSON file ()
data "http" "access_key_ttl" {
url = "https://example.com/access_key_ttl.json"
}
- With the data source in place, you can use
replace_triggered_by
meta-argument in thelifecycle
block to automatically recreateaws_iam_access_key
resources.
resource "aws_iam_access_key" "example" {
user = aws_iam_user.example.name
lifecycle {
create_before_destroy = true
ignore_changes = [
id,
status,
create_date,
]
replace_triggered_by = [
data.http.access_key_ttl.body,
]
}
}
You will also need to set up a cron job that can periodically update the TTL data source e.g., the access_key_ttl.json
file) with a new value.
When the TTL value changes, Terraform will detect the change and recreate the aws_iam_access_key
resource based on the replace_triggered_by
meta-argument.