127 types
For a detailed guide on CDK security and safety please see the CDK Security And Safety Dev Guide
The guide will cover topics like:
Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:
role = AWSCDK::IAM::Role.new(self, "MyRole", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("sns.amazonaws.com"),
})
role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
resources: ["*"],
actions: ["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).
user = AWSCDK::IAM::User.new(self, "MyUser", {password: AWSCDK::SecretValue.plain_text("1234")})
group = AWSCDK::IAM::Group.new(self, "MyGroup")
policy = AWSCDK::IAM::Policy.new(self, "MyPolicy")
policy.attach_to_user(user)
group.attach_inline_policy(policy)
Managed policies can be attached using xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName)):
group = AWSCDK::IAM::Group.new(self, "MyGroup")
group.add_managed_policy(AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AdministratorAccess"))
Many of the AWS CDK resources have grant methods (accessible via the grants attribute) 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.
fn = nil # AWSCDK::Lambda::Function
table = nil # AWSCDK::DynamoDB::Table
table.grants.write_data(fn)
The more generic actions method allows you to give specific permissions to a resource:
fn = nil # AWSCDK::Lambda::Function
table = nil # AWSCDK::DynamoDB::Table
table.grants.actions(fn, "dynamodb:PutItem")
The grant methods accept an IGrantable object. This interface is implemented by IAM principal resources (groups, users and roles), policies, managed policies 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.
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 the public methods in the
RoleGrants class (see the previous section).
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 my_role itself.
For example, to have an AWS CodePipeline not automatically add the required permissions to trigger the expected targets, do the following:
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("codepipeline.amazonaws.com"),
# custom description if desired
description: "This is a custom role...",
})
AWSCDK::Codepipeline::Pipeline.new(self, "Pipeline", {
# Give the Pipeline an immutable view of the Role
role: role.without_policy_updates,
})
# You now have to manage the Role policies yourself
role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
actions: [],
resources: [],
}))
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:
role = AWSCDK::IAM::Role.from_role_arn(self, "Role", "arn:aws:iam::123456789012:role/MyExistingRole", {
# 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,
})
If you want to lookup roles that actually exist in your account, you can use Role.fromLookup().
role = AWSCDK::IAM::Role.from_lookup(self, "Role", {
role_name: "MyExistingRole",
})
It is best practice to allow CDK to manage IAM roles and permissions. You can prevent CDK from
creating roles by using the customize_roles method for special cases. One such case is using CDK in
an environment where role creation is not allowed or needs to be managed through a process outside
of the CDK application.
An example of how to opt in to this behavior is below:
stack = nil # AWSCDK::Stack
AWSCDK::IAM::Role.customize_roles(stack)
CDK will not create any IAM roles or policies with the stack scope. cdk synth will fail and
it will generate a policy report to the cloud assembly (i.e. cdk.out). The iam-policy-report.txt
report will contain a list of IAM roles and associated permissions that would have been created.
This report can be used to create the roles with the appropriate permissions outside of
the CDK application.
Once the missing roles have been created, their names can be added to the use_precreated_roles
property, like shown below:
app = nil # AWSCDK::App
stack = AWSCDK::Stack.new(app, "MyStack")
AWSCDK::IAM::Role.customize_roles(self, {
use_precreated_roles: {
"MyStack/MyRole" => "my-precreated-role-name",
},
})
AWSCDK::IAM::Role.new(self, "MyRole", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("sns.amazonaws.com"),
})
If any IAM policies reference deploy time values (i.e. ARN of a resource that hasn't been created yet) you will have to modify the generated report to be more generic. For example, given the following CDK code:
app = nil # AWSCDK::App
stack = AWSCDK::Stack.new(app, "MyStack")
AWSCDK::IAM::Role.customize_roles(stack)
fn = AWSCDK::Lambda::Function.new(self, "MyLambda", {
code: AWSCDK::Lambda::InlineCode.new("foo"),
handler: "index.handler",
runtime: AWSCDK::Lambda::Runtime.NODEJS_LATEST,
})
bucket = AWSCDK::S3::Bucket.new(self, "Bucket")
bucket.grants.read(fn)
The following report will be generated.
<missing role> (MyStack/MyLambda/ServiceRole)
AssumeRole Policy:
[
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
]
Managed Policy ARNs:
[
"arn:(PARTITION):iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
]
Managed Policies Statements:
NONE
Identity Policy Statements:
[
{
"Action": [
"s3:GetObject*",
"s3:GetBucket*",
"s3:List*"
],
"Effect": "Allow",
"Resource": [
"(MyStack/Bucket/Resource.Arn)",
"(MyStack/Bucket/Resource.Arn)/*"
]
}
]
You would then need to create the role with the inline & managed policies in the report and then
come back and update the customize_roles with the role name.
app = nil # AWSCDK::App
stack = AWSCDK::Stack.new(app, "MyStack")
AWSCDK::IAM::Role.customize_roles(self, {
use_precreated_roles: {
"MyStack/MyLambda/ServiceRole" => "my-role-name",
},
})
For more information on configuring permissions see the Security And Safety Dev Guide
When customize_roles is used, the iam-policy-report.txt report will contain a list
of IAM roles and associated permissions that would have been created. This report is
generated in an attempt to resolve and replace any references with a more user-friendly
value.
The following are some examples of the value that will appear in the report:
"Resource": {
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":iam::",
{
"Ref": "AWS::AccountId"
},
":role/Role"
]
]
}
The policy report will instead get:
"Resource": "arn:(PARTITION):iam::(ACCOUNT):role/Role"
If IAM policy is referencing a resource attribute:
"Resource": [
{
"Fn::GetAtt": [
"SomeResource",
"Arn"
]
},
{
"Ref": "AWS::NoValue",
}
]
The policy report will instead get:
"Resource": [
"(Path/To/SomeResource.Arn)"
"(NOVALUE)"
]
The following pseudo parameters will be converted:
{ 'Ref': 'AWS::AccountId' } -> `(ACCOUNT){ 'Ref': 'AWS::Partition' } -> `(PARTITION){ 'Ref': 'AWS::Region' } -> `(REGION){ 'Ref': 'AWS::NoValue' } -> `(NOVALUE)It is also possible to generate the report without preventing the role/policy creation.
stack = nil # AWSCDK::Stack
AWSCDK::IAM::Role.customize_roles(self, {
prevent_synthesis: false,
})
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:
role = AWSCDK::IAM::Role.new(self, "MyRole", {
assumed_by: AWSCDK::IAM::AccountPrincipal.new("123456789012"),
external_ids: ["SUPPLY-ME"],
})
If you need to create resource policies using aws:SourceArn and aws:SourceAccount for cross-service resource access,
use add_source_arn_condition and add_source_account_condition to create the conditions.
See Cross-service confused deputy prevention for more details.
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.
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 add_xxx_principal methods:
add_aws_principal, add_arn_principal or new ArnPrincipal(arn) for { "AWS": arn }add_aws_account_principal or new AccountPrincipal(accountId) for { "AWS": account-arn }add_service_principal or new ServicePrincipal(service) for { "Service": service }add_account_root_principal or new AccountRootPrincipal() for { "AWS": { "Ref: "AWS::AccountId" } }add_canonical_user_principal or new CanonicalUserPrincipal(id) for { "CanonicalUser": id }add_federated_principal or new FederatedPrincipal(federated, conditions, assumeAction) for
{ "Federated": arn } and a set of optional conditions and the assume role action to use.add_any_principal or new AnyPrincipal for { "AWS": "*" }If multiple principals are added to the policy statement, they will be merged together:
statement = AWSCDK::IAM::PolicyStatement.new
statement.add_service_principal("cloudwatch.amazonaws.com")
statement.add_service_principal("ec2.amazonaws.com")
statement.add_arn_principal("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:
role = AWSCDK::IAM::Role.new(self, "MyRole", {
assumed_by: AWSCDK::IAM::CompositePrincipal.new(
AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
AWSCDK::IAM::AccountPrincipal.new("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:
principal = AWSCDK::IAM::AccountPrincipal.new("123456789000").with_conditions({StringEquals: {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
CfnJsonto render this condition. See this test for an example.
The WebIdentityPrincipal class can be used as a principal for web identities like
Cognito, Amazon, Google or Facebook, for example:
principal = AWSCDK::IAM::WebIdentityPrincipal.new("cognito-identity.amazonaws.com", {
"StringEquals" => {"cognito-identity.amazonaws.com:aud" => "us-east-2:12345678-abcd-abcd-abcd-123456"},
"ForAnyValue:StringLike" => {"cognito-identity.amazonaws.com:amr" => "unauthenticated"},
})
If your identity provider is configured to assume a Role with session
tags, you
need to call .withSessionTags() to add the required permissions to the Role's
policy document:
AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::WebIdentityPrincipal.new("cognito-identity.amazonaws.com", {
"StringEquals" => {
"cognito-identity.amazonaws.com:aud" => "us-east-2:12345678-abcd-abcd-abcd-123456",
},
"ForAnyValue:StringLike" => {
"cognito-identity.amazonaws.com:amr" => "unauthenticated",
},
}).,
})
A principal can be granted permission to assume a role using assume_role from the RoleGrants class.
For convenience, an instance of this class is available via the grants attribute on the Role class.
Note that this does not apply to service principals or account principals as they must be added to the role trust policy via assume_role_policy.
user = AWSCDK::IAM::User.new(self, "user")
role = AWSCDK::IAM::Role.new(self, "role", {
assumed_by: AWSCDK::IAM::AccountPrincipal.new(@account),
})
role.grants.assume_role(user)
Service principals and account principals can be granted permission to assume a role using assume_role_policy which modifies the role trust policy.
role = AWSCDK::IAM::Role.new(self, "role", {
assumed_by: AWSCDK::IAM::AccountPrincipal.new(@account),
})
role.assume_role_policy&.add_statements(AWSCDK::IAM::PolicyStatement.new({
actions: ["sts:AssumeRole"],
principals: [
AWSCDK::IAM::AccountPrincipal.new("123456789"),
AWSCDK::IAM::ServicePrincipal.new("beep-boop.amazonaws.com"),
],
}))
In some cases, certain AWS services may not use the standard <service>.amazonaws.com pattern for their service principals. For these services, you can define the ServicePrincipal as following where the provided service principle name will be used as is without any changing.
sp = AWSCDK::IAM::ServicePrincipal.from_static_service_principle_name("elasticmapreduce.amazonaws.com.cn")
This principle can use as normal in defining any role, for example:
emr_service_role = AWSCDK::IAM::Role.new(self, "EMRServiceRole", {
assumed_by: AWSCDK::IAM::ServicePrincipal.from_static_service_principle_name("elasticmapreduce.amazonaws.com.cn"),
managed_policies: [
AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonElasticMapReduceRole"),
],
})
The PolicyDocument.fromJson and PolicyStatement.fromJson static methods can be used to parse JSON objects. For example:
policy_document = {
"Version" => "2012-10-17",
"Statement" => [
{
"Sid" => "FirstStatement",
"Effect" => "Allow",
"Action" => ["iam:ChangePassword"],
"Resource" => ["*"],
},
{
"Sid" => "SecondStatement",
"Effect" => "Allow",
"Action" => ["s3:ListAllMyBuckets"],
"Resource" => ["*"],
},
{
"Sid" => "ThirdStatement",
"Effect" => "Allow",
"Action" => [
"s3:List*",
"s3:Get*",
],
"Resource" => [
"arn:aws:s3:::confidential-data",
"arn:aws:s3:::confidential-data/*",
],
"Condition" => {"Bool" => {"aws:MultiFactorAuthPresent" => "true"}},
},
],
}
custom_policy_document = AWSCDK::IAM::PolicyDocument.from_json(policy_document)
# You can pass this document as an initial document to a ManagedPolicy
# or inline Policy.
new_managed_policy = AWSCDK::IAM::ManagedPolicy.new(self, "MyNewManagedPolicy", {
document: custom_policy_document,
})
new_policy = AWSCDK::IAM::Policy.new(self, "MyNewPolicy", {
document: custom_policy_document,
})
The Sid (statement ID) element in IAM identity policies must be alphanumeric (A-Z, a-z, 0-9) according to AWS IAM requirements. CDK validates identity policy SIDs at synthesis time.
# This will throw an error when used in an identity policy
AWSCDK::IAM::PolicyStatement.new({
sid: "Allow access for S3.",
# Invalid: contains spaces and period
actions: ["s3:GetObject"],
resources: ["*"],
})
# Valid SID - alphanumeric only
AWSCDK::IAM::PolicyStatement.new({
sid: "AllowAccessForS3",
# Valid: alphanumeric only
actions: ["s3:GetObject"],
resources: ["*"],
})
This validation helps catch SID errors early in development rather than at deployment time.
Permissions
Boundaries
can be used as a mechanism to prevent privilege escalation 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.
If a permissions boundary has been enforced as part of CDK bootstrap, all IAM
Roles and Users that are created as part of the CDK application must be created
with the permissions boundary attached. The most common scenario will be to
apply the enforced permissions boundary to the entire CDK app. This can be done
either by adding the value to cdk.json or directly in the App constructor.
For example if your organization has created and is enforcing a permissions
boundary with the name
cdk-${Qualifier}-PermissionsBoundary
{
"context": {
"@aws-cdk/core:permissionsBoundary": {
"name": "cdk-${Qualifier}-PermissionsBoundary"
}
}
}
OR
AWSCDK::App.new({
context: {
PERMISSIONS_BOUNDARY_CONTEXT_KEY => {
name: "cdk-${Qualifier}-PermissionsBoundary",
},
},
})
Another scenario might be if your organization enforces different permissions boundaries for different environments. For example your CDK application may have
DevStage that deploys to a personal dev environment where you have elevated
privilegesBetaStage that deploys to a beta environment which and has a relaxed
permissions boundaryGammaStage that deploys to a gamma environment which has the prod
permissions boundaryProdStage that deploys to the prod environment and has the prod permissions
boundaryapp = nil # AWSCDK::App
AWSCDK::Stage.new(app, "DevStage")
AWSCDK::Stage.new(app, "BetaStage", {
permissions_boundary: AWSCDK::PermissionsBoundary.from_name("beta-permissions-boundary"),
})
AWSCDK::Stage.new(app, "GammaStage", {
permissions_boundary: AWSCDK::PermissionsBoundary.from_name("prod-permissions-boundary"),
})
AWSCDK::Stage.new(app, "ProdStage", {
permissions_boundary: AWSCDK::PermissionsBoundary.from_name("prod-permissions-boundary"),
})
The provided name can include placeholders for the partition, region, qualifier, and account These placeholders will be replaced with the actual values if available. This requires that the Stack has the environment specified, it does not work with environment.
app = nil # AWSCDK::App
prod_stage = AWSCDK::Stage.new(app, "ProdStage", {
permissions_boundary: AWSCDK::PermissionsBoundary.from_name("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}"),
})
AWSCDK::Stack.new(prod_stage, "ProdStack", {
synthesizer: AWSCDK::DefaultStackSynthesizer.new({
qualifier: "custom",
}),
})
For more information on configuring permissions see the Security And Safety Dev Guide
It is possible to attach Permissions Boundaries to all Roles created in a construct tree all at once:
# Directly apply the boundary to a Role you create
role = nil # AWSCDK::IAM::Role
# Apply the boundary to an Role that was implicitly created for you
fn = nil # AWSCDK::Lambda::Function
# Remove a Permissions Boundary that is inherited, for example from the Stack level
custom_resource = nil # AWSCDK::CustomResource
# This imports an existing policy.
boundary = AWSCDK::IAM::ManagedPolicy.from_managed_policy_arn(self, "Boundary", "arn:aws:iam::123456789012:policy/boundary")
# This creates a new boundary
boundary2 = AWSCDK::IAM::ManagedPolicy.new(self, "Boundary2", {
statements: [
AWSCDK::IAM::PolicyStatement.new({
effect: AWSCDK::IAM::Effect::DENY,
actions: ["iam:*"],
resources: ["*"],
}),
],
})
AWSCDK::IAM::PermissionsBoundary.of(role).apply(boundary)
AWSCDK::IAM::PermissionsBoundary.of(fn).apply(boundary)
# Apply the boundary to all Roles in a stack
AWSCDK::IAM::PermissionsBoundary.of(self).apply(boundary)
AWSCDK::IAM::PermissionsBoundary.of(custom_resource).clear
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.
The older OpenIdConnectProvider is still supported, but for new stacks, it is recommended to use the new OidcProviderNative which uses the native CloudFormation resource AWS::IAM::OIDCProvider over the old OpenIdConnectProvider which uses a custom resource. While OidcProviderNative does not provide new features compared to OpenIdConnectProvider, it offers a simpler implementation using native CloudFormation resources instead of custom resources.
native_provider = AWSCDK::IAM::OidcProviderNative.new(self, "MyProvider", {
url: "https://openid/connect",
client_ids: ["myclient1", "myclient2"],
thumbprints: ["aa00aa1122aa00aa1122aa00aa1122aa00aa1122"],
})
For the new OidcProviderNative, you must provide at least one thumbprint when creating an IAM OIDC
provider. For example, assume that the OIDC provider is server.example.com
and the provider stores its keys at
https://keys.server.example.com/openid-connect. In that case, the
thumbprint string would be the hex-encoded SHA-1 hash value of the
certificate used by https://keys.server.example.com.
The server certificate thumbprint is the hex-encoded SHA-1 hash value of the X.509 certificate used by the domain where the OpenID Connect provider makes its keys available. It is always a 40-character string.
Typically this list includes only one entry. However, IAM lets you have up to five thumbprints for an OIDC provider. This lets you maintain multiple thumbprints if the identity provider is rotating certificates.
Obtain the thumbprint of the root certificate authority from the provider's server as described in https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html
The older OpenIdConnectProvider is still supported but it is recommended to use the new OidcProviderNative instead.
provider = AWSCDK::IAM::OpenIdConnectProvider.new(self, "MyProvider", {
url: "https://openid/connect",
client_ids: ["myclient1", "myclient2"],
})
For the older OpenIdConnectProvider, 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.
By default, the custom resource enforces strict security practices by rejecting
any unauthorized connections when downloading CA thumbprints from the issuer URL.
If you need to connect to an unauthorized OIDC identity provider and understand the
implications, you can disable this behavior by setting the feature flag
IAM_OIDC_REJECT_UNAUTHORIZED_CONNECTIONS to false in your cdk.context.json
or cdk.json. Visit CDK Feature Flag
for more information on how to configure feature flags.
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:
require 'aws-cdk-lib'
my_provider = nil # AWSCDK::IAM::OpenIdConnectProvider
AWSCDK::Cognito::CfnIdentityPool.new(self, "IdentityPool", {
open_id_connect_provider_arns: [my_provider.open_id_connect_provider_arn],
# And the other properties for your identity pool
allow_unauthenticated_identities: false,
})
The OpenIdConnectPrincipal class can be used as a principal used with a OpenIdConnectProvider, for example:
provider = AWSCDK::IAM::OpenIdConnectProvider.new(self, "MyProvider", {
url: "https://openid/connect",
client_ids: ["myclient1", "myclient2"],
})
principal = AWSCDK::IAM::OpenIdConnectPrincipal.new(provider)
An IAM SAML 2.0 identity provider is an entity in IAM that describes an external identity provider (IdP) service that supports the SAML 2.0 (Security Assertion Markup Language 2.0) standard. You use an IAM identity provider when you want to establish trust between a SAML-compatible IdP such as Shibboleth or Active Directory Federation Services and AWS, so that users in your organization can access AWS resources. IAM SAML identity providers are used as principals in an IAM trust policy.
AWSCDK::IAM::SamlProvider.new(self, "Provider", {
metadata_document: AWSCDK::IAM::SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml"),
})
The SamlPrincipal class can be used as a principal with a SamlProvider:
provider = AWSCDK::IAM::SamlProvider.new(self, "Provider", {
metadata_document: AWSCDK::IAM::SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml"),
})
principal = AWSCDK::IAM::SamlPrincipal.new(provider, {
StringEquals: {
"SAML:iss" => "issuer",
},
})
When creating a role for programmatic and AWS Management Console access, use the SamlConsolePrincipal
class:
provider = AWSCDK::IAM::SamlProvider.new(self, "Provider", {
metadata_document: AWSCDK::IAM::SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml"),
})
AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::SamlConsolePrincipal.new(provider),
})
IAM manages users for your AWS account. To create a new user:
user = AWSCDK::IAM::User.new(self, "MyUser")
To import an existing user by name with path:
user = AWSCDK::IAM::User.from_user_name(self, "MyImportedUserByName", "johnsmith")
To import an existing user by ARN:
user = AWSCDK::IAM::User.from_user_arn(self, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith")
To import an existing user by attributes:
user = AWSCDK::IAM::User.from_user_attributes(self, "MyImportedUserByAttributes", {
user_arn: "arn:aws:iam::123456789012:user/johnsmith",
})
The ability for a user to make API calls via the CLI or an SDK is enabled by the user having an access key pair. To create an access key:
user = AWSCDK::IAM::User.new(self, "MyUser")
access_key = AWSCDK::IAM::AccessKey.new(self, "MyAccessKey", {user: user})
You can force CloudFormation to rotate the access key by providing a monotonically increasing serial
property. Simply provide a higher serial value than any number used previously:
user = AWSCDK::IAM::User.new(self, "MyUser")
access_key = AWSCDK::IAM::AccessKey.new(self, "MyAccessKey", {user: user, serial: 1})
An access key may only be associated with a single user and cannot be "moved" between users. Changing the user associated with an access key replaces the access key (and its ID and secret value).
An IAM user group is a collection of IAM users. User groups let you specify permissions for multiple users.
group = AWSCDK::IAM::Group.new(self, "MyGroup")
To import an existing group by ARN:
group = AWSCDK::IAM::Group.from_group_arn(self, "MyImportedGroupByArn", "arn:aws:iam::account-id:group/group-name")
To import an existing group by name with path:
group = AWSCDK::IAM::Group.from_group_name(self, "MyImportedGroupByName", "group-name")
To add a user to a group (both for a new and imported user/group):
user = AWSCDK::IAM::User.new(self, "MyUser") # or User.fromUserName(this, 'User', 'johnsmith');
group = AWSCDK::IAM::Group.new(self, "MyGroup") # or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');
user.add_to_group(group)
# or
group.add_user(user)
An IAM instance profile is a container for an IAM role that you can use to pass role information to an EC2 instance when the instance starts. By default, an instance profile must be created with a role:
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
})
instance_profile = AWSCDK::IAM::InstanceProfile.new(self, "InstanceProfile", {
role: role,
})
An instance profile can also optionally be created with an instance profile name and/or a path to the instance profile:
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
})
instance_profile = AWSCDK::IAM::InstanceProfile.new(self, "InstanceProfile", {
role: role,
instance_profile_name: "MyInstanceProfile",
path: "/sample/path/",
})
To import an existing instance profile by name:
instance_profile = AWSCDK::IAM::InstanceProfile.from_instance_profile_name(self, "ImportedInstanceProfile", "MyInstanceProfile")
To import an existing instance profile by ARN:
instance_profile = AWSCDK::IAM::InstanceProfile.from_instance_profile_arn(self, "ImportedInstanceProfile", "arn:aws:iam::account-id:instance-profile/MyInstanceProfile")
To import an existing instance profile with an associated role:
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
})
instance_profile = AWSCDK::IAM::InstanceProfile.from_instance_profile_attributes(self, "ImportedInstanceProfile", {
instance_profile_arn: "arn:aws:iam::account-id:instance-profile/MyInstanceProfile",
role: role,
})