IAM Access Keys, even when securely stored (such as in environment variables), due to their long-lived nature, remain active and valid until manually rotated or revoked. This poses a security risk as they provide continuous access if compromised.
import boto3
import os
# Long-lived credentials stored in environment variables
aws_access_key_id = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY')
# Initialize S3 client with long-lived credentials
client = boto3.client(
's3',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key
)
# List S3 buckets
response = client.list_buckets()
print("S3 Buckets:", response['Buckets'])
The more secure approach is to use ephemeral credentials through AWS IAM roles. These credentials are short-lived and dynamically generated, limiting their validity. Even if compromised, they are only valid for a short time, drastically reducing the risk window.
To convert an IAM access key to a role in AWS, you first create an IAM role with the necessary permissions that match the original access key's usage.
You then update any applications or services to use the STS AssumeRole API, which allows them to assume the role and obtain temporary credentials instead of using long-term access keys.
Once the applications are successfully configured to use the role, you deactivate and delete the old access keys associated with the IAM user, improving security by using short-lived credentials and following best practices for AWS identity and access management.
import boto3
# Assume an IAM role to obtain ephemeral credentials
sts_client = boto3.client('sts')
response = sts_client.assume_role(
RoleArn='arn:aws:iam::123456789012:role/YourRoleName',
RoleSessionName='SessionName'
)
# Extract temporary credentials
credentials = response['Credentials']
# Use ephemeral credentials for the S3 client
client = boto3.client(
's3',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
# List S3 buckets
response = client.list_buckets()
print("S3 Buckets:", response['Buckets'])
Basically when a resource in one AWS account (Like EC2, Lambda Function, ECS Task, etc) wants to have access to a resource on another account it can “Assume” a role instead of using an long lived Access Key.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS":
"arn:aws:iam::123456789012:root"
},
"Action": "sts:AssumeRole"
}
]
}
This policy allows the role to be assumed by users or services from the specified account (123456789012 in this case) or specific AWS services.
You need to basically copy all of the policies attached to the IAM User that generated the IAM access key that you would like to convert and attach them to the new role that you are converting it to