Create AWS access key and secret access key for an IAM user

Create AWS access key and secret access key for an IAM user - AWS CDK

IAM is an essential part of how you interact with AWS and how AWS services interact with each other. When working solely with AWS services, good security practices dictate that you should create IAM roles and “assume” them.

However, this only works when AWS services interact with other AWS services. AWS services can assume IAM roles (granted you allow them to).

If we are talking about legacy apps that are running outside of AWS and want to communicate with AWS, IAM roles are not a possibility. You have to resort to generating IAM access key and secret access key and embed them within the application (e.g. as environment variables). The same is also true if you want “your computer” to communicate with the AWS account.

Luckily, AWS CDK makes it easy to programmatically generate such keys and rotate them as needed (which is useful from a security perspective – regular rotation of such keys is recommended).

Let’s start by creating an IAM user within the AWS account:

import {User} from '@aws-cdk/aws-iam'
const user = new User(this, 'User', {})

The next step is to create the access key and secret access key combination for this user:

const accessKey = new CfnAccessKey(this, 'CfnAccessKey', {
userName: user.userName,

Since there is no L2 construct for this, we resort to using Cfn constructs, but that’s fine for such a trivial example.

Now, how do we get AWS CDK to provide us with these values? One option is to use Outputs:

new CfnOutput(this, 'accessKeyId', {value: accessKey.ref});
new CfnOutput(this, 'secretAccessKey', {value: accessKey.attrSecretAccessKey});

Happy coding!

Need help? Get in touch