Skip to content
v2.273.0

PolicyDocument Class ​

A PolicyDocument is a collection of statements.

Example ​

ts
import * as iam from 'aws-cdk-lib/aws-iam';

const myFileSystemPolicy = new iam.PolicyDocument({
  statements: [new iam.PolicyStatement({
    actions: [
      'elasticfilesystem:ClientWrite',
      'elasticfilesystem:ClientMount',
    ],
    principals: [new iam.AccountRootPrincipal()],
    resources: ['*'],
    conditions: {
      Bool: {
        'elasticfilesystem:AccessedViaMountTarget': 'true',
      },
    },
  })],
});

const fileSystem = new efs.FileSystem(this, 'MyEfsFileSystem', {
  vpc: new ec2.Vpc(this, 'VPC'),
  fileSystemPolicy: myFileSystemPolicy,
});
python
import aws_cdk.aws_iam as iam


my_file_system_policy = iam.PolicyDocument(
    statements=[iam.PolicyStatement(
        actions=["elasticfilesystem:ClientWrite", "elasticfilesystem:ClientMount"
        ],
        principals=[iam.AccountRootPrincipal()],
        resources=["*"],
        conditions={
            "Bool": {
                "elasticfilesystem:AccessedViaMountTarget": "true"
            }
        }
    )]
)

file_system = efs.FileSystem(self, "MyEfsFileSystem",
    vpc=ec2.Vpc(self, "VPC"),
    file_system_policy=my_file_system_policy
)
java
import software.amazon.awscdk.services.iam.*;


PolicyDocument myFileSystemPolicy = PolicyDocument.Builder.create()
        .statements(List.of(PolicyStatement.Builder.create()
                .actions(List.of("elasticfilesystem:ClientWrite", "elasticfilesystem:ClientMount"))
                .principals(List.of(new AccountRootPrincipal()))
                .resources(List.of("*"))
                .conditions(Map.of(
                        "Bool", Map.of(
                                "elasticfilesystem:AccessedViaMountTarget", "true")))
                .build()))
        .build();

FileSystem fileSystem = FileSystem.Builder.create(this, "MyEfsFileSystem")
        .vpc(new Vpc(this, "VPC"))
        .fileSystemPolicy(myFileSystemPolicy)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.IAM;


var myFileSystemPolicy = new PolicyDocument(new PolicyDocumentProps {
    Statements = new [] { new PolicyStatement(new PolicyStatementProps {
        Actions = new [] { "elasticfilesystem:ClientWrite", "elasticfilesystem:ClientMount" },
        Principals = new [] { new AccountRootPrincipal() },
        Resources = new [] { "*" },
        Conditions = new Dictionary<string, object> {
            { "Bool", new Dictionary<string, string> {
                { "elasticfilesystem:AccessedViaMountTarget", "true" }
            } }
        }
    }) }
});

var fileSystem = new FileSystem(this, "MyEfsFileSystem", new FileSystemProps {
    Vpc = new Vpc(this, "VPC"),
    FileSystemPolicy = myFileSystemPolicy
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"


myFileSystemPolicy := iam.NewPolicyDocument(&PolicyDocumentProps{
	Statements: []PolicyStatement{
		iam.NewPolicyStatement(&PolicyStatementProps{
			Actions: []*string{
				jsii.String("elasticfilesystem:ClientWrite"),
				jsii.String("elasticfilesystem:ClientMount"),
			},
			Principals: []IPrincipal{
				iam.NewAccountRootPrincipal(),
			},
			Resources: []*string{
				jsii.String("*"),
			},
			Conditions: map[string]interface{}{
				"Bool": map[string]*string{
					"elasticfilesystem:AccessedViaMountTarget": jsii.String("true"),
				},
			},
		}),
	},
})

fileSystem := efs.NewFileSystem(this, jsii.String("MyEfsFileSystem"), &FileSystemProps{
	Vpc: ec2.NewVpc(this, jsii.String("VPC")),
	FileSystemPolicy: myFileSystemPolicy,
})

Initializer ​

ts
new PolicyDocument(props?: PolicyDocumentProps)
python
PolicyDocument(props: typing.Optional[PolicyDocumentProps] = None)
java
new PolicyDocument(PolicyDocumentProps props)
csharp
new PolicyDocument(PolicyDocumentProps? props = null)
go
NewPolicyDocument(Props PolicyDocumentProps)

Properties ​

creationStackstring[]creation_stacktyping.List[str]creationStackList<String>CreationStackstring[]CreationStack*[]*stringrequired#
The creation stack of this resolvable which will be appended to errors thrown during resolution.

This may return an array with a single informational element indicating how to get this property populated, if it was skipped for performance reasons.

isEmptybooleanis_emptyboolisEmptyBooleanIsEmptyboolIsEmpty*boolrequired#
Whether the policy document contains any statements.
statementCountnumberstatement_countint | floatstatementCountNumberStatementCountdoubleStatementCount*float64required#
The number of statements already added to this policy.

Can be used, for example, to generate unique "sid"s within the policy.

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.
1 parameter

Parameters

  • statementstatementstatementstatementStatement — the statement to add.
fromJson(obj: any): PolicyDocument // chainable@staticmethod def from_json(obj: Any) -> PolicyDocumentpublic static PolicyDocument fromJson(Object obj)public static PolicyDocument FromJson(object obj)func FromJson(Obj interface{}) PolicyDocumentstatic#
Creates a new PolicyDocument based on the object provided.

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

1 parameter

Parameters

  • objobjobjobjObj — the PolicyDocument in object form.
resolve(context: IResolveContext): anydef resolve(self, context: IResolveContext) -> Anypublic Object resolve(IResolveContext context)public object Resolve(IResolveContext context)func Resolve(Context IResolveContext) interface{}#
Produce the Token's value at resolution time.
toJSON(): anydef to_json(self, ) -> Anypublic Object toJSON()public object ToJSON()func ToJSON() interface{}#
JSON-ify the document.

Used when JSON.stringify() is called

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Encode the policy document as a string.
validateForAnyPolicy(): string[]def validate_for_any_policy(self, ) -> typing.List[str]public List<String> validateForAnyPolicy()public string[] ValidateForAnyPolicy()func ValidateForAnyPolicy() *[]*string#
Validate that all policy statements in the policy document satisfies the requirements for any policy.
returns

Returns: An array of validation error messages, or an empty array if the document 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 all policy statements in the policy document satisfies the requirements for an identity-based policy.
returns

Returns: An array of validation error messages, or an empty array if the document 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 all policy statements in the policy document satisfies the 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 document 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 all policy statements in the policy document satisfies the 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 document is valid.