Namespace Amazon.CDK.AWS.IAM
AWS Identity and Access Management Construct Library
Security and Safety Dev Guide
For a detailed guide on CDK security and safety please see the CDK Security And Safety Dev Guide
The guide will cover topics like:
Overview
Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:
var 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)
.
var user = new User(this, "MyUser", new UserProps { Password = SecretValue.PlainText("1234") });
var group = new Group(this, "MyGroup");
var policy = new Policy(this, "MyPolicy");
policy.AttachToUser(user);
group.AttachInlinePolicy(policy);
Managed policies can be attached using xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))
:
var 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.
Function fn;
Table table;
table.GrantWriteData(fn);
The more generic grant
method allows you to give specific permissions to a resource:
Function fn;
Table table;
table.Grant(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.
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:
var 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:
var 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
});
Customizing role creation
It is best practice to allow CDK to manage IAM roles and permissions. You can prevent CDK from
creating roles by using the customizeRoles
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 stack;
Role.CustomizeRoles(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 usePrecreatedRoles
property, like shown below:
App app;
var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(this, new CustomizeRolesOptions {
UsePrecreatedRoles = new Dictionary<string, string> {
{ "MyStack/MyRole", "my-precreated-role-name" }
}
});
new Role(this, "MyRole", new RoleProps {
AssumedBy = new ServicePrincipal("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 app;
var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(stack);
var fn = new Function(this, "MyLambda", new FunctionProps {
Code = new InlineCode("foo"),
Handler = "index.handler",
Runtime = Runtime.NODEJS_LATEST
});
var bucket = new Bucket(this, "Bucket");
bucket.GrantRead(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 customizeRoles
with the role name.
App app;
var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(this, new CustomizeRolesOptions {
UsePrecreatedRoles = new Dictionary<string, string> {
{ "MyStack/MyLambda/ServiceRole", "my-role-name" }
}
});
For more information on configuring permissions see the Security And Safety Dev Guide
Policy report generation
When customizeRoles
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:
Generating a permissions report
It is also possible to generate the report without preventing the role/policy creation.
Stack stack;
Role.CustomizeRoles(this, new CustomizeRolesOptions {
PreventSynthesis = 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:
var role = new Role(this, "MyRole", new RoleProps {
AssumedBy = new AccountPrincipal("123456789012"),
ExternalIds = new [] { "SUPPLY-ME" }
});
SourceArn and SourceAccount
If you need to create resource policies using aws:SourceArn
and aws:SourceAccount
for cross-service resource access,
use addSourceArnCondition
and addSourceAccountCondition
to create the conditions.
See Cross-service confused deputy prevention for more details.
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:
var 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:
var 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:
var principal = new AccountPrincipal("123456789000").WithConditions(new Dictionary<string, object> { { "StringEquals", new Dictionary<string, string> { { "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:
var principal = new WebIdentityPrincipal("cognito-identity.amazonaws.com", new Dictionary<string, object> {
{ "StringEquals", new Dictionary<string, string> { { "cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456" } } },
{ "ForAnyValue:StringLike", new Dictionary<string, string> { { "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:
new Role(this, "Role", new RoleProps {
AssumedBy = new WebIdentityPrincipal("cognito-identity.amazonaws.com", new Dictionary<string, object> {
{ "StringEquals", new Dictionary<string, string> {
{ "cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456" }
} },
{ "ForAnyValue:StringLike", new Dictionary<string, string> {
{ "cognito-identity.amazonaws.com:amr", "unauthenticated" }
} }
}).WithSessionTags()
});
Granting a principal permission to assume a role
A principal can be granted permission to assume a role using grantAssumeRole
.
Note that this does not apply to service principals or account principals as they must be added to the role trust policy via assumeRolePolicy
.
var user = new User(this, "user");
var role = new Role(this, "role", new RoleProps {
AssumedBy = new AccountPrincipal(Account)
});
role.GrantAssumeRole(user);
Granting service and account principals permission to assume a role
Service principals and account principals can be granted permission to assume a role using assumeRolePolicy
which modifies the role trust policy.
var role = new Role(this, "role", new RoleProps {
AssumedBy = new AccountPrincipal(Account)
});
role.AssumeRolePolicy.AddStatements(new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "sts:AssumeRole" },
Principals = new [] {
new AccountPrincipal("123456789"),
new ServicePrincipal("beep-boop.amazonaws.com") }
}));
Fixing the synthesized service principle for services that do not follow the IAM Pattern
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.
var sp = ServicePrincipal.FromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn");
This principle can use as normal in defining any role, for example:
var emrServiceRole = new Role(this, "EMRServiceRole", new RoleProps {
AssumedBy = ServicePrincipal.FromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn"),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonElasticMapReduceRole") }
});
Parsing JSON Policy Documents
The PolicyDocument.fromJson
and PolicyStatement.fromJson
static methods can be used to parse JSON objects. For example:
IDictionary<string, 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 [] { "*" } }
}, new Dictionary<string, object> {
{ "Sid", "SecondStatement" },
{ "Effect", "Allow" },
{ "Action", new [] { "s3:ListAllMyBuckets" } },
{ "Resource", new [] { "*" } }
}, 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" } } } } }
} } }
};
var customPolicyDocument = PolicyDocument.FromJson(policyDocument);
// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
var newManagedPolicy = new ManagedPolicy(this, "MyNewManagedPolicy", new ManagedPolicyProps {
Document = customPolicyDocument
});
var newPolicy = new Policy(this, "MyNewPolicy", new PolicyProps {
Document = customPolicyDocument
});
Permissions Boundaries
Permissions
Boundaries
can be used as a mechanism to prevent privilege escalation by creating new
Role
s. 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 Role
s will be enforced by
IAM policies.
Bootstrap Permissions Boundary
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
new App(new AppProps {
Context = new Dictionary<string, object> {
{ PERMISSIONS_BOUNDARY_CONTEXT_KEY, new Dictionary<string, string> {
{ "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
App app;
new Stage(app, "DevStage");
new Stage(app, "BetaStage", new StageProps {
PermissionsBoundary = PermissionsBoundary.FromName("beta-permissions-boundary")
});
new Stage(app, "GammaStage", new StageProps {
PermissionsBoundary = PermissionsBoundary.FromName("prod-permissions-boundary")
});
new Stage(app, "ProdStage", new StageProps {
PermissionsBoundary = PermissionsBoundary.FromName("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 app;
var prodStage = new Stage(app, "ProdStage", new StageProps {
PermissionsBoundary = PermissionsBoundary.FromName("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}")
});
new Stack(prodStage, "ProdStack", new StackProps {
Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps {
Qualifier = "custom"
})
});
For more information on configuring permissions see the Security And Safety Dev Guide
Custom Permissions Boundary
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 role;
// Apply the boundary to an Role that was implicitly created for you
Function fn;
// Remove a Permissions Boundary that is inherited, for example from the Stack level
CustomResource customResource;
// This imports an existing policy.
var boundary = ManagedPolicy.FromManagedPolicyArn(this, "Boundary", "arn:aws:iam::123456789012:policy/boundary");
// This creates a new boundary
var boundary2 = new ManagedPolicy(this, "Boundary2", new ManagedPolicyProps {
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Effect = Effect.DENY,
Actions = new [] { "iam:*" },
Resources = new [] { "*" }
}) }
});
PermissionsBoundary.Of(role).Apply(boundary);
PermissionsBoundary.Of(fn).Apply(boundary);
// Apply the boundary to all Roles in a stack
PermissionsBoundary.Of(this).Apply(boundary);
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.
var 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:
using Amazon.CDK.AWS.Cognito;
OpenIdConnectProvider myProvider;
new CfnIdentityPool(this, "IdentityPool", new CfnIdentityPoolProps {
OpenIdConnectProviderArns = new [] { myProvider.OpenIdConnectProviderArn },
// And the other properties for your identity pool
AllowUnauthenticatedIdentities = false
});
The OpenIdConnectPrincipal
class can be used as a principal used with a OpenIdConnectProvider
, for example:
var provider = new OpenIdConnectProvider(this, "MyProvider", new OpenIdConnectProviderProps {
Url = "https://openid/connect",
ClientIds = new [] { "myclient1", "myclient2" }
});
var principal = new OpenIdConnectPrincipal(provider);
SAML 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.
new SamlProvider(this, "Provider", new SamlProviderProps {
MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
The SamlPrincipal
class can be used as a principal with a SamlProvider
:
var provider = new SamlProvider(this, "Provider", new SamlProviderProps {
MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
var principal = new SamlPrincipal(provider, new Dictionary<string, object> {
{ "StringEquals", new Dictionary<string, string> {
{ "SAML:iss", "issuer" }
} }
});
When creating a role for programmatic and AWS Management Console access, use the SamlConsolePrincipal
class:
var provider = new SamlProvider(this, "Provider", new SamlProviderProps {
MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
new Role(this, "Role", new RoleProps {
AssumedBy = new SamlConsolePrincipal(provider)
});
Users
IAM manages users for your AWS account. To create a new user:
var user = new User(this, "MyUser");
To import an existing user by name with path:
var user = User.FromUserName(this, "MyImportedUserByName", "johnsmith");
To import an existing user by ARN:
var user = User.FromUserArn(this, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith");
To import an existing user by attributes:
var user = User.FromUserAttributes(this, "MyImportedUserByAttributes", new UserAttributes {
UserArn = "arn:aws:iam::123456789012:user/johnsmith"
});
Access Keys
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:
var user = new User(this, "MyUser");
var accessKey = new AccessKey(this, "MyAccessKey", new AccessKeyProps { 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:
var user = new User(this, "MyUser");
var accessKey = new AccessKey(this, "MyAccessKey", new AccessKeyProps { 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).
Groups
An IAM user group is a collection of IAM users. User groups let you specify permissions for multiple users.
var group = new Group(this, "MyGroup");
To import an existing group by ARN:
var group = Group.FromGroupArn(this, "MyImportedGroupByArn", "arn:aws:iam::account-id:group/group-name");
To import an existing group by name with path:
var group = Group.FromGroupName(this, "MyImportedGroupByName", "group-name");
To add a user to a group (both for a new and imported user/group):
var user = new User(this, "MyUser"); // or User.fromUserName(this, 'User', 'johnsmith');
var group = new Group(this, "MyGroup"); // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');
user.AddToGroup(group);
// or
group.AddUser(user);
Instance Profiles
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:
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});
var instanceProfile = new InstanceProfile(this, "InstanceProfile", new InstanceProfileProps {
Role = role
});
An instance profile can also optionally be created with an instance profile name and/or a path to the instance profile:
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});
var instanceProfile = new InstanceProfile(this, "InstanceProfile", new InstanceProfileProps {
Role = role,
InstanceProfileName = "MyInstanceProfile",
Path = "/sample/path/"
});
To import an existing instance profile by name:
var instanceProfile = InstanceProfile.FromInstanceProfileName(this, "ImportedInstanceProfile", "MyInstanceProfile");
To import an existing instance profile by ARN:
var instanceProfile = InstanceProfile.FromInstanceProfileArn(this, "ImportedInstanceProfile", "arn:aws:iam::account-id:instance-profile/MyInstanceProfile");
To import an existing instance profile with an associated role:
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});
var instanceProfile = InstanceProfile.FromInstanceProfileAttributes(this, "ImportedInstanceProfile", new InstanceProfileAttributes {
InstanceProfileArn = "arn:aws:iam::account-id:instance-profile/MyInstanceProfile",
Role = role
});
Features
Classes
AccessKey | Define a new IAM Access Key. |
AccessKeyProps | Properties for defining an IAM access key. |
AccessKeyStatus | Valid statuses for an IAM Access Key. |
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 |
AddToResourcePolicyResult | Result of calling addToResourcePolicy. |
AnyPrincipal | A principal representing all AWS 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 | Creates a new AWS secret access key and corresponding AWS access key ID for the specified user. |
CfnAccessKeyProps | Properties for defining a |
CfnGroup | Creates a new group. |
CfnGroup.PolicyProperty | Contains information about an attached policy. |
CfnGroupPolicy | Adds or updates an inline policy document that is embedded in the specified IAM group. |
CfnGroupPolicyProps | Properties for defining a |
CfnGroupProps | Properties for defining a |
CfnInstanceProfile | Creates a new instance profile. For information about instance profiles, see Using instance profiles . |
CfnInstanceProfileProps | Properties for defining a |
CfnManagedPolicy | Creates a new managed policy for your AWS account . |
CfnManagedPolicyProps | Properties for defining a |
CfnOIDCProvider | Creates or updates an IAM entity to describe an identity provider (IdP) that supports OpenID Connect (OIDC) . |
CfnOIDCProviderProps | Properties for defining a |
CfnPolicy | Adds or updates an inline policy document that is embedded in the specified IAM group, user or role. |
CfnPolicyProps | Properties for defining a |
CfnRole | Creates a new role for your AWS account . |
CfnRole.PolicyProperty | Contains information about an attached policy. |
CfnRolePolicy | Adds or updates an inline policy document that is embedded in the specified IAM role. |
CfnRolePolicyProps | Properties for defining a |
CfnRoleProps | Properties for defining a |
CfnSAMLProvider | Creates an IAM resource that describes an identity provider (IdP) that supports SAML 2.0. |
CfnSAMLProviderProps | Properties for defining a |
CfnServerCertificate | Uploads a server certificate entity for the AWS account . |
CfnServerCertificateProps | Properties for defining a |
CfnServiceLinkedRole | Creates an IAM role that is linked to a specific AWS service. |
CfnServiceLinkedRoleProps | Properties for defining a |
CfnUser | Creates a new IAM user for your AWS account . |
CfnUser.LoginProfileProperty | Creates a password for the specified user, giving the user the ability to access AWS services through the AWS Management Console . |
CfnUser.PolicyProperty | Contains information about an attached policy. |
CfnUserPolicy | Adds or updates an inline policy document that is embedded in the specified IAM user. |
CfnUserPolicyProps | Properties for defining a |
CfnUserProps | Properties for defining a |
CfnUserToGroupAddition | Adds the specified user to the specified group. |
CfnUserToGroupAdditionProps | Properties for defining a |
CfnVirtualMFADevice | Creates a new virtual MFA device for the AWS account . |
CfnVirtualMFADeviceProps | Properties for defining a |
CommonGrantOptions | Basic options for a grant operation. |
ComparablePrincipal | Helper class for working with |
CompositeDependable | Composite dependable. |
CompositePrincipal | Represents a principal that has multiple types of principals. |
CustomizeRolesOptions | Options for customizing IAM role creation. |
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 |
FromRoleNameOptions | Options allowing customizing the behavior of |
Grant | Result of a grant() operation. |
GrantOnPrincipalAndResourceOptions | Options for a grant operation to both identity and resource. |
GrantOnPrincipalOptions | Options for a grant operation that only applies to principals. |
GrantWithResourceOptions | 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. |
InstanceProfile | IAM Instance Profile. |
InstanceProfileAttributes | Attributes of an Instance Profile. |
InstanceProfileProps | Properties of an Instance Profile. |
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 | 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 | Initialization properties for |
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 inline IAM policy with IAM users, roles, or groups. For more information about IAM policies, see Overview of IAM Policies in the IAM User Guide guide. |
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. |
SamlConsolePrincipal | Principal entity that represents a SAML federated identity provider for programmatic and AWS Management Console access. |
SamlMetadataDocument | A SAML metadata document. |
SamlPrincipal | Principal entity that represents a SAML federated identity provider. |
SamlProvider | A SAML provider. |
SamlProviderProps | Properties for a SAML provider. |
ServicePrincipal | An IAM principal that represents an AWS service (i.e. |
ServicePrincipalOpts | Options for a service principal. |
SessionTagsPrincipal | Enables session tags on role assumptions from a principal. |
StarPrincipal | A principal that uses a literal '*' in the IAM JSON language. |
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. |
WithoutPolicyUpdatesOptions | Options for the |
Interfaces
CfnGroup.IPolicyProperty | Contains information about an attached policy. |
CfnRole.IPolicyProperty | Contains information about an attached policy. |
CfnUser.ILoginProfileProperty | Creates a password for the specified user, giving the user the ability to access AWS services through the AWS Management Console . |
CfnUser.IPolicyProperty | Contains information about an attached policy. |
IAccessKey | Represents an IAM Access Key. |
IAccessKeyProps | Properties for defining an IAM access key. |
IAddToPrincipalPolicyResult | Result of calling |
IAddToResourcePolicyResult | Result of calling addToResourcePolicy. |
IAssumeRolePrincipal | A type of principal that has more control over its own representation in AssumeRolePolicyDocuments. |
ICfnAccessKeyProps | Properties for defining a |
ICfnGroupPolicyProps | Properties for defining a |
ICfnGroupProps | Properties for defining a |
ICfnInstanceProfileProps | Properties for defining a |
ICfnManagedPolicyProps | Properties for defining a |
ICfnOIDCProviderProps | Properties for defining a |
ICfnPolicyProps | Properties for defining a |
ICfnRolePolicyProps | Properties for defining a |
ICfnRoleProps | Properties for defining a |
ICfnSAMLProviderProps | Properties for defining a |
ICfnServerCertificateProps | Properties for defining a |
ICfnServiceLinkedRoleProps | Properties for defining a |
ICfnUserPolicyProps | Properties for defining a |
ICfnUserProps | Properties for defining a |
ICfnUserToGroupAdditionProps | Properties for defining a |
ICfnVirtualMFADeviceProps | Properties for defining a |
ICommonGrantOptions | Basic options for a grant operation. |
IComparablePrincipal | Interface for principals that can be compared. |
ICustomizeRolesOptions | Options for customizing IAM role creation. |
IFromRoleArnOptions | Options allowing customizing the behavior of |
IFromRoleNameOptions | Options allowing customizing the behavior of |
IGrantable | Any object that has an associated principal that a permission can be granted to. |
IGrantOnPrincipalAndResourceOptions | Options for a grant operation to both identity and resource. |
IGrantOnPrincipalOptions | Options for a grant operation that only applies to principals. |
IGrantWithResourceOptions | 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. |
IInstanceProfile | Represents an IAM Instance Profile. |
IInstanceProfileAttributes | Attributes of an Instance Profile. |
IInstanceProfileProps | Properties of an Instance Profile. |
ILazyRoleProps | Properties for defining a LazyRole. |
IManagedPolicy | A managed policy. |
IManagedPolicyProps | Properties for defining an IAM managed policy. |
IOpenIdConnectProvider | Represents an IAM OpenID Connect provider. |
IOpenIdConnectProviderProps | Initialization properties for |
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. |
ISamlProvider | A SAML provider. |
ISamlProviderProps | Properties for a SAML provider. |
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. |
IWithoutPolicyUpdatesOptions | Options for the |