Skip to content

Instantly share code, notes, and snippets.

@scarbeau
Last active December 20, 2021 15:46
Show Gist options
  • Save scarbeau/dfe7c0bd94bed6289c9bedfe51b5e6df to your computer and use it in GitHub Desktop.
Save scarbeau/dfe7c0bd94bed6289c9bedfe51b5e6df to your computer and use it in GitHub Desktop.
Terraform AWS Access Key Rotation
resource "aws_iam_user" "monthly_credential_rotation_example" {
provider = aws.local
name = "monthly-credential-rotation-example"
}
resource "aws_iam_access_key" "one" {
provider = aws.local
count = local.modmonth == 0 ? 1 : 0
user = aws_iam_user.monthly_credential_rotation_example.name
}
resource "aws_iam_access_key" "two" {
provider = aws.local
count = local.modmonth == 1 ? 1 : 0
user = aws_iam_user.monthly_credential_rotation_example.name
}
data "external" "modulo_month" {
program = ["/bin/sh", "-c", "echo '{\"value\": \"'$(expr $(date '+%m') % 2)'\"}'"]
}
locals {
modmonth = tonumber(data.external.modulo_month.result.value)
}
output "accesskeyid" {
value = try(aws_iam_access_key.one[0].id, aws_iam_access_key.two[0].id)
}
output "secretaccesskey" {
value = try(aws_iam_access_key.one[0].secret, aws_iam_access_key.two[0].secret)
}
@pjaudiomv
Copy link

looks good, instead of using an external data source you could also just use built in TF date functions

ex.

locals {
  modmonth = formatdate("M", timestamp()) % 2
}

@pjaudiomv
Copy link

pjaudiomv commented Dec 20, 2021

ahh nevermind, I guess you can't. and im guessing you found that out already :(. Because of use of the timestamp function as described here https://www.terraform.io/language/expressions/function-calls#when-terraform-calls-functions

@scarbeau
Copy link
Author

Yeah, terraform needs to resolve the count values in the plan so it has to be in a data source rather than a timestamp function in locals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment