AWS CDK AWS IAM Construct Library (v1)

1.204.0 · deprecated · verified Thu Apr 16

The `aws-cdk-aws-iam` package provides a set of AWS Cloud Development Kit (CDK) constructs for defining and managing AWS Identity and Access Management (IAM) resources in Python. It simplifies the process of creating IAM roles, users, groups, and policies, and assigning granular permissions to other AWS resources. This particular version, 1.204.0, belongs to AWS CDK v1, which reached End-of-Support on June 1, 2023. While still functional, it no longer receives updates, patches, or technical support. AWS CDK (v2) generally follows a weekly release cadence for new features and bug fixes, with critical maintenance releases as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an IAM role for a Lambda function with specific S3 read permissions and how to create an IAM user and attach an AWS managed policy. This code should be placed within an AWS CDK application structure (e.g., `app.py` or a stack file) and assumes you have the AWS CDK CLI and credentials configured. Remember to replace 'my-bucket' with an actual S3 bucket name or dynamic reference. Ensure `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables are set for non-environment-agnostic deployments.

import os
from aws_cdk import (
    Stack,
    App,
    aws_iam as iam
)

class MyIamStack(Stack):
    def __init__(self, scope: App, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Define an IAM Role for a Lambda function
        lambda_role = iam.Role(
            self,
            "MyLambdaRole",
            assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
        )

        # Add a policy statement to grant S3 read access
        lambda_role.add_to_policy(
            iam.PolicyStatement(
                actions=["s3:GetObject", "s3:ListBucket"],
                resources=["arn:aws:s3:::my-bucket/*", "arn:aws:s3:::my-bucket"]
            )
        )

        # Define an IAM User
        my_user = iam.User(self, "MyCdkUser")

        # Attach an AWS managed policy to a user
        my_user.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("ReadOnlyAccess")
        )

app = App()
MyIamStack(app, "MyIamStack",
           env={'account': os.environ.get('CDK_DEFAULT_ACCOUNT', os.environ.get('AWS_ACCOUNT_ID', '')),
                'region': os.environ.get('CDK_DEFAULT_REGION', os.environ.get('AWS_REGION', ''))})
app.synth()

view raw JSON →