Skip to content

Instantly share code, notes, and snippets.

@BDF
Created March 13, 2023 14:00
Show Gist options
  • Save BDF/f94f242b2b42366ea2115439d01c5a7b to your computer and use it in GitHub Desktop.
Save BDF/f94f242b2b42366ea2115439d01c5a7b to your computer and use it in GitHub Desktop.
Sample typescript code for creating an AWS user with cluster access.
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import {Role, ServicePrincipal, PolicyStatement, User, PolicyDocument, Policy} from 'aws-cdk-lib/aws-iam';
/**
* Create an AWS IAM user with access (DescribeCluster, ListClusters, ListTagsForResource)
* to named cluster.
* Warning: minimal testing so far, 2023-03-13
*/
export class CreateIAMUserWithClusterAccessStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const clusterName = 'example-cluster';
const userName = 'example-user';
// Create a new IAM role for the user
const role = new Role(this, 'example-cluster-role', {
assumedBy: new ServicePrincipal('sts.amazonaws.com'),
});
// Grant the necessary permissions to the role
const statement = new PolicyStatement({
actions: [
'eks:DescribeCluster',
'eks:ListClusters',
'eks:ListTagsForResource'
],
resources: [`arn:aws:eks:*:*:cluster/${clusterName}`],
});
const policyDocument = new PolicyDocument({
statements: [statement],
});
role.addToPolicy(statement);
const policy = new Policy(this, 'ExamplePolicy', {
document: policyDocument,
});
// Create a new IAM user and attach the role to it
const user = new User(this, userName);
user.attachInlinePolicy(policy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment