Skip to content
v2.273.0

PolicyStatement Class ​

Represents a statement in an IAM policy document.

Example ​

ts
    // Add gateway endpoints when creating the VPC
    const vpc = new ec2.Vpc(this, 'MyVpc', {
      gatewayEndpoints: {
        S3: {
          service: ec2.GatewayVpcEndpointAwsService.S3,
        },
      },
    });

    // Alternatively gateway endpoints can be added on the VPC
    const dynamoDbEndpoint = vpc.addGatewayEndpoint('DynamoDbEndpoint', {
      service: ec2.GatewayVpcEndpointAwsService.DYNAMODB,
    });

    // This allows to customize the endpoint policy
    dynamoDbEndpoint.addToPolicy(
      new iam.PolicyStatement({ // Restrict to listing and describing tables
        principals: [new iam.AnyPrincipal()],
        actions: ['dynamodb:DescribeTable', 'dynamodb:ListTables'],
        resources: ['*'],
      }));

    // Add an interface endpoint
    vpc.addInterfaceEndpoint('EcrDockerEndpoint', {
      service: ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER,

      // Uncomment the following to allow more fine-grained control over
      // who can access the endpoint via the '.connections' object.
      // open: false
    });
python
# Add gateway endpoints when creating the VPC
vpc = ec2.Vpc(self, "MyVpc",
    gateway_endpoints={
        "S3": cdk.aws_ec2.GatewayVpcEndpointOptions(
            service=ec2.GatewayVpcEndpointAwsService.S3
        )
    }
)

# Alternatively gateway endpoints can be added on the VPC
dynamo_db_endpoint = vpc.add_gateway_endpoint("DynamoDbEndpoint",
    service=ec2.GatewayVpcEndpointAwsService.DYNAMODB
)

# This allows to customize the endpoint policy
dynamo_db_endpoint.add_to_policy(
    iam.PolicyStatement( # Restrict to listing and describing tables
        principals=[iam.AnyPrincipal()],
        actions=["dynamodb:DescribeTable", "dynamodb:ListTables"],
        resources=["*"]))

# Add an interface endpoint
vpc.add_interface_endpoint("EcrDockerEndpoint",
    service=ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER
)
java
// Add gateway endpoints when creating the VPC
Vpc vpc = Vpc.Builder.create(this, "MyVpc")
        .gatewayEndpoints(Map.of(
                "S3", GatewayVpcEndpointOptions.builder()
                        .service(GatewayVpcEndpointAwsService.S3)
                        .build()))
        .build();

// Alternatively gateway endpoints can be added on the VPC
GatewayVpcEndpoint dynamoDbEndpoint = vpc.addGatewayEndpoint("DynamoDbEndpoint", GatewayVpcEndpointOptions.builder()
        .service(GatewayVpcEndpointAwsService.DYNAMODB)
        .build());

// This allows to customize the endpoint policy
dynamoDbEndpoint.addToPolicy(
PolicyStatement.Builder.create() // Restrict to listing and describing tables
        .principals(List.of(new AnyPrincipal()))
        .actions(List.of("dynamodb:DescribeTable", "dynamodb:ListTables"))
        .resources(List.of("*")).build());

// Add an interface endpoint
vpc.addInterfaceEndpoint("EcrDockerEndpoint", InterfaceVpcEndpointOptions.builder()
        .service(InterfaceVpcEndpointAwsService.ECR_DOCKER)
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
// Add gateway endpoints when creating the VPC
var vpc = new Vpc(this, "MyVpc", new VpcProps {
    GatewayEndpoints = new Dictionary<string, GatewayVpcEndpointOptions> {
        { "S3", new GatewayVpcEndpointOptions {
            Service = GatewayVpcEndpointAwsService.S3
        } }
    }
});

// Alternatively gateway endpoints can be added on the VPC
var dynamoDbEndpoint = vpc.AddGatewayEndpoint("DynamoDbEndpoint", new GatewayVpcEndpointOptions {
    Service = GatewayVpcEndpointAwsService.DYNAMODB
});

// This allows to customize the endpoint policy
dynamoDbEndpoint.AddToPolicy(
new PolicyStatement(new PolicyStatementProps {  // Restrict to listing and describing tables
    Principals = new [] { new AnyPrincipal() },
    Actions = new [] { "dynamodb:DescribeTable", "dynamodb:ListTables" },
    Resources = new [] { "*" } }));

// Add an interface endpoint
vpc.AddInterfaceEndpoint("EcrDockerEndpoint", new InterfaceVpcEndpointOptions {
    Service = InterfaceVpcEndpointAwsService.ECR_DOCKER
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Add gateway endpoints when creating the VPC
vpc := ec2.NewVpc(this, jsii.String("MyVpc"), &VpcProps{
	GatewayEndpoints: map[string]GatewayVpcEndpointOptions{
		"S3": &GatewayVpcEndpointOptions{
			"service": ec2.GatewayVpcEndpointAwsService_S3(),
		},
	},
})

// Alternatively gateway endpoints can be added on the VPC
dynamoDbEndpoint := vpc.addGatewayEndpoint(jsii.String("DynamoDbEndpoint"), &GatewayVpcEndpointOptions{
	Service: ec2.GatewayVpcEndpointAwsService_DYNAMODB(),
})

// This allows to customize the endpoint policy
dynamoDbEndpoint.AddToPolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
	 // Restrict to listing and describing tables
	Principals: []IPrincipal{
		iam.NewAnyPrincipal(),
	},
	Actions: []*string{
		jsii.String("dynamodb:DescribeTable"),
		jsii.String("dynamodb:ListTables"),
	},
	Resources: []*string{
		jsii.String("*"),
	},
}))

// Add an interface endpoint
vpc.addInterfaceEndpoint(jsii.String("EcrDockerEndpoint"), &InterfaceVpcEndpointOptions{
	Service: ec2.InterfaceVpcEndpointAwsService_ECR_DOCKER(),
})

Initializer ​

ts
new PolicyStatement(props?: PolicyStatementProps)
python
PolicyStatement(props: typing.Optional[PolicyStatementProps] = None)
java
new PolicyStatement(PolicyStatementProps props)
csharp
new PolicyStatement(PolicyStatementProps? props = null)
go
NewPolicyStatement(Props PolicyStatementProps)

Properties ​

actionsstring[]actionstyping.List[str]actionsList<String>Actionsstring[]Actions*[]*stringrequired#
The Actions added to this statement.
conditionsanyconditionsAnyconditionsObjectConditionsobjectConditionsinterface{}required#
The conditions added to this statement.
effectEffecteffectEffecteffectEffectEffectEffectEffectEffectrequired#
Whether to allow or deny the actions in this statement Set effect for this statement.
frozenbooleanfrozenboolfrozenBooleanFrozenboolFrozen*boolrequired#
Whether the PolicyStatement has been frozen.

The statement object is frozen when freeze() is called.

hasPrincipalbooleanhas_principalboolhasPrincipalBooleanHasPrincipalboolHasPrincipal*boolrequired#
Indicates if this permission has a "Principal" section.
hasResourcebooleanhas_resourceboolhasResourceBooleanHasResourceboolHasResource*boolrequired#
Indicates if this permission has at least one resource associated with it.
notActionsstring[]not_actionstyping.List[str]notActionsList<String>NotActionsstring[]NotActions*[]*stringrequired#
The NotActions added to this statement.
notPrincipalsIPrincipal[]not_principalstyping.List[IPrincipal]notPrincipalsList<IPrincipal>NotPrincipalsIPrincipal[]NotPrincipals*[]IPrincipalrequired#
The NotPrincipals added to this statement.
notResourcesstring[]not_resourcestyping.List[str]notResourcesList<String>NotResourcesstring[]NotResources*[]*stringrequired#
The NotResources added to this statement.
principalsIPrincipal[]principalstyping.List[IPrincipal]principalsList<IPrincipal>PrincipalsIPrincipal[]Principals*[]IPrincipalrequired#
The Principals added to this statement.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
resourcesstring[]resourcestyping.List[str]resourcesList<String>Resourcesstring[]Resources*[]*stringrequired#
The Resources added to this statement.
sidstringsidstrsidStringSidstringSid*string#
Statement ID for this statement Set Statement ID for this statement.

Methods ​

addAccountCondition(accountId: string): voiddef add_account_condition(self, account_id: str) -> Nonepublic void addAccountCondition(String accountId)public void AddAccountCondition(string accountId)func AddAccountCondition(AccountId *string)#
Add a `StringEquals` condition that limits to a given account from `sts:ExternalId`.

This method can only be called once: subsequent calls will overwrite earlier calls.

addAccountRootPrincipal(): voiddef add_account_root_principal(self, ) -> Nonepublic void addAccountRootPrincipal()public void AddAccountRootPrincipal()func AddAccountRootPrincipal()#
Adds an AWS account root user principal to this policy statement.
addActions(...actions: string[]): voiddef add_actions(self, actions: str) -> Nonepublic void addActions(String actions)public void AddActions(string actions)func AddActions(Actions *string)#
Specify allowed actions into the "Action" section of the policy statement.
1 parameter

Parameters

  • actionsactionsactionsactionsActions — actions that will be allowed.
addAllResources(): voiddef add_all_resources(self, ) -> Nonepublic void addAllResources()public void AddAllResources()func AddAllResources()#
Adds a ``"*"`` resource to this statement.
addAnyPrincipal(): voiddef add_any_principal(self, ) -> Nonepublic void addAnyPrincipal()public void AddAnyPrincipal()func AddAnyPrincipal()#
Adds all identities in all accounts ("*") to this policy statement.
addArnPrincipal(arn: string): voiddef add_arn_principal(self, arn: str) -> Nonepublic void addArnPrincipal(String arn)public void AddArnPrincipal(string arn)func AddArnPrincipal(Arn *string)#
Specify a principal using the ARN identifier of the principal.

You cannot specify IAM groups and instance profiles as principals.

1 parameter

Parameters

  • arnarnarnarnArn — ARN identifier of AWS account, IAM user, or IAM role (i.e. arn:aws:iam::123456789012:user/user-name).
addAwsAccountPrincipal(accountId: string): voiddef add_aws_account_principal(self, account_id: str) -> Nonepublic void addAwsAccountPrincipal(String accountId)public void AddAwsAccountPrincipal(string accountId)func AddAwsAccountPrincipal(AccountId *string)#
Specify AWS account ID as the principal entity to the "Principal" section of a policy statement.
addCanonicalUserPrincipal(canonicalUserId: string): voiddef add_canonical_user_principal(self, canonical_user_id: str) -> Nonepublic void addCanonicalUserPrincipal(String canonicalUserId)public void AddCanonicalUserPrincipal(string canonicalUserId)func AddCanonicalUserPrincipal(CanonicalUserId *string)#
Adds a canonical user ID principal to this policy document.
1 parameter

Parameters

  • canonicalUserIdcanonical_user_idcanonicalUserIdcanonicalUserIdCanonicalUserId — unique identifier assigned by AWS for every account.
addCondition(key: string, value: any): voiddef add_condition(self, key: str, value: Any) -> Nonepublic void addCondition(String key, Object value)public void AddCondition(string key, object value)func AddCondition(Key *string, Value interface{})#
Add a condition to the Policy.
notes

If multiple calls are made to add a condition with the same operator and field, only the last one wins. For example:

ts
declare const stmt: iam.PolicyStatement;

stmt.addCondition('StringEquals', { 'aws:SomeField': '1' });
stmt.addCondition('StringEquals', { 'aws:SomeField': '2' });

Will end up with the single condition StringEquals: { 'aws:SomeField': '2' }.

If you meant to add a condition to say that the field can be either 1 or 2, write this:

ts
declare const stmt: iam.PolicyStatement;

stmt.addCondition('StringEquals', { 'aws:SomeField': ['1', '2'] });
addConditions(conditions: { [key: string]: any }): voiddef add_conditions(self, conditions: typing.Mapping[str, Any]) -> Nonepublic void addConditions(Map<String, Object> conditions)public void AddConditions(IDictionary<string, object> conditions)func AddConditions(Conditions *map[string]interface{})#
Add multiple conditions to the Policy.

See the addCondition function for a caveat on calling this method multiple times.

addFederatedPrincipal(federated: any, conditions: { [key: string]: any }): voiddef add_federated_principal(self, federated: Any, conditions: typing.Mapping[str, Any]) -> Nonepublic void addFederatedPrincipal(Object federated, Map<String, Object> conditions)public void AddFederatedPrincipal(object federated, IDictionary<string, object> conditions)func AddFederatedPrincipal(Federated interface{}, Conditions *map[string]interface{})#
Adds a federated identity provider such as Amazon Cognito to this policy statement.
2 parameters

Parameters

  • federatedfederatedfederatedfederatedFederated — federated identity provider (i.e. 'cognito-identity.amazonaws.com').
  • conditionsconditionsconditionsconditionsConditions — The conditions under which the policy is in effect.
addNotActions(...notActions: string[]): voiddef add_not_actions(self, not_actions: str) -> Nonepublic void addNotActions(String notActions)public void AddNotActions(string notActions)func AddNotActions(NotActions *string)#
Explicitly allow all actions except the specified list of actions into the "NotAction" section of the policy document.
1 parameter

Parameters

  • notActionsnot_actionsnotActionsnotActionsNotActions — actions that will be denied.
addNotPrincipals(...notPrincipals: IPrincipal[]): voiddef add_not_principals(self, not_principals: IPrincipal) -> Nonepublic void addNotPrincipals(IPrincipal notPrincipals)public void AddNotPrincipals(IPrincipal notPrincipals)func AddNotPrincipals(NotPrincipals IPrincipal)#
Specify principals that is not allowed or denied access to the "NotPrincipal" section of a policy statement.
1 parameter

Parameters

  • notPrincipalsnot_principalsnotPrincipalsnotPrincipalsNotPrincipals — IAM principals that will be denied access.
addNotResources(...arns: string[]): voiddef add_not_resources(self, arns: str) -> Nonepublic void addNotResources(String arns)public void AddNotResources(string arns)func AddNotResources(Arns *string)#
Specify resources that this policy statement will not apply to in the "NotResource" section of this policy statement.

All resources except the specified list will be matched.

1 parameter

Parameters

  • arnsarnsarnsarnsArns — Amazon Resource Names (ARNs) of the resources that this policy statement does not apply to.
addPrincipals(...principals: IPrincipal[]): voiddef add_principals(self, principals: IPrincipal) -> Nonepublic void addPrincipals(IPrincipal principals)public void AddPrincipals(IPrincipal principals)func AddPrincipals(Principals IPrincipal)#
Adds principals to the "Principal" section of a policy statement.
1 parameter

Parameters

  • principalsprincipalsprincipalsprincipalsPrincipals — IAM principals that will be added.
addResources(...arns: string[]): voiddef add_resources(self, arns: str) -> Nonepublic void addResources(String arns)public void AddResources(string arns)func AddResources(Arns *string)#
Specify resources that this policy statement applies into the "Resource" section of this policy statement.
1 parameter

Parameters

  • arnsarnsarnsarnsArns — Amazon Resource Names (ARNs) of the resources that this policy statement applies to.
addServicePrincipal(service: string, opts?: ServicePrincipalOpts): voiddef add_service_principal(self, service: str, opts: typing.Optional[ServicePrincipalOpts] = None) -> Nonepublic void addServicePrincipal(String service, ServicePrincipalOpts opts)public void AddServicePrincipal(string service, ServicePrincipalOpts? opts = null)func AddServicePrincipal(Service *string, Opts ServicePrincipalOpts)#
Adds a service principal to this policy statement.
2 parameters

Parameters

  • serviceserviceserviceserviceService — the service name for which a service principal is requested (e.g: s3.amazonaws.com).
  • optsoptsoptsoptsOpts — options for adding the service principal (such as specifying a principal in a different region).
addSourceAccountCondition(accountId: string): voiddef add_source_account_condition(self, account_id: str) -> Nonepublic void addSourceAccountCondition(String accountId)public void AddSourceAccountCondition(string accountId)func AddSourceAccountCondition(AccountId *string)#
Add an `StringEquals` condition that limits to a given account from `aws:SourceAccount`.

This method can only be called once: subsequent calls will overwrite earlier calls.

addSourceArnCondition(arn: string): voiddef add_source_arn_condition(self, arn: str) -> Nonepublic void addSourceArnCondition(String arn)public void AddSourceArnCondition(string arn)func AddSourceArnCondition(Arn *string)#
Add an `ArnEquals` condition that limits to a given resource arn from `aws:SourceArn`.

This method can only be called once: subsequent calls will overwrite earlier calls.

copy(overrides?: PolicyStatementProps): PolicyStatement // chainabledef copy(self, overrides: typing.Optional[PolicyStatementProps] = None) -> PolicyStatementpublic PolicyStatement copy(PolicyStatementProps overrides)public PolicyStatement Copy(PolicyStatementProps? overrides = null)func Copy(Overrides PolicyStatementProps) PolicyStatement#
Create a new `PolicyStatement` with the same exact properties as this one, except for the overrides.
freeze(): PolicyStatement // chainabledef freeze(self, ) -> PolicyStatementpublic PolicyStatement freeze()public PolicyStatement Freeze()func Freeze() PolicyStatement#
Make the PolicyStatement immutable.
notes

After calling this, any of the addXxx() methods will throw an exception.

Libraries that lazily generate statement bodies can override this method to fill the actual PolicyStatement fields. Be aware that this method may be called multiple times.

fromJson(obj: any): PolicyStatement // chainable@staticmethod def from_json(obj: Any) -> PolicyStatementpublic static PolicyStatement fromJson(Object obj)public static PolicyStatement FromJson(object obj)func FromJson(Obj interface{}) PolicyStatementstatic#
Creates a new PolicyStatement based on the object provided.

This will accept an object created from the .toJSON() call

1 parameter

Parameters

  • objobjobjobjObj — the PolicyStatement in object form.
toJSON(): anydef to_json(self, ) -> Anypublic Object toJSON()public object ToJSON()func ToJSON() interface{}#
JSON-ify the statement.

Used when JSON.stringify() is called

toStatementJson(): anydef to_statement_json(self, ) -> Anypublic Object toStatementJson()public object ToStatementJson()func ToStatementJson() interface{}#
JSON-ify the policy statement.

Used when JSON.stringify() is called

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
String representation of this policy statement.
validateForAnyPolicy(): string[]def validate_for_any_policy(self, ) -> typing.List[str]public List<String> validateForAnyPolicy()public string[] ValidateForAnyPolicy()func ValidateForAnyPolicy() *[]*string#
Validate that the policy statement satisfies base requirements for a policy.
returns

Returns: An array of validation error messages, or an empty array if the statement is valid.

validateForIdentityPolicy(): string[]def validate_for_identity_policy(self, ) -> typing.List[str]public List<String> validateForIdentityPolicy()public string[] ValidateForIdentityPolicy()func ValidateForIdentityPolicy() *[]*string#
Validate that the policy statement satisfies all requirements for an identity-based policy.
returns

Returns: An array of validation error messages, or an empty array if the statement is valid.

validateForResourcePolicy(options?: ResourcePolicyValidationOptions): string[]def validate_for_resource_policy(self, options: typing.Optional[ResourcePolicyValidationOptions] = None) -> typing.List[str]public List<String> validateForResourcePolicy(ResourcePolicyValidationOptions options)public string[] ValidateForResourcePolicy(ResourcePolicyValidationOptions? options = null)func ValidateForResourcePolicy(Options ResourcePolicyValidationOptions) *[]*string#
Validate that the policy statement satisfies all requirements for a resource-based policy.
1 parameter · returns

Parameters

  • optionsoptionsoptionsoptionsOptions — Optional validation options.

Returns: An array of validation error messages, or an empty array if the statement is valid.

validateForTrustPolicy(): string[]def validate_for_trust_policy(self, ) -> typing.List[str]public List<String> validateForTrustPolicy()public string[] ValidateForTrustPolicy()func ValidateForTrustPolicy() *[]*string#
Validate that the policy statement satisfies all requirements for a trust policy (assume role policy).

Trust policies are a special type of resource-based policy where the resource is implicit (the role itself).

returns

Returns: An array of validation error messages, or an empty array if the statement is valid.