AWS CDK AWS IAM Construct Library (v1)
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
-
Unable to resolve AWS account for the stack. This usually happens when you don't specify 'env' for your stack. For example: new MyStack(app, 'MyStack', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION } });cause The CDK CLI or application cannot determine which AWS account and region to deploy to, often due to missing environment variables or explicit `env` properties on the stack. This is common when switching authentication methods (e.g., from IAM user to OIDC role).fixExplicitly define the `env` property for your stacks using environment variables (`os.environ.get('CDK_DEFAULT_ACCOUNT', '')`, `os.environ.get('CDK_DEFAULT_REGION', '')`) or by passing them directly. Ensure your AWS CLI credentials are correctly configured and accessible by the CDK application. -
AccessDeniedException: User: arn:aws:iam::123456789012:user/MyUser is not authorized to perform: s3:PutObject on resource: arn:aws:s3:::cdk-123456789012-assets-us-east-1/...
cause The IAM principal (user or role) attempting to deploy the CDK stack lacks the necessary permissions to create or modify AWS resources, particularly the S3 bucket used by CDK for asset staging or the CloudFormation execution role.fixEnsure the IAM principal has sufficient permissions. For deployments involving assets, verify write access to the CDK Toolkit's asset S3 bucket. For full stack deployments, the CloudFormation execution role needs permissions to manage all resources defined in the stack. Consider re-bootstrapping your environment if using v2. -
The CloudFormation template contains too many resources. (Maximum: 500 resources)
cause The synthesized CloudFormation template exceeds the maximum allowed size (50KB) or resource count (500 resources for most regions).fixBreak down large CDK applications into smaller, modular stacks. For templates larger than 50KB, ensure your environment is bootstrapped, as CDK will upload the template to S3. Consider using higher-level constructs or patterns to reduce the number of underlying CloudFormation resources. -
The resource with name 'MyResource' already exists.
cause You are attempting to create an AWS resource with a fixed, explicit name that already exists in your AWS account, outside of or within another CloudFormation stack.fixAvoid assigning explicit `resourceName` properties to constructs that might conflict with existing resources. Allow CDK to generate unique logical IDs. If you need to manage an existing resource, use `from_xxx_name` or `from_xxx_arn` methods to import it into your stack, or use `cdk import` functionality.
Warnings
- breaking AWS CDK v1, including `aws-cdk-aws-iam` version 1.204.0, reached End-of-Support on June 1, 2023. It no longer receives maintenance, updates, patches, or technical support. Continuing to use v1 exposes your infrastructure to potential security vulnerabilities and unaddressed bugs. Migration to AWS CDK v2 is strongly recommended.
- breaking Migrating from AWS CDK v1 to v2 requires significant changes to import statements. Individual construct libraries (like `aws_iam`) are consolidated under the `aws-cdk-lib` package in v2.
- breaking AWS CDK v2 requires environments to be bootstrapped with the modern bootstrap stack. The legacy v1 bootstrap stack is no longer supported. This can impact deployment permissions for assets.
- gotcha Granting overly permissive IAM permissions (e.g., using `*` for actions or resources) violates the principle of least privilege, creating security vulnerabilities.
- gotcha Hardcoding IAM resource names (e.g., policy names, role names) can lead to deployment failures and unrecoverable errors, especially when reusing templates across regions or refactoring.
Install
-
pip install aws-cdk.aws-iam==1.204.0 -
npm install -g aws-cdk
Imports
- aws_iam
import aws_cdk.aws_iam
from aws_cdk import aws_iam as iam
- Role
from aws_cdk.aws_iam import Role, ServicePrincipal, PolicyStatement
Quickstart
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()