Skip to content

Instantly share code, notes, and snippets.

@denzhel
Created August 10, 2022 17:52
Show Gist options
  • Save denzhel/62855033f8eca2c772660659c6812929 to your computer and use it in GitHub Desktop.
Save denzhel/62855033f8eca2c772660659c6812929 to your computer and use it in GitHub Desktop.
rotate iam user key with terraform
# create a pair of access key id and access secret key for the user above
resource "aws_iam_access_key" "active" {
  user   = aws_iam_user.travis_ci.name
  status = "Active"
}
# create a pair of rotated access key id and access secret key for the user above
resource "aws_iam_access_key" "rotated" {
  count = var.key_rotation ? 1 : 0
  user  = aws_iam_user.travis_ci.name
}
awslocal iam list-access-keys --user-name travis-ci

{
    "AccessKeyMetadata": [
        {
            "UserName": "travis-ci",
            "AccessKeyId": "AKIAOTGGDMT2I22J7KAD",
            "Status": "Active",
            "CreateDate": "2022-08-10T06:20:48+00:00"
        }
    ]
}
tf state show aws_iam_access_key.active 
# aws_iam_access_key.active:
resource "aws_iam_access_key" "active" {
    create_date          = "2022-08-10T06:20:48Z"
    id                   = "AKIAOTGGDMT2I22J7KAD"
    secret               = (sensitive value)
    ses_smtp_password_v4 = (sensitive value)
    status               = "Active"
    user                 = "travis-ci"
}
tfa -var key_rotation=true                         
awslocal iam list-access-keys --user-name travis-ci
{
    "AccessKeyMetadata": [
        {
            "UserName": "travis-ci",
            "AccessKeyId": "AKIAOTGGDMT2I22J7KAD",
            "Status": "Active",
            "CreateDate": "2022-08-10T06:20:48+00:00"
        },
        {
            "UserName": "travis-ci",
            "AccessKeyId": "AKIAE7N5XAWD6P0KUQ35",
            "Status": "Active",
            "CreateDate": "2022-08-10T06:27:00+00:00"
        }
    ]
}

Change the key to status = "Inactive" and run apply again

tfa -var key_rotation=true                         
tfd -target='aws_iam_access_key.active'
tf state mv 'aws_iam_access_key.rotated[0]' aws_iam_access_key.active
Move "aws_iam_access_key.rotated[0]" to "aws_iam_access_key.active"
Successfully moved 1 object(s).
tfa
aws_iam_user.travis_ci: Refreshing state... [id=travis-ci]
aws_iam_access_key.active: Refreshing state... [id=AKIAE7N5XAWD6P0KUQ35]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment