Show / Hide Table of Contents

Namespace Amazon.CDK.AWS.IAM

AWS Identity and Access Management Construct Library

--- cfn-resources: Stable cdk-constructs: Stable

Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:

// Example automatically generated. See https://github.com/aws/jsii/issues/826
Role role = new Role(this, "MyRole", new RoleProps {
    AssumedBy = new ServicePrincipal("sns.amazonaws.com")
});

role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Resources = new [] { "*" },
    Actions = new [] { "lambda:InvokeFunction" }
}));

Define a policy and attach it to groups, users and roles. Note that it is possible to attach the policy either by calling xxx.attachInlinePolicy(policy) or policy.attachToXxx(xxx).

// Example automatically generated. See https://github.com/aws/jsii/issues/826
User user = new User(this, "MyUser", new UserProps { Password = SecretValue.PlainText("1234") });
Group group = new Group(this, "MyGroup");

Policy policy = new Policy(this, "MyPolicy");
policy.AttachToUser(user);
group.AttachInlinePolicy(policy);

Managed policies can be attached using xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName)):

// Example automatically generated. See https://github.com/aws/jsii/issues/826
Group group = new Group(this, "MyGroup");
group.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AdministratorAccess"));

Granting permissions to resources

Many of the AWS CDK resources have grant* methods that allow you to grant other resources access to that resource. As an example, the following code gives a Lambda function write permissions (Put, Update, Delete) to a DynamoDB table.

// Example automatically generated. See https://github.com/aws/jsii/issues/826
Function fn = new Function(this, "Function", functionProps);
Table table = new Table(this, "Table", tableProps);

table.GrantWriteData(fn);

The more generic grant method allows you to give specific permissions to a resource:

// Example automatically generated. See https://github.com/aws/jsii/issues/826
Function fn = new Function(this, "Function", functionProps);
Table table = new Table(this, "Table", tableProps);

table.Grant(fn, "dynamodb:PutItem");

The grant* methods accept an IGrantable object. This interface is implemented by IAM principlal resources (groups, users and roles) and resources that assume a role such as a Lambda function, EC2 instance or a Codebuild project.

You can find which grant* methods exist for a resource in the AWS CDK API Reference.

Roles

Many AWS resources require Roles to operate. These Roles define the AWS API calls an instance or other AWS service is allowed to make.

Creating Roles and populating them with the right permissions Statements is a necessary but tedious part of setting up AWS infrastructure. In order to help you focus on your business logic, CDK will take care of creating roles and populating them with least-privilege permissions automatically.

All constructs that require Roles will create one for you if don't specify one at construction time. Permissions will be added to that role automatically if you associate the construct with other constructs from the AWS Construct Library (for example, if you tell an AWS CodePipeline to trigger an AWS Lambda Function, the Pipeline's Role will automatically get lambda:InvokeFunction permissions on that particular Lambda Function), or if you explicitly grant permissions using grant functions (see the previous section).

Opting out of automatic permissions management

You may prefer to manage a Role's permissions yourself instead of having the CDK automatically manage them for you. This may happen in one of the following cases:

    To prevent constructs from updating your Role's policy, pass the object returned by myRole.withoutPolicyUpdates() instead of myRole itself.

    For example, to have an AWS CodePipeline not automatically add the required permissions to trigger the expected targets, do the following:

    // Example automatically generated. See https://github.com/aws/jsii/issues/826
    Role role = new Role(this, "Role", new RoleProps {
        AssumedBy = new ServicePrincipal("codepipeline.amazonaws.com"),
        // custom description if desired
        Description = "This is a custom role..."
    });
    
    new Pipeline(this, "Pipeline", new PipelineProps {
        // Give the Pipeline an immutable view of the Role
        Role = role.WithoutPolicyUpdates()
    });
    
    // You now have to manage the Role policies yourself
    role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
        Actions = new [] {  },
        Resources = new [] {  }
    }));

    Using existing roles

    If there are Roles in your account that have already been created which you would like to use in your CDK application, you can use Role.fromRoleArn to import them, as follows:

    // Example automatically generated. See https://github.com/aws/jsii/issues/826
    IRole role = Role.FromRoleArn(this, "Role", "arn:aws:iam::123456789012:role/MyExistingRole", new FromRoleArnOptions {
        // Set 'mutable' to 'false' to use the role as-is and prevent adding new
        // policies to it. The default is 'true', which means the role may be
        // modified as part of the deployment.
        Mutable = false
    });

    Configuring an ExternalId

    If you need to create Roles that will be assumed by third parties, it is generally a good idea to require an ExternalId to assume them. Configuring an ExternalId works like this:

    // Example automatically generated. See https://github.com/aws/jsii/issues/826
    Role role = new Role(this, "MyRole", new RoleProps {
        AssumedBy = new AccountPrincipal("123456789012"),
        ExternalIds = new [] { "SUPPLY-ME" }
    });

    Principals vs Identities

    When we say Principal, we mean an entity you grant permissions to. This entity can be an AWS Service, a Role, or something more abstract such as "all users in this account" or even "all users in this organization". An Identity is an IAM representing a single IAM entity that can have a policy attached, one of Role, User, or Group.

    IAM Principals

    When defining policy statements as part of an AssumeRole policy or as part of a resource policy, statements would usually refer to a specific IAM principal under Principal.

    IAM principals are modeled as classes that derive from the iam.PolicyPrincipal abstract class. Principal objects include principal type (string) and value (array of string), optional set of conditions and the action that this principal requires when it is used in an assume role policy document.

    To add a principal to a policy statement you can either use the abstract statement.addPrincipal, one of the concrete addXxxPrincipal methods:

      If multiple principals are added to the policy statement, they will be merged together:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      PolicyStatement statement = new PolicyStatement();
      statement.AddServicePrincipal("cloudwatch.amazonaws.com");
      statement.AddServicePrincipal("ec2.amazonaws.com");
      statement.AddArnPrincipal("arn:aws:boom:boom");

      Will result in:

      {
        "Principal": {
          "Service": [ "cloudwatch.amazonaws.com", "ec2.amazonaws.com" ],
          "AWS": "arn:aws:boom:boom"
        }
      }

      The CompositePrincipal class can also be used to define complex principals, for example:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      Role role = new Role(this, "MyRole", new RoleProps {
          AssumedBy = new CompositePrincipal(
          new ServicePrincipal("ec2.amazonaws.com"),
          new AccountPrincipal("1818188181818187272"))
      });

      The PrincipalWithConditions class can be used to add conditions to a principal, especially those that don't take a conditions parameter in their constructor. The principal.withConditions() method can be used to create a PrincipalWithConditions from an existing principal, for example:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      IPrincipal principal = new AccountPrincipal("123456789000").WithConditions(new Dictionary<string, object> { { "StringEquals", new Struct { Foo = "baz" } } });
      NOTE: If you need to define an IAM condition that uses a token (such as a
      deploy-time attribute of another resource) in a JSON map key, use <code>CfnJson</code> to
      render this condition. See <a href="./test/integ-condition-with-ref.ts">this test</a> for
      an example.
      

      The WebIdentityPrincipal class can be used as a principal for web identities like Cognito, Amazon, Google or Facebook, for example:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      IPrincipal principal = new WebIdentityPrincipal("cognito-identity.amazonaws.com").WithConditions(new Dictionary<string, object> {
          { "StringEquals", new Struct { Cognito-identity.amazonaws.com:aud = "us-east-2:12345678-abcd-abcd-abcd-123456" } },
          { "ForAnyValue:StringLike", new Struct { Cognito-identity.amazonaws.com:amr = "unauthenticated" } }
      });

      Parsing JSON Policy Documents

      The PolicyDocument.fromJson and PolicyStatement.fromJson static methods can be used to parse JSON objects. For example:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      __object policyDocument = new Dictionary<string, object> {
          { "Version", "2012-10-17" },
          { "Statement", new [] { new Dictionary<string, object> {
              { "Sid", "FirstStatement" },
              { "Effect", "Allow" },
              { "Action", new [] { "iam:ChangePassword" } },
              { "Resource", "*" }
          }, new Dictionary<string, string> {
              { "Sid", "SecondStatement" },
              { "Effect", "Allow" },
              { "Action", "s3:ListAllMyBuckets" },
              { "Resource", "*" }
          }, new Dictionary<string, object> {
              { "Sid", "ThirdStatement" },
              { "Effect", "Allow" },
              { "Action", new [] { "s3:List*", "s3:Get*" } },
              { "Resource", new [] { "arn:aws:s3:::confidential-data", "arn:aws:s3:::confidential-data/*" } },
              { "Condition", new Dictionary<string, IDictionary<string, string>> { { "Bool", new Dictionary<string, string> { { "aws:MultiFactorAuthPresent", "true" } } } } }
          } } }
      };
      
      PolicyDocument customPolicyDocument = PolicyDocument.FromJson(policyDocument);
      
      // You can pass this document as an initial document to a ManagedPolicy
      // or inline Policy.
      var newManagedPolicy = new ManagedPolicy(stack, "MyNewManagedPolicy", new Struct {
          Document = customPolicyDocument
      });
      var newPolicy = new Policy(stack, "MyNewPolicy", new Struct {
          Document = customPolicyDocument
      });

      Permissions Boundaries

      Permissions Boundaries can be used as a mechanism to prevent privilege esclation by creating new Roles. Permissions Boundaries are a Managed Policy, attached to Roles or Users, that represent the maximum set of permissions they can have. The effective set of permissions of a Role (or User) will be the intersection of the Identity Policy and the Permissions Boundary attached to the Role (or User). Permissions Boundaries are typically created by account Administrators, and their use on newly created Roles will be enforced by IAM policies.

      It is possible to attach Permissions Boundaries to all Roles created in a construct tree all at once:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      // This imports an existing policy.
      IManagedPolicy boundary = ManagedPolicy.FromManagedPolicyArn(this, "Boundary", "arn:aws:iam::123456789012:policy/boundary");
      
      // This creates a new boundary
      ManagedPolicy boundary2 = new ManagedPolicy(this, "Boundary2", new ManagedPolicyProps {
          Statements = new [] {
              new PolicyStatement(new PolicyStatementProps {
                  Effect = Effect.DENY,
                  Actions = new [] { "iam:*" },
                  Resources = new [] { "*" }
              }) }
      });
      
      // Directly apply the boundary to a Role you create
      PermissionsBoundary.Of(role).Apply(boundary);
      
      // Apply the boundary to an Role that was implicitly created for you
      PermissionsBoundary.Of(lambdaFunction).Apply(boundary);
      
      // Apply the boundary to all Roles in a stack
      PermissionsBoundary.Of(stack).Apply(boundary);
      
      // Remove a Permissions Boundary that is inherited, for example from the Stack level
      PermissionsBoundary.Of(customResource).Clear();

      OpenID Connect Providers

      OIDC identity providers are entities in IAM that describe an external identity provider (IdP) service that supports the OpenID Connect (OIDC) standard, such as Google or Salesforce. You use an IAM OIDC identity provider when you want to establish trust between an OIDC-compatible IdP and your AWS account. This is useful when creating a mobile app or web application that requires access to AWS resources, but you don't want to create custom sign-in code or manage your own user identities. For more information about this scenario, see [About Web Identity Federation] and the relevant documentation in the [Amazon Cognito Identity Pools Developer Guide].

      The following examples defines an OpenID Connect provider. Two client IDs (audiences) are will be able to send authentication requests to https://openid/connect.

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      OpenIdConnectProvider provider = new OpenIdConnectProvider(this, "MyProvider", new OpenIdConnectProviderProps {
          Url = "https://openid/connect",
          ClientIds = new [] { "myclient1", "myclient2" }
      });

      You can specify an optional list of thumbprints. If not specified, the thumbprint of the root certificate authority (CA) will automatically be obtained from the host as described here.

      Once you define an OpenID connect provider, you can use it with AWS services that expect an IAM OIDC provider. For example, when you define an Amazon Cognito identity pool you can reference the provider's ARN as follows:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      new CfnIdentityPool(this, "IdentityPool", new CfnIdentityPoolProps {
          OpenIdConnectProviderArns = new [] { myProvider.OpenIdConnectProviderArn },
          // And the other properties for your identity pool
          AllowUnauthenticatedIdentities = allowUnauthenticatedIdentities
      });

      The OpenIdConnectPrincipal class can be used as a principal used with a OpenIdConnectProvider, for example:

      // Example automatically generated. See https://github.com/aws/jsii/issues/826
      OpenIdConnectProvider provider = new OpenIdConnectProvider(this, "MyProvider", new OpenIdConnectProviderProps {
          Url = "https://openid/connect",
          ClientIds = new [] { "myclient1", "myclient2" }
      });
      OpenIdConnectPrincipal principal = new OpenIdConnectPrincipal(provider);

      Users

      IAM manages users for your AWS account. To create a new user:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      var user = new User(this, "MyUser");

      To import an existing user by name with path:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      var user = User.FromUserName(stack, "MyImportedUserByName", "johnsmith");

      To import an existing user by ARN:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      var user = User.FromUserArn(this, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith");

      To import an existing user by attributes:

      // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
      var user = User.FromUserAttributes(stack, "MyImportedUserByAttributes", new Struct {
          UserArn = "arn:aws:iam::123456789012:user/johnsmith"
      });

      Features

        Classes

        AccountPrincipal

        Specify AWS account ID as the principal entity in a policy to delegate authority to the account.

        AccountRootPrincipal

        Use the AWS account into which a stack is deployed as the principal entity in a policy.

        AddToPrincipalPolicyResult

        Result of calling addToPrincipalPolicy.

        AddToResourcePolicyResult

        Result of calling addToResourcePolicy.

        Anyone

        (deprecated) A principal representing all identities in all accounts.

        AnyPrincipal

        A principal representing all identities in all accounts.

        ArnPrincipal

        Specify a principal by the Amazon Resource Name (ARN).

        CanonicalUserPrincipal

        A policy principal for canonicalUserIds - useful for S3 bucket policies that use Origin Access identities.

        CfnAccessKey

        A CloudFormation AWS::IAM::AccessKey.

        CfnAccessKeyProps

        Properties for defining a AWS::IAM::AccessKey.

        CfnGroup

        A CloudFormation AWS::IAM::Group.

        CfnGroup.PolicyProperty
        CfnGroupProps

        Properties for defining a AWS::IAM::Group.

        CfnInstanceProfile

        A CloudFormation AWS::IAM::InstanceProfile.

        CfnInstanceProfileProps

        Properties for defining a AWS::IAM::InstanceProfile.

        CfnManagedPolicy

        A CloudFormation AWS::IAM::ManagedPolicy.

        CfnManagedPolicyProps

        Properties for defining a AWS::IAM::ManagedPolicy.

        CfnPolicy

        A CloudFormation AWS::IAM::Policy.

        CfnPolicyProps

        Properties for defining a AWS::IAM::Policy.

        CfnRole

        A CloudFormation AWS::IAM::Role.

        CfnRole.PolicyProperty
        CfnRoleProps

        Properties for defining a AWS::IAM::Role.

        CfnServiceLinkedRole

        A CloudFormation AWS::IAM::ServiceLinkedRole.

        CfnServiceLinkedRoleProps

        Properties for defining a AWS::IAM::ServiceLinkedRole.

        CfnUser

        A CloudFormation AWS::IAM::User.

        CfnUser.LoginProfileProperty
        CfnUser.PolicyProperty
        CfnUserProps

        Properties for defining a AWS::IAM::User.

        CfnUserToGroupAddition

        A CloudFormation AWS::IAM::UserToGroupAddition.

        CfnUserToGroupAdditionProps

        Properties for defining a AWS::IAM::UserToGroupAddition.

        CommonGrantOptions

        (experimental) Basic options for a grant operation.

        CompositeDependable

        Composite dependable.

        CompositePrincipal

        Represents a principal that has multiple types of principals.

        Effect

        The Effect element of an IAM policy.

        FederatedPrincipal

        Principal entity that represents a federated identity provider such as Amazon Cognito, that can be used to provide temporary security credentials to users who have been authenticated.

        FromRoleArnOptions

        Options allowing customizing the behavior of {@link Role.fromRoleArn}.

        Grant

        Result of a grant() operation.

        GrantOnPrincipalAndResourceOptions

        (experimental) Options for a grant operation to both identity and resource.

        GrantOnPrincipalOptions

        (experimental) Options for a grant operation that only applies to principals.

        GrantWithResourceOptions

        (experimental) Options for a grant operation.

        Group

        An IAM Group (collection of IAM users) lets you specify permissions for multiple users, which can make it easier to manage permissions for those users.

        GroupProps

        Properties for defining an IAM group.

        LazyRole

        An IAM role that only gets attached to the construct tree once it gets used, not before.

        LazyRoleProps

        Properties for defining a LazyRole.

        ManagedPolicy

        Managed policy.

        ManagedPolicyProps

        Properties for defining an IAM managed policy.

        OpenIdConnectPrincipal

        A principal that represents a federated identity provider as from a OpenID Connect provider.

        OpenIdConnectProvider

        (experimental) IAM OIDC identity providers are entities in IAM that describe an external identity provider (IdP) service that supports the OpenID Connect (OIDC) standard, such as Google or Salesforce.

        OpenIdConnectProviderProps

        (experimental) Initialization properties for OpenIdConnectProvider.

        OrganizationPrincipal

        A principal that represents an AWS Organization.

        PermissionsBoundary

        Modify the Permissions Boundaries of Users and Roles in a construct tree.

        Policy

        The AWS::IAM::Policy resource associates an IAM policy with IAM users, roles, or groups.

        PolicyDocument

        A PolicyDocument is a collection of statements.

        PolicyDocumentProps

        Properties for a new PolicyDocument.

        PolicyProps

        Properties for defining an IAM inline policy document.

        PolicyStatement

        Represents a statement in an IAM policy document.

        PolicyStatementProps

        Interface for creating a policy statement.

        PrincipalBase

        Base class for policy principals.

        PrincipalPolicyFragment

        A collection of the fields in a PolicyStatement that can be used to identify a principal.

        PrincipalWithConditions

        An IAM principal with additional conditions specifying when the policy is in effect.

        Role

        IAM Role.

        RoleProps

        Properties for defining an IAM Role.

        ServicePrincipal

        An IAM principal that represents an AWS service (i.e. sqs.amazonaws.com).

        ServicePrincipalOpts

        Options for a service principal.

        UnknownPrincipal

        A principal for use in resources that need to have a role but it's unknown.

        UnknownPrincipalProps

        Properties for an UnknownPrincipal.

        User

        Define a new IAM user.

        UserAttributes

        Represents a user defined outside of this stack.

        UserProps

        Properties for defining an IAM user.

        WebIdentityPrincipal

        A principal that represents a federated identity provider as Web Identity such as Cognito, Amazon, Facebook, Google, etc.

        Interfaces

        CfnGroup.IPolicyProperty
        CfnRole.IPolicyProperty
        CfnUser.ILoginProfileProperty
        CfnUser.IPolicyProperty
        IAddToPrincipalPolicyResult

        Result of calling addToPrincipalPolicy.

        IAddToResourcePolicyResult

        Result of calling addToResourcePolicy.

        ICfnAccessKeyProps

        Properties for defining a AWS::IAM::AccessKey.

        ICfnGroupProps

        Properties for defining a AWS::IAM::Group.

        ICfnInstanceProfileProps

        Properties for defining a AWS::IAM::InstanceProfile.

        ICfnManagedPolicyProps

        Properties for defining a AWS::IAM::ManagedPolicy.

        ICfnPolicyProps

        Properties for defining a AWS::IAM::Policy.

        ICfnRoleProps

        Properties for defining a AWS::IAM::Role.

        ICfnServiceLinkedRoleProps

        Properties for defining a AWS::IAM::ServiceLinkedRole.

        ICfnUserProps

        Properties for defining a AWS::IAM::User.

        ICfnUserToGroupAdditionProps

        Properties for defining a AWS::IAM::UserToGroupAddition.

        ICommonGrantOptions

        (experimental) Basic options for a grant operation.

        IFromRoleArnOptions

        Options allowing customizing the behavior of {@link Role.fromRoleArn}.

        IGrantable

        Any object that has an associated principal that a permission can be granted to.

        IGrantOnPrincipalAndResourceOptions

        (experimental) Options for a grant operation to both identity and resource.

        IGrantOnPrincipalOptions

        (experimental) Options for a grant operation that only applies to principals.

        IGrantWithResourceOptions

        (experimental) Options for a grant operation.

        IGroup

        Represents an IAM Group.

        IGroupProps

        Properties for defining an IAM group.

        IIdentity

        A construct that represents an IAM principal, such as a user, group or role.

        ILazyRoleProps

        Properties for defining a LazyRole.

        IManagedPolicy

        A managed policy.

        IManagedPolicyProps

        Properties for defining an IAM managed policy.

        IOpenIdConnectProvider

        (experimental) Represents an IAM OpenID Connect provider.

        IOpenIdConnectProviderProps

        (experimental) Initialization properties for OpenIdConnectProvider.

        IPolicy

        Represents an IAM Policy.

        IPolicyDocumentProps

        Properties for a new PolicyDocument.

        IPolicyProps

        Properties for defining an IAM inline policy document.

        IPolicyStatementProps

        Interface for creating a policy statement.

        IPrincipal

        Represents a logical IAM principal.

        IResourceWithPolicy

        A resource with a resource policy that can be added to.

        IRole

        A Role object.

        IRoleProps

        Properties for defining an IAM Role.

        IServicePrincipalOpts

        Options for a service principal.

        IUnknownPrincipalProps

        Properties for an UnknownPrincipal.

        IUser

        Represents an IAM user.

        IUserAttributes

        Represents a user defined outside of this stack.

        IUserProps

        Properties for defining an IAM user.

        Back to top Generated by DocFX