IAM Group Examples in AWS CDK - Complete Guide

avatar

Borislav Hadzhiev

Wed Apr 28 20214 min read

banner

Photo by Anson Antony

A complete example of creating and managing IAM Groups in AWS CDK.

Table of Contents #

  1. IAM Group Examples in AWS CDK
  2. Attaching Policies to a Group in AWS CDK
  3. Adding a User to a Group in AWS CDK

IAM Group Examples in AWS CDK #

An IAM Group is a collection of users. Groups enable us to reuse common permissions, by attaching permissions on the group, rather than on each individual user.

In order to create groups in AWS CDK, we have to instantiate the Group class.

The code for this article is available on GitHub

Let's start by creating a simple IAM group with a managed policy:

lib/cdk-starter-stack.ts
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';

export class CdkStarterStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // ๐Ÿ‘‡ create an IAM group
    const group = new iam.Group(this, 'group-id', {
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEC2ReadOnlyAccess'),
      ],
    });

    console.log('group name ๐Ÿ‘‰', group.groupName);
    console.log('group arn ๐Ÿ‘‰', group.groupArn);
  }
}

In the code snippet we instantiated the Group class. The constructor method of the class takes 3 parameters:

  • groupName - a name for the group. In our case we didn't specify one, because by default CDK will generate a unique group name for us.
  • managedPolicies - a list of managed policies to associate to the group. In our case, we used an AWS managed policy, that grants EC2 read permissions.
  • path - the path to the group - defaults to /.

The values for the groupName and groupArn are tokens at synthesis time, so we can't use them in conditionals:

group tokens

Tokens are encoded values that get resolved at deployment time by CloudFormation.

Let's execute a deployment:

shell
npx cdk deploy

If we look at the group in the IAM console, we can see that the managed policy has been attached to it:

group policy attached

Attaching Policies to a Group in AWS CDK #

We can attach a policy to a Group in CDK, by using the following methods:

The code for this article is available on GitHub

Let's look at an example of all 3 methods:

lib/cdk-starter-stack.ts
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';

export class CdkStarterStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // ... rest

      // ๐Ÿ‘‡ attach a managed policy to the group
    group.addManagedPolicy(
      iam.ManagedPolicy.fromAwsManagedPolicyName(
        'service-role/AWSLambdaBasicExecutionRole',
      ),
    );

    // ๐Ÿ‘‡ add an inline policy to the group
    group.addToPolicy(
      new iam.PolicyStatement({
        actions: ['logs:CreateLogGroup', 'logs:CreateLogStream'],
        resources: ['*'],
      }),
    );

    // ๐Ÿ‘‡ attach an inline policy on the group
    group.attachInlinePolicy(
      new iam.Policy(this, 'cw-logs', {
        statements: [
          new iam.PolicyStatement({
            effect: iam.Effect.DENY,
            actions: ['logs:PutLogEvents'],
            resources: ['*'],
          }),
        ],
      }),
    );
  }
}

In the code snippet we've used the addManagedPolicy, addToPolicy and attachInlinePolicy methods on an instance of the Group class.

  • addManagedPolicy - takes a single parameter - an IAM managed policy

  • addToPolicy - takes a PolicyStatement instance as a parameter

  • attachInlinePolicy takes a Policy instance as a parameter

Let's execute a deployment:

shell
npx cdk deploy

If we take a look at the group in the IAM console, we can see that it now has 4 permission policies attached:

group policies attached

Adding a User to a Group in AWS CDK #

In order to add a user to a group in AWS CDK, we have to use the addUser method on an instance of the Group class.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';

export class CdkStarterStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // ... rest

    // ๐Ÿ‘‡ create IAM User
    const user = new iam.User(this, 'user-id');

    // ๐Ÿ‘‡ add the User to the group
    group.addUser(user);
  }
}

In the code snippet we created an IAM user and added it to a group.

Let's deploy the changes:

shell
npx cdk deploy

If we look at the Users section of our group, we can see that the user we created has been added:

user in group

Import an Existing Group in AWS CDK #

In order to import an existing group in a CDK stack, we have to use the fromGroupArn static method on Group class.

lib/cdk-starter-stack.ts
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';

export class CdkStarterStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // ... rest

    // ๐Ÿ‘‡ import existing Group
    const externalGroup = iam.Group.fromGroupArn(
      this,
      'external-group-id',
      `arn:aws:iam::${cdk.Stack.of(this).account}:group/YOUR_GROUP_NAME`,
    );
  }
}

In the code snippet we used the fromGroupArn static method on the Group class to import an existing group. The third parameter the method takes is the ARN of the group.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee