Home > OS >  How do I rotate my AWS IAM user access and secret key using boto3?
How do I rotate my AWS IAM user access and secret key using boto3?

Time:10-13

We are using the Python AWS SDK (boto3) to connect to S3.

We have a static access and secret token, however my network is not safe.

I can't use another network for sending requests so is there a way to change the access and secret keys after every request?

I can save a new token in a safe database for sending another request but it's important that after using the token, it expires.

What I'm looking for:

send: curl https://aws.endpoint/refresh/token
response: {“new_access_token”:”blablabla”, “new_secret_token”:”blablablabla”}

CodePudding user response:

If you must, you can rotate your keys using a combination of iam.create_access_key, iam.get_access_key_last_used, iam.update_access_key & iam.delete_access_key API actions.

Keep in mind you can only have a maximum of 2 access keys per user so you will have to create a new one using create_access_key, disable/make inactive the current (old) one (get_access_key_last_used & update_access_key), change your access key to the next one within the application code, and then finally delete the current one delete_access_key.


However, AWS access keys are meant to be long-term credentials for an IAM user or the AWS account root user; you can rotate them on a regular basis but I wouldn't be doing that in the first place in this scenario.

Your optimal solution will depend on the service you are using.

If using EC2 instances to call S3, for example, don't use/embed/pass/read access keys but instead use shortlived temporary security credentials that would be provided by launching the EC2 instance with a role for S3 access.

If you're using this script locally, you can use AWS Security Token Service (AWS STS) that enables you to request temporary, limited-privilege credentials for AWS IAM users/federated users (single sign-on etc.). You'd be looking for the GetSessionToken API operation (Boto3 SDK docs here).

In both cases, the credentials include a security token that indicates when the credentials expire & they are short-lived on purpose to help reduce your risk in case credentials are accidentally exposed.

Read: Best practices for managing AWS access keys

  • Related