Rotate IAM Credentials Securely

Rotate IAM credentials securely — Cloud security essentials tutorial, lesson 30. Learn the core concept, step-by-step process, hands-on walkthrough, and troubleshooting tips to reduce security risks and prepare for the next lesson.

Focus: rotate iam credentials securely

Sponsored

Your AWS access keys are the crown jewels of your cloud account — and they sit in plain text on your laptop, in CI/CD pipelines, and in code repositories. A single leaked key can lead to a multi-million-dollar crypto mining bill or, worse, a full account takeover. In this lesson, you'll learn exactly how to rotate IAM credentials securely — a fundamental cloud security practice that limits the blast radius of compromised keys and keeps your infrastructure airtight. By the end, you'll not only understand the mechanics of key rotation but also be able to execute it hands-on with confidence.

The Problem This Lesson Solves

Every time you create an access key for an IAM user, you’re handing out a permanent passport to your AWS account. Unlike passwords, access keys are designed for programmatic access — they don’t expire unless you manually rotate them. If a key is exposed via a leaked environment variable or a public GitHub repo, an attacker gets unrestricted API access until you notice and revoke it.

The core problem: IAM access keys have no built-in expiration. Left untouched, a key from three years ago still works today, silently granting access to your S3 buckets, EC2 instances, and databases. The longer a key lives, the higher the chance of exposure and the larger the potential damage. A key rotated daily limits an attacker's window to minutes; a key rotated yearly leaves a massive opportunity.

Why care now? AWS shared responsibility model puts key management squarely on you. Cloud security essentials — like rotation — are the difference between a minor incident and a catastrophic breach.

Core Concept / Mental Model

Think of IAM credentials like the physical keys to your office building. You don’t use the same key forever — you change the locks regularly, especially after an employee leaves or a key goes missing. Rotation is the digital equivalent: you issue a new key, update all applications that use the old one, then deactivate and delete the old key.

Key terms you must know:

  • Access Key ID — a public identifier (e.g., AKIA...), not secret.
  • Secret Access Key — the secret paired with the key ID; treat it like a password.
  • Active / Inactive — a key can be made inactive without deleting it, which immediately blocks usage but preserves metadata.
  • Rotation window — the period where old and new keys coexist (e.g., 24 hours) to allow safe updates without downtime.

The mental model is a two-phase swap: create new → update apps → deactivate old → delete old. This minimizes disruption while ensuring no single key remains valid indefinitely.

How It Works Step by Step

The rotation process for IAM user credentials follows a predictable pattern. Here’s the high-level sequence, applicable to both the AWS Console and CLI:

  1. Create a new access key for the IAM user (you can have up to 2 active keys per user).
  2. Update all applications, scripts, and CI/CD pipelines to use the new key. This may involve updating environment variables, AWS credentials files, secrets managers like AWS Secrets Manager, or hardcoded configs.
  3. Deactivate the old access key — this prevents any new requests with the old key, but retains it for auditing.
  4. Wait for the rotation window — give your systems time to fully switch over. Verify that no application is still using the old key by checking CloudTrail for requests with the old key ID.
  5. Delete the old access key once you’re confident it’s no longer in use.

This approach ensures zero downtime — you never have a moment without valid credentials.

Pro tip: Always have exactly two keys per user during rotation. That’s why AWS limits you to two — it forces you to rotate, not stack.

Automating rotation

Manual rotation is error-prone and rare. In production, you should automate rotation using AWS Secrets Manager or custom scripts with the AWS CLI. The CLI method is the same procedure, but scriptable — we’ll practice that in the next section.

Hands-On Walkthrough

Let’s practice rotating IAM credentials securely using the AWS CLI. We’ll assume you have aws-cli configured with a profile that has permissions to manage IAM users (iam:CreateAccessKey, iam:UpdateAccessKey, iam:DeleteAccessKey). Replace YOUR_USER with your IAM username.

Step 1: List existing access keys

First, see what keys exist for the user:

aws iam list-access-keys --user-name YOUR_USER --output table

Example output:

-----------------------------------------------------------------------
|                        ListAccessKeys                               |
+---------------------------------------------------------------------+
||                          AccessKeyMetadata                        ||
|+---------+----------------------------+----------------------------+|
||  AccessKeyId   |   CreateDate         |  Status                     ||
|+---------+----------------------------+----------------------------+|
||  AKIAIOSFODNN7EXAMPLE | 2024-03-01T10:00:00Z | Active     ||
|+---------+----------------------------+----------------------------+|

Step 2: Create a new access key

aws iam create-access-key --user-name YOUR_USER

Output (store carefully):

{
    "AccessKey": {
        "UserName": "YOUR_USER",
        "AccessKeyId": "AKIAI44QH8DHBEXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "Status": "Active",
        "CreateDate": "2025-01-01T12:00:00Z"
    }
}

Critical: The SecretAccessKey is shown only once. Copy it immediately to a secure location (e.g., a password manager or AWS Secrets Manager). If you lose it, you must create another key.

Step 3: Update your applications

Now update any app that uses the old key. For example, if you use environment variables:

export AWS_ACCESS_KEY_ID=AKIAI44QH8DHBEXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

If you use the credentials file (~/.aws/credentials), edit it:

[my-profile]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

Step 4: Deactivate the old key

aws iam update-access-key --user-name YOUR_USER --access-key-id AKIAIOSFODNN7EXAMPLE --status Inactive

Step 5: Verify no usage and delete

Check CloudTrail for recent API calls using the old key ID. Then delete it:

aws iam delete-access-key --user-name YOUR_USER --access-key-id AKIAIOSFODNN7EXAMPLE

Confirm no keys remain active except the new one:

aws iam list-access-keys --user-name YOUR_USER --output table

A Python example for automation

You can script the entire rotation in Python using boto3. Here's a minimal version:

import boto3
from botocore.exceptions import ClientError

iam = boto3.client('iam')
user_name = 'YOUR_USER'

try:
    # 1. Create new key
    new_key = iam.create_access_key(UserName=user_name)['AccessKey']
    print(f"New key created: {new_key['AccessKeyId']}")

    # 2. Deactivate all existing active keys (except the new one)
    existing_keys = iam.list_access_keys(UserName=user_name)['AccessKeyMetadata']
    for key in existing_keys:
        if key['AccessKeyId'] != new_key['AccessKeyId'] and key['Status'] == 'Active':
            iam.update_access_key(UserName=user_name, AccessKeyId=key['AccessKeyId'], Status='Inactive')
            print(f"Deactivated: {key['AccessKeyId']}")

    # 3. In a real rotation, update secrets manager or env vars here
    # 4. After a grace period, delete all inactive keys
    # for key in existing_keys:
    #     if key['Status'] == 'Inactive':
    #         iam.delete_access_key(UserName=user_name, AccessKeyId=key['AccessKeyId'])

    print("Rotation initiated. Remember to update your apps and delete old keys after verification.")
except ClientError as e:
    print(f"Error: {e}")

Expected output (when run):

New key created: AKIAI44QH8DHBEXAMPLE
Deactivated: AKIAIOSFODNN7EXAMPLE
Rotation initiated. Remember to update your apps and delete old keys after verification.

Compare Options / When to Choose What

There's more than one way to rotate IAM credentials. Here's a comparison to help you decide:

Method Ease of Use Security Automation Best For
AWS Console (manual) High Medium (human errors) None Occasional one-off rotations
AWS CLI Medium Medium-High Scriptable Ad-hoc rotations, sysadmins
AWS Secrets Manager High High (built-in rotation) Fully automated Production workloads, compliance-driven environments
Custom Python/CLI scripts Low High (if done right) Fully automated Enterprises with complex policies

When to choose what:

  • Use the console for small teams or testing.
  • Use CLI to practice and understand the underlying steps.
  • Use Secrets Manager when you need automatic rotation for applications that read secrets from a central store — it can rotate keys on a schedule and update your apps without manual intervention.
  • Write custom scripts when you need multi-account rotation or precise control over the process.

Troubleshooting & Edge Cases

The secret access key is lost after creation

If you didn't save SecretAccessKey when it was created, you can't recover it. You must create a new key and go through rotation again. Mitigation: always store secrets in Secrets Manager immediately after creation — never wait.

Got "LimitExceeded" when creating a new key

IAM users can have at most two access keys. If you already have two active/inactive keys, you must delete one before creating a new one. This is a common mistake when keys are left inactive after a failed rotation.

Fix: list keys, remove any that are inactive and unused, or delete an old key you're ready to retire.

aws iam list-access-keys --user-name YOUR_USER
# Delete an unused key
aws iam delete-access-key --user-name YOUR_USER --access-key-id OLD_UNUSED_KEY

Applications fail after deactivating the old key

If you deactivate the old key too quickly, applications still using it get InvalidClientTokenId errors. Fix: always wait for the rotation window (e.g., 24 hours) and monitor CloudTrail for the old key ID before deleting. Use get-credential-report to see when each key was last used:

aws iam generate-credential-report
aws iam get-credential-report --query 'Content' --output text | base64 -d | cut -d, -f1,4,5,9,14 | column -t -s,

Using the old key in CI/CD pipeline after rotation

Pipelines store keys as environment variables. If you forget to update them, they still reference the old inactive key. Always grep your codebase and CI configs for the old key ID before deactivating:

grep -r "AKIAIOSFODNN7EXAMPLE" .

Deleted keys appear in CloudTrail

Even after deletion, CloudTrail logs will show the old key ID in events. This is normal — retention is good for auditing. The key is unusable, but the logs remain for compliance.

What You Learned & What's Next

In this lesson, you learned why Rotate IAM credentials securely is a critical cloud security practice. You now understand the mental model of a two-phase swap, can execute the rotation using the AWS CLI or a Python script, and know how to choose between manual, scripted, and fully automated methods like Secrets Manager. You also know how to troubleshoot common issues like key limits and application disruptions.

Key objectives met:

  • You can explain the core idea behind rotating IAM credentials securely: reduce blaster radius by regularly replacing keys.
  • You completed a practical exercise to rotate a key safely.

What's next: In the next lesson, we'll dive deeper into automating credential management with AWS Secrets Manager, including how to set up automatic rotation schedules and integrate with your applications. This builds directly on what you've learned today — taking rotation from a manual chore to a hands-off policy.

Keep your keys fresh, and your cloud will stay safe!

Practice recap

Mini exercise: In a test AWS account, create a temporary IAM user with only S3 read-only permissions. Rotate its keys manually using the AWS CLI, ensuring you save the new secret key, update a dummy environment variable, deactivate the old key, and then — after a 10-minute wait — delete the old key and confirm no active keys exist except the new one.

Common mistakes

  • Deleting the old key immediately after creating a new one, without updating applications — this causes immediate outages.
  • Failing to save the SecretAccessKey at creation; it is only shown once
  • Hitting the 2-key limit because inactive keys are never deleted
  • Skpping the deactivation step and going straight to deletion, which removes risk of verifying usage
  • Not checking if CI/CD or stored secrets still reference the old key before deactivating

Variations

  1. Using AWS Secrets Manager for automatic rotation with a Lambda-backed rotation schedule
  2. Using infrastructure-as-code (Terraform/CloudFormation) to rotate keys as part of resource lifecycle
  3. Implementing a custom rotation script in Python/CLI for multi-account orchestration

Real-world use cases

  • A startup rotates IAM keys every 90 days for all developer accounts to comply with internal security policy, reducing risk of key leaks from personal devices
  • An e-commerce platform uses Secrets Manager to rotate database IAM credentials automatically, seamlessly updating its microservices without downtime
  • A security auditor rotates a compromised key after detecting it in a public GitHub repo, restricting attacker access within minutes

Key takeaways

  • IAM access keys have no built-in expiration — rotation is your only defense against long-lived, leaked keys
  • The rotation process: create, update, deactivate, verify, delete — in that order
  • The two-key limit per IAM user is by design to force rotation, not to stack keys
  • Always store new secret keys securely and immediately, as they are shown only once
  • Automation via Secrets Manager or scripts prevents human error and ensures rotation happens consistently
  • Always verify old-key usage via CloudTrail before deletion to avoid breaking applications

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.