Introduction
While Terraform does not have a native time-to-live (TTL) mechanism for resources, you can automate the rotation of an AWS IAM access key by using the lifecycle block. This approach forces the recreation of the aws_iam_access_key resource when an external data source changes.
Expected Outcome
You will rotate (re-create) an AWS IAM Access Key automatically using Terraform based on a configurable trigger.
Prerequisites
- Terraform v1.2 or newer.
Use Case
This procedure uses the replace_triggered_by argument within the lifecycle block to replace a resource when a specified data source value changes. This is useful for implementing security policies that require periodic credential rotation.
Procedure
Follow these steps to configure automated key rotation.
-
Create an external data source file that contains the desired Time To Live (TTL) for the access key. Terraform will monitor this file for changes. Save this content in a file named
access_key_ttl.jsonand host it at an accessible URL.{ "ttl_days": 30 } -
In your Terraform configuration, define a
datasource to read the JSON file from its URL.data "http" "access_key_ttl" { url = "https://example.com/access_key_ttl.json" } -
Configure the
aws_iam_access_keyresource to use thereplace_triggered_bymeta-argument. This tells Terraform to destroy and recreate the access key whenever the body of theaccess_key_ttl.jsonfile changes.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, ] } } -
Set up an external automation, such as a cron job or a scheduled CI/CD pipeline, to periodically update the value in the
access_key_ttl.jsonfile.When this external process updates the file, the
data.http.access_key_ttl.bodyvalue will change. During the nextterraform apply, Terraform will detect this change and trigger the replacement of theaws_iam_access_keyresource, effectively rotating the key.
Additional Information
- For more details on the
lifecycleblock and its arguments, refer to The lifecycle Meta-Argument documentation.