Skip to content
v2.273.0

ManagedPolicy L2 construct ​

Managed policy.

Example ​

ts
declare const build: gamelift.Build;
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.CompositePrincipal(new iam.ServicePrincipal('gamelift.amazonaws.com'))
});
role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'));

const fleet = new gamelift.BuildFleet(this, 'Game server fleet', {
  fleetName: 'test-fleet',
  content: build,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE),
  runtimeConfiguration: {
    serverProcesses: [{
      launchPath: '/local/game/GameLiftExampleServer.x86_64',
    }]
  },
  role: role
});

// Actions can also be grantted through dedicated method
fleet.grant(role, 'gamelift:ListFleets');
python
# build: gamelift.Build

role = iam.Role(self, "Role",
    assumed_by=iam.CompositePrincipal(iam.ServicePrincipal("gamelift.amazonaws.com"))
)
role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchAgentServerPolicy"))

fleet = gamelift.BuildFleet(self, "Game server fleet",
    fleet_name="test-fleet",
    content=build,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE),
    runtime_configuration=gamelift.RuntimeConfiguration(
        server_processes=[gamelift.ServerProcess(
            launch_path="/local/game/GameLiftExampleServer.x86_64"
        )]
    ),
    role=role
)

# Actions can also be grantted through dedicated method
fleet.grant(role, "gamelift:ListFleets")
java
Build build;

Role role = Role.Builder.create(this, "Role")
        .assumedBy(new CompositePrincipal(new ServicePrincipal("gamelift.amazonaws.com")))
        .build();
role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));

BuildFleet fleet = BuildFleet.Builder.create(this, "Game server fleet")
        .fleetName("test-fleet")
        .content(build)
        .instanceType(InstanceType.of(InstanceClass.C5, InstanceSize.LARGE))
        .runtimeConfiguration(RuntimeConfiguration.builder()
                .serverProcesses(List.of(ServerProcess.builder()
                        .launchPath("/local/game/GameLiftExampleServer.x86_64")
                        .build()))
                .build())
        .role(role)
        .build();

// Actions can also be grantted through dedicated method
fleet.grant(role, "gamelift:ListFleets");
csharp
// Install: dotnet add package Amazon.CDK.Lib
Build build;

var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new CompositePrincipal(new ServicePrincipal("gamelift.amazonaws.com"))
});
role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));

var fleet = new BuildFleet(this, "Game server fleet", new BuildFleetProps {
    FleetName = "test-fleet",
    Content = build,
    InstanceType = InstanceType.Of(InstanceClass.C5, InstanceSize.LARGE),
    RuntimeConfiguration = new RuntimeConfiguration {
        ServerProcesses = new [] { new ServerProcess {
            LaunchPath = "/local/game/GameLiftExampleServer.x86_64"
        } }
    },
    Role = role
});

// Actions can also be grantted through dedicated method
fleet.Grant(role, "gamelift:ListFleets");
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var build Build

role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewCompositePrincipal(iam.NewServicePrincipal(jsii.String("gamelift.amazonaws.com"))),
})
role.AddManagedPolicy(iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("CloudWatchAgentServerPolicy")))

fleet := gamelift.NewBuildFleet(this, jsii.String("Game server fleet"), &BuildFleetProps{
	FleetName: jsii.String("test-fleet"),
	Content: build,
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_C5, ec2.InstanceSize_LARGE),
	RuntimeConfiguration: &RuntimeConfiguration{
		ServerProcesses: []ServerProcess{
			&ServerProcess{
				LaunchPath: jsii.String("/local/game/GameLiftExampleServer.x86_64"),
			},
		},
	},
	Role: role,
})

// Actions can also be grantted through dedicated method
fleet.Grant(role, jsii.String("gamelift:ListFleets"))

Initializer ​

ts
new ManagedPolicy(scope: Construct, id: string, props?: ManagedPolicyProps)
python
ManagedPolicy(scope: Construct, id: str, props: typing.Optional[ManagedPolicyProps] = None)
java
new ManagedPolicy(Construct scope, String id, ManagedPolicyProps props)
csharp
new ManagedPolicy(Construct scope, string id, ManagedPolicyProps? props = null)
go
NewManagedPolicy(Scope Construct, Id *string, Props ManagedPolicyProps)

Construct Props ​

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= empty#
A description of the managed policy.

Typically used to store information about the permissions defined in the policy. For example, "Grants access to production DynamoDB tables." The policy description is immutable. After a value is assigned, it cannot be changed.

documentPolicyDocumentdocumentPolicyDocumentdocumentPolicyDocumentDocumentPolicyDocumentDocumentPolicyDocument= An empty policy.#
Initial PolicyDocument to use for this ManagedPolicy.

If omited, any PolicyStatement provided in the statements property will be applied against the empty default PolicyDocument.

groupsIGroupRef[]groupstyping.List[IGroupRef]groupsList<IGroupRef>GroupsIGroupRef[]Groups*[]IGroupRef= No groups.#
Groups to attach this policy to.

You can also use attachToGroup(group) to attach this policy to a group.

managedPolicyNamestringmanaged_policy_namestrmanagedPolicyNameStringManagedPolicyNamestringManagedPolicyName*string= A name is automatically generate…#
The name of the managed policy.

If you specify multiple policies for an entity, specify unique names. For example, if you specify a list of policies for an IAM role, each policy must have a unique name.

default

Default: A name is automatically generated.

pathstringpathstrpathStringPathstringPath*string= "/"#
The path for the policy.
notes

This parameter allows (through its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (\u0021) through the DEL character (\u007F), including most punctuation characters, digits, and upper and lowercased letters.

For more information about paths, see IAM Identifiers in the IAM User Guide.

rolesIRole[]rolestyping.List[IRole]rolesList<IRole>RolesIRole[]Roles*[]IRole= No roles.#
Roles to attach this policy to.

You can also use attachToRole(role) to attach this policy to a role.

statementsPolicyStatement[]statementstyping.List[PolicyStatement]statementsList<PolicyStatement>StatementsPolicyStatement[]Statements*[]PolicyStatement= No statements.#
Initial set of permissions to add to this policy document.

You can also use addPermission(statement) to add permissions later.

usersIUser[]userstyping.List[IUser]usersList<IUser>UsersIUser[]Users*[]IUser= No users.#
Users to attach this policy to.

You can also use attachToUser(user) to attach this policy to a user.

Properties ​

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*stringrequired#
The description of this policy.
documentPolicyDocumentdocumentPolicyDocumentdocumentPolicyDocumentDocumentPolicyDocumentDocumentPolicyDocumentrequired#
The policy document.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
The principal to grant permissions to.
managedPolicyArnstringmanaged_policy_arnstrmanagedPolicyArnStringManagedPolicyArnstringManagedPolicyArn*stringrequired#
Returns the ARN of this managed policy.
managedPolicyNamestringmanaged_policy_namestrmanagedPolicyNameStringManagedPolicyNamestringManagedPolicyName*stringrequired#
The name of this policy.
managedPolicyRefManagedPolicyReferencemanaged_policy_refManagedPolicyReferencemanagedPolicyRefManagedPolicyReferenceManagedPolicyRefManagedPolicyReferenceManagedPolicyRefManagedPolicyReferencerequired#
A reference to a ManagedPolicy resource.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
pathstringpathstrpathStringPathstringPath*stringrequired#
The path of this policy.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

addStatements(...statement: PolicyStatement[]): voiddef add_statements(self, statement: PolicyStatement) -> Nonepublic void addStatements(PolicyStatement statement)public void AddStatements(PolicyStatement statement)func AddStatements(Statement PolicyStatement)#
Adds a statement to the policy document.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

attachToGroup(group: IGroupRef): voiddef attach_to_group(self, group: IGroupRef) -> Nonepublic void attachToGroup(IGroupRef group)public void AttachToGroup(IGroupRef group)func AttachToGroup(Group IGroupRef)#
Attaches this policy to a group.
attachToRole(role: IRole): voiddef attach_to_role(self, role: IRole) -> Nonepublic void attachToRole(IRole role)public void AttachToRole(IRole role)func AttachToRole(Role IRole)#
Attaches this policy to a role.
attachToUser(user: IUserRef): voiddef attach_to_user(self, user: IUserRef) -> Nonepublic void attachToUser(IUserRef user)public void AttachToUser(IUserRef user)func AttachToUser(User IUserRef)#
Attaches this policy to a user.
fromAwsManagedPolicyName(managedPolicyName: string): IManagedPolicy@staticmethod def from_aws_managed_policy_name(managed_policy_name: str) -> IManagedPolicypublic static IManagedPolicy fromAwsManagedPolicyName(String managedPolicyName)public static IManagedPolicy FromAwsManagedPolicyName(string managedPolicyName)func FromAwsManagedPolicyName(ManagedPolicyName *string) IManagedPolicystatic#
Import a managed policy from one of the policies that AWS manages.
notes

For this managed policy, you only need to know the name to be able to use it.

Some managed policy names start with "service-role/", some start with "job-function/", and some don't start with anything. Include the prefix when constructing this object.

fromManagedPolicyArn(scope: Construct, id: string, managedPolicyArn: string): IManagedPolicy@staticmethod def from_managed_policy_arn(scope: Construct, id: str, managed_policy_arn: str) -> IManagedPolicypublic static IManagedPolicy fromManagedPolicyArn(Construct scope, String id, String managedPolicyArn)public static IManagedPolicy FromManagedPolicyArn(Construct scope, string id, string managedPolicyArn)func FromManagedPolicyArn(Scope Construct, Id *string, ManagedPolicyArn *string) IManagedPolicystatic#
Import an external managed policy by ARN.
notes · 3 parameters

For this managed policy, you only need to know the ARN to be able to use it. This can be useful if you got the ARN from a CloudFormation Export.

If the imported Managed Policy ARN is a Token (such as a CfnParameter.valueAsString or a Fn.importValue()) and the referenced managed policy has a path (like arn:...:policy/AdminPolicy/AdminAllow), the managedPolicyName property will not resolve to the correct value. Instead it will resolve to the first path component. We unfortunately cannot express the correct calculation of the full path name as a CloudFormation expression. In this scenario the Managed Policy ARN should be supplied without the path in order to resolve the correct managed policy resource.

Parameters

  • scopescopescopescopeScope — construct scope.
  • ididididId — construct id.
  • managedPolicyArnmanaged_policy_arnmanagedPolicyArnmanagedPolicyArnManagedPolicyArn — the ARN of the managed policy to import.
fromManagedPolicyName(scope: Construct, id: string, managedPolicyName: string): IManagedPolicy@staticmethod def from_managed_policy_name(scope: Construct, id: str, managed_policy_name: str) -> IManagedPolicypublic static IManagedPolicy fromManagedPolicyName(Construct scope, String id, String managedPolicyName)public static IManagedPolicy FromManagedPolicyName(Construct scope, string id, string managedPolicyName)func FromManagedPolicyName(Scope Construct, Id *string, ManagedPolicyName *string) IManagedPolicystatic#
Import a customer managed policy from the managedPolicyName.

For this managed policy, you only need to know the name to be able to use it.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.