Skip to content
v2.274.0

Amazon Elastic File System Construct Library ​

Amazon Elastic File System (Amazon EFS) provides a simple, scalable, fully managed elastic NFS file system for use with AWS Cloud services and on-premises resources. Amazon EFS provides file storage in the AWS Cloud. With Amazon EFS, you can create a file system, mount the file system on an Amazon EC2 instance, and then read and write data to and from your file system.

This module is part of the AWS Cloud Development Kit project.

File Systems ​

Amazon EFS provides elastic, shared file storage that is POSIX-compliant. The file system you create supports concurrent read and write access from multiple Amazon EC2 instances and is accessible from all of the Availability Zones in the AWS Region where it is created. Learn more about EFS file systems

Create an Amazon EFS file system ​

A Virtual Private Cloud (VPC) is required to create an Amazon EFS file system. The following example creates a file system that is encrypted at rest, running in General Purpose performance mode, and Bursting throughput mode and does not transition files to the Infrequent Access (IA) storage class.

ts
const fileSystem = new efs.FileSystem(this, 'MyEfsFileSystem', {
  vpc: new ec2.Vpc(this, 'VPC'),
  lifecyclePolicy: efs.LifecyclePolicy.AFTER_14_DAYS, // files are not transitioned to infrequent access (IA) storage by default
  performanceMode: efs.PerformanceMode.GENERAL_PURPOSE, // default
  outOfInfrequentAccessPolicy: efs.OutOfInfrequentAccessPolicy.AFTER_1_ACCESS, // files are not transitioned back from (infrequent access) IA to primary storage by default
  transitionToArchivePolicy: efs.LifecyclePolicy.AFTER_14_DAYS, // files are not transitioned to Archive by default
  replicationOverwriteProtection: efs.ReplicationOverwriteProtection.ENABLED, // Set to `DISABLED` if you want to create a read-only file system for use as a replication destination
});
python
file_system = efs.FileSystem(self, "MyEfsFileSystem",
    vpc=ec2.Vpc(self, "VPC"),
    lifecycle_policy=efs.LifecyclePolicy.AFTER_14_DAYS,  # files are not transitioned to infrequent access (IA) storage by default
    performance_mode=efs.PerformanceMode.GENERAL_PURPOSE,  # default
    out_of_infrequent_access_policy=efs.OutOfInfrequentAccessPolicy.AFTER_1_ACCESS,  # files are not transitioned back from (infrequent access) IA to primary storage by default
    transition_to_archive_policy=efs.LifecyclePolicy.AFTER_14_DAYS,  # files are not transitioned to Archive by default
    replication_overwrite_protection=efs.ReplicationOverwriteProtection.ENABLED
)
java
FileSystem fileSystem = FileSystem.Builder.create(this, "MyEfsFileSystem")
        .vpc(new Vpc(this, "VPC"))
        .lifecyclePolicy(LifecyclePolicy.AFTER_14_DAYS) // files are not transitioned to infrequent access (IA) storage by default
        .performanceMode(PerformanceMode.GENERAL_PURPOSE) // default
        .outOfInfrequentAccessPolicy(OutOfInfrequentAccessPolicy.AFTER_1_ACCESS) // files are not transitioned back from (infrequent access) IA to primary storage by default
        .transitionToArchivePolicy(LifecyclePolicy.AFTER_14_DAYS) // files are not transitioned to Archive by default
        .replicationOverwriteProtection(ReplicationOverwriteProtection.ENABLED)
        .build();
csharp
var fileSystem = new FileSystem(this, "MyEfsFileSystem", new FileSystemProps {
    Vpc = new Vpc(this, "VPC"),
    LifecyclePolicy = LifecyclePolicy.AFTER_14_DAYS,  // files are not transitioned to infrequent access (IA) storage by default
    PerformanceMode = PerformanceMode.GENERAL_PURPOSE,  // default
    OutOfInfrequentAccessPolicy = OutOfInfrequentAccessPolicy.AFTER_1_ACCESS,  // files are not transitioned back from (infrequent access) IA to primary storage by default
    TransitionToArchivePolicy = LifecyclePolicy.AFTER_14_DAYS,  // files are not transitioned to Archive by default
    ReplicationOverwriteProtection = ReplicationOverwriteProtection.ENABLED
});
go
fileSystem := efs.NewFileSystem(this, jsii.String("MyEfsFileSystem"), &FileSystemProps{
	Vpc: ec2.NewVpc(this, jsii.String("VPC")),
	LifecyclePolicy: efs.LifecyclePolicy_AFTER_14_DAYS,
	 // files are not transitioned to infrequent access (IA) storage by default
	PerformanceMode: efs.PerformanceMode_GENERAL_PURPOSE,
	 // default
	OutOfInfrequentAccessPolicy: efs.OutOfInfrequentAccessPolicy_AFTER_1_ACCESS,
	 // files are not transitioned back from (infrequent access) IA to primary storage by default
	TransitionToArchivePolicy: efs.LifecyclePolicy_AFTER_14_DAYS,
	 // files are not transitioned to Archive by default
	ReplicationOverwriteProtection: efs.ReplicationOverwriteProtection_ENABLED,
})

⚠️ An Amazon EFS file system's performance mode can't be MAX_IO when its throughputMode is ELASTIC.

⚠️ An Amazon EFS file system's performance mode can't be changed after the file system has been created. Updating this property will replace the file system.

Any file system that has been created outside the stack can be imported into your CDK app.

Use the fromFileSystemAttributes() API to import an existing file system. Here is an example of giving a role write permissions on a file system.

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

const importedFileSystem = efs.FileSystem.fromFileSystemAttributes(this, 'existingFS', {
  fileSystemId: 'fs-12345678', // You can also use fileSystemArn instead of fileSystemId.
  securityGroup: ec2.SecurityGroup.fromSecurityGroupId(this, 'SG', 'sg-123456789', {
    allowAllOutbound: false,
  }),
});
python
import aws_cdk.aws_iam as iam


imported_file_system = efs.FileSystem.from_file_system_attributes(self, "existingFS",
    file_system_id="fs-12345678",  # You can also use fileSystemArn instead of fileSystemId.
    security_group=ec2.SecurityGroup.from_security_group_id(self, "SG", "sg-123456789",
        allow_all_outbound=False
    )
)
java
import software.amazon.awscdk.services.iam.*;


IFileSystem importedFileSystem = FileSystem.fromFileSystemAttributes(this, "existingFS", FileSystemAttributes.builder()
        .fileSystemId("fs-12345678") // You can also use fileSystemArn instead of fileSystemId.
        .securityGroup(SecurityGroup.fromSecurityGroupId(this, "SG", "sg-123456789", SecurityGroupImportOptions.builder()
                .allowAllOutbound(false)
                .build()))
        .build());
csharp
using Amazon.CDK.AWS.IAM;


var importedFileSystem = FileSystem.FromFileSystemAttributes(this, "existingFS", new FileSystemAttributes {
    FileSystemId = "fs-12345678",  // You can also use fileSystemArn instead of fileSystemId.
    SecurityGroup = SecurityGroup.FromSecurityGroupId(this, "SG", "sg-123456789", new SecurityGroupImportOptions {
        AllowAllOutbound = false
    })
});
go
import iam "github.com/aws/aws-cdk-go/awscdk"


importedFileSystem := efs.FileSystem_FromFileSystemAttributes(this, jsii.String("existingFS"), &FileSystemAttributes{
	FileSystemId: jsii.String("fs-12345678"),
	 // You can also use fileSystemArn instead of fileSystemId.
	SecurityGroup: ec2.SecurityGroup_FromSecurityGroupId(this, jsii.String("SG"), jsii.String("sg-123456789"), &SecurityGroupImportOptions{
		AllowAllOutbound: jsii.Boolean(false),
	}),
})

One Zone file system ​

To initialize a One Zone file system use the oneZone property:

ts
declare const vpc: ec2.Vpc;

new efs.FileSystem(this, 'OneZoneFileSystem', {
  vpc,
  oneZone: true,
})
python
# vpc: ec2.Vpc


efs.FileSystem(self, "OneZoneFileSystem",
    vpc=vpc,
    one_zone=True
)
java
Vpc vpc;


FileSystem.Builder.create(this, "OneZoneFileSystem")
        .vpc(vpc)
        .oneZone(true)
        .build();
csharp
Vpc vpc;


new FileSystem(this, "OneZoneFileSystem", new FileSystemProps {
    Vpc = vpc,
    OneZone = true
});
go
var vpc Vpc


efs.NewFileSystem(this, jsii.String("OneZoneFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	OneZone: jsii.Boolean(true),
})

⚠️ One Zone file systems are not compatible with the MAX_IO performance mode.

⚠️ When oneZone is enabled, the file system is automatically placed in the first availability zone of the VPC. To specify a different availability zone:

ts
declare const vpc: ec2.Vpc;

new efs.FileSystem(this, 'OneZoneFileSystem', {
  vpc,
  oneZone: true,
  vpcSubnets: {
    availabilityZones: ['us-east-1b'],
  },
})
python
# vpc: ec2.Vpc


efs.FileSystem(self, "OneZoneFileSystem",
    vpc=vpc,
    one_zone=True,
    vpc_subnets=ec2.SubnetSelection(
        availability_zones=["us-east-1b"]
    )
)
java
Vpc vpc;


FileSystem.Builder.create(this, "OneZoneFileSystem")
        .vpc(vpc)
        .oneZone(true)
        .vpcSubnets(SubnetSelection.builder()
                .availabilityZones(List.of("us-east-1b"))
                .build())
        .build();
csharp
Vpc vpc;


new FileSystem(this, "OneZoneFileSystem", new FileSystemProps {
    Vpc = vpc,
    OneZone = true,
    VpcSubnets = new SubnetSelection {
        AvailabilityZones = new [] { "us-east-1b" }
    }
});
go
var vpc Vpc


efs.NewFileSystem(this, jsii.String("OneZoneFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	OneZone: jsii.Boolean(true),
	VpcSubnets: &SubnetSelection{
		AvailabilityZones: []*string{
			jsii.String("us-east-1b"),
		},
	},
})

⚠️ When oneZone is enabled, mount targets will be created only in the specified availability zone. This is to prevent deployment failures due to cross-AZ configurations.

⚠️ When oneZone is enabled, vpcSubnets can be specified with availabilityZones that contains exactly one single zone.

Replicating file systems ​

You can create a replica of your EFS file system in the AWS Region of your preference.

ts
declare const vpc: ec2.Vpc;

// auto generate a regional replication destination file system
new efs.FileSystem(this, 'RegionalReplicationFileSystem', {
  vpc,
  replicationConfiguration: efs.ReplicationConfiguration.regionalFileSystem('us-west-2'),
});

// auto generate a one zone replication destination file system
new efs.FileSystem(this, 'OneZoneReplicationFileSystem', {
  vpc,
  replicationConfiguration: efs.ReplicationConfiguration.oneZoneFileSystem('us-east-1', 'us-east-1a'),
});

const destinationFileSystem = new efs.FileSystem(this, 'DestinationFileSystem', {
  vpc,
  // set as the read-only file system for use as a replication destination
  replicationOverwriteProtection: efs.ReplicationOverwriteProtection.DISABLED,
});
// specify the replication destination file system
new efs.FileSystem(this, 'ReplicationFileSystem', {
  vpc,
  replicationConfiguration: efs.ReplicationConfiguration.existingFileSystem(destinationFileSystem),
});
python
# vpc: ec2.Vpc


# auto generate a regional replication destination file system
efs.FileSystem(self, "RegionalReplicationFileSystem",
    vpc=vpc,
    replication_configuration=efs.ReplicationConfiguration.regional_file_system("us-west-2")
)

# auto generate a one zone replication destination file system
efs.FileSystem(self, "OneZoneReplicationFileSystem",
    vpc=vpc,
    replication_configuration=efs.ReplicationConfiguration.one_zone_file_system("us-east-1", "us-east-1a")
)

destination_file_system = efs.FileSystem(self, "DestinationFileSystem",
    vpc=vpc,
    # set as the read-only file system for use as a replication destination
    replication_overwrite_protection=efs.ReplicationOverwriteProtection.DISABLED
)
# specify the replication destination file system
efs.FileSystem(self, "ReplicationFileSystem",
    vpc=vpc,
    replication_configuration=efs.ReplicationConfiguration.existing_file_system(destination_file_system)
)
java
Vpc vpc;


// auto generate a regional replication destination file system
// auto generate a regional replication destination file system
FileSystem.Builder.create(this, "RegionalReplicationFileSystem")
        .vpc(vpc)
        .replicationConfiguration(ReplicationConfiguration.regionalFileSystem("us-west-2"))
        .build();

// auto generate a one zone replication destination file system
// auto generate a one zone replication destination file system
FileSystem.Builder.create(this, "OneZoneReplicationFileSystem")
        .vpc(vpc)
        .replicationConfiguration(ReplicationConfiguration.oneZoneFileSystem("us-east-1", "us-east-1a"))
        .build();

FileSystem destinationFileSystem = FileSystem.Builder.create(this, "DestinationFileSystem")
        .vpc(vpc)
        // set as the read-only file system for use as a replication destination
        .replicationOverwriteProtection(ReplicationOverwriteProtection.DISABLED)
        .build();
// specify the replication destination file system
// specify the replication destination file system
FileSystem.Builder.create(this, "ReplicationFileSystem")
        .vpc(vpc)
        .replicationConfiguration(ReplicationConfiguration.existingFileSystem(destinationFileSystem))
        .build();
csharp
Vpc vpc;


// auto generate a regional replication destination file system
// auto generate a regional replication destination file system
new FileSystem(this, "RegionalReplicationFileSystem", new FileSystemProps {
    Vpc = vpc,
    ReplicationConfiguration = ReplicationConfiguration.RegionalFileSystem("us-west-2")
});

// auto generate a one zone replication destination file system
// auto generate a one zone replication destination file system
new FileSystem(this, "OneZoneReplicationFileSystem", new FileSystemProps {
    Vpc = vpc,
    ReplicationConfiguration = ReplicationConfiguration.OneZoneFileSystem("us-east-1", "us-east-1a")
});

var destinationFileSystem = new FileSystem(this, "DestinationFileSystem", new FileSystemProps {
    Vpc = vpc,
    // set as the read-only file system for use as a replication destination
    ReplicationOverwriteProtection = ReplicationOverwriteProtection.DISABLED
});
// specify the replication destination file system
// specify the replication destination file system
new FileSystem(this, "ReplicationFileSystem", new FileSystemProps {
    Vpc = vpc,
    ReplicationConfiguration = ReplicationConfiguration.ExistingFileSystem(destinationFileSystem)
});
go
var vpc Vpc


// auto generate a regional replication destination file system
// auto generate a regional replication destination file system
efs.NewFileSystem(this, jsii.String("RegionalReplicationFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	ReplicationConfiguration: efs.ReplicationConfiguration_RegionalFileSystem(jsii.String("us-west-2")),
})

// auto generate a one zone replication destination file system
// auto generate a one zone replication destination file system
efs.NewFileSystem(this, jsii.String("OneZoneReplicationFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	ReplicationConfiguration: efs.ReplicationConfiguration_OneZoneFileSystem(jsii.String("us-east-1"), jsii.String("us-east-1a")),
})

destinationFileSystem := efs.NewFileSystem(this, jsii.String("DestinationFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	// set as the read-only file system for use as a replication destination
	ReplicationOverwriteProtection: efs.ReplicationOverwriteProtection_DISABLED,
})
// specify the replication destination file system
// specify the replication destination file system
efs.NewFileSystem(this, jsii.String("ReplicationFileSystem"), &FileSystemProps{
	Vpc: Vpc,
	ReplicationConfiguration: efs.ReplicationConfiguration_ExistingFileSystem(destinationFileSystem),
})

Note: EFS now supports only one replication destination and thus allows specifying just one replicationConfiguration for each file system.

Visit Replicating file systems for more details.

IAM to control file system data access ​

You can use both IAM identity policies and resource policies to control client access to Amazon EFS resources in a way that is scalable and optimized for cloud environments. Using IAM, you can permit clients to perform specific actions on a file system, including read-only, write, and root access.

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
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
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,
})

Alternatively, a resource policy can be added later using addToResourcePolicy(statement). Note that this will not work with imported FileSystem.

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

declare const statement: iam.PolicyStatement;
const fileSystem = new efs.FileSystem(this, 'MyEfsFileSystem', {
  vpc: new ec2.Vpc(this, 'VPC'),
});

fileSystem.addToResourcePolicy(statement);
python
import aws_cdk.aws_iam as iam

# statement: iam.PolicyStatement

file_system = efs.FileSystem(self, "MyEfsFileSystem",
    vpc=ec2.Vpc(self, "VPC")
)

file_system.add_to_resource_policy(statement)
java
import software.amazon.awscdk.services.iam.*;

PolicyStatement statement;

FileSystem fileSystem = FileSystem.Builder.create(this, "MyEfsFileSystem")
        .vpc(new Vpc(this, "VPC"))
        .build();

fileSystem.addToResourcePolicy(statement);
csharp
using Amazon.CDK.AWS.IAM;

PolicyStatement statement;

var fileSystem = new FileSystem(this, "MyEfsFileSystem", new FileSystemProps {
    Vpc = new Vpc(this, "VPC")
});

fileSystem.AddToResourcePolicy(statement);
go
import iam "github.com/aws/aws-cdk-go/awscdk"

var statement PolicyStatement

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

fileSystem.addToResourcePolicy(statement)

Permissions ​

If you need to grant file system permissions to another resource, you can use the .grant() API. As an example, the following code gives elasticfilesystem:Backup permissions to an IAM role.

ts
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.AnyPrincipal(),
});

fileSystem.grant(role, 'elasticfilesystem:Backup');
python
role = iam.Role(self, "Role",
    assumed_by=iam.AnyPrincipal()
)

file_system.grant(role, "elasticfilesystem:Backup")
java
Role role = Role.Builder.create(this, "Role")
        .assumedBy(new AnyPrincipal())
        .build();

fileSystem.grant(role, "elasticfilesystem:Backup");
csharp
var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new AnyPrincipal()
});

fileSystem.Grant(role, "elasticfilesystem:Backup");
go
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewAnyPrincipal(),
})

fileSystem.grant(role, jsii.String("elasticfilesystem:Backup"))

APIs for clients also include .grantRead(), .grantReadWrite(), and .grantRootAccess(). Using these APIs grants access to clients. Also, by default, the file system policy is updated to only allow access to clients using IAM authentication and deny access to anonymous clients.

ts
const role = new iam.Role(this, 'ClientRole', {
  assumedBy: new iam.AnyPrincipal(),
});

fileSystem.grantRead(role);
python
role = iam.Role(self, "ClientRole",
    assumed_by=iam.AnyPrincipal()
)

file_system.grant_read(role)
java
Role role = Role.Builder.create(this, "ClientRole")
        .assumedBy(new AnyPrincipal())
        .build();

fileSystem.grantRead(role);
csharp
var role = new Role(this, "ClientRole", new RoleProps {
    AssumedBy = new AnyPrincipal()
});

fileSystem.GrantRead(role);
go
role := iam.NewRole(this, jsii.String("ClientRole"), &RoleProps{
	AssumedBy: iam.NewAnyPrincipal(),
})

fileSystem.grantRead(role)

You can control this behavior with allowAnonymousAccess. The following example continues to allow anonymous client access.

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

const role = new iam.Role(this, 'ClientRole', {
  assumedBy: new iam.AnyPrincipal(),
});
const fileSystem = new efs.FileSystem(this, 'MyEfsFileSystem', {
  vpc: new ec2.Vpc(this, 'VPC'),
  allowAnonymousAccess: true,
});

fileSystem.grantRead(role);
python
import aws_cdk.aws_iam as iam


role = iam.Role(self, "ClientRole",
    assumed_by=iam.AnyPrincipal()
)
file_system = efs.FileSystem(self, "MyEfsFileSystem",
    vpc=ec2.Vpc(self, "VPC"),
    allow_anonymous_access=True
)

file_system.grant_read(role)
java
import software.amazon.awscdk.services.iam.*;


Role role = Role.Builder.create(this, "ClientRole")
        .assumedBy(new AnyPrincipal())
        .build();
FileSystem fileSystem = FileSystem.Builder.create(this, "MyEfsFileSystem")
        .vpc(new Vpc(this, "VPC"))
        .allowAnonymousAccess(true)
        .build();

fileSystem.grantRead(role);
csharp
using Amazon.CDK.AWS.IAM;


var role = new Role(this, "ClientRole", new RoleProps {
    AssumedBy = new AnyPrincipal()
});
var fileSystem = new FileSystem(this, "MyEfsFileSystem", new FileSystemProps {
    Vpc = new Vpc(this, "VPC"),
    AllowAnonymousAccess = true
});

fileSystem.GrantRead(role);
go
import "github.com/aws/aws-cdk-go/awscdk"


role := iam.NewRole(this, jsii.String("ClientRole"), &RoleProps{
	AssumedBy: iam.NewAnyPrincipal(),
})
fileSystem := efs.NewFileSystem(this, jsii.String("MyEfsFileSystem"), &FileSystemProps{
	Vpc: ec2.NewVpc(this, jsii.String("VPC")),
	AllowAnonymousAccess: jsii.Boolean(true),
})

fileSystem.grantRead(role)

Access Point ​

An access point is an application-specific view into an EFS file system that applies an operating system user and group, and a file system path, to any file system request made through the access point. The operating system user and group override any identity information provided by the NFS client. The file system path is exposed as the access point's root directory. Applications using the access point can only access data in its own directory and below. To learn more, see Mounting a File System Using EFS Access Points.

Use the addAccessPoint API to create an access point from a fileSystem.

ts
fileSystem.addAccessPoint('MyAccessPoint', {
  // create a unique access point via an optional client token
  clientToken: 'client-token',
});
python
file_system.add_access_point("MyAccessPoint",
    # create a unique access point via an optional client token
    client_token="client-token"
)
java
fileSystem.addAccessPoint("MyAccessPoint", AccessPointOptions.builder()
        // create a unique access point via an optional client token
        .clientToken("client-token")
        .build());
csharp
fileSystem.AddAccessPoint("MyAccessPoint", new AccessPointOptions {
    // create a unique access point via an optional client token
    ClientToken = "client-token"
});
go
fileSystem.AddAccessPoint(jsii.String("MyAccessPoint"), &AccessPointOptions{
	// create a unique access point via an optional client token
	ClientToken: jsii.String("client-token"),
})

By default, when you create an access point, the root(/) directory is exposed to the client connecting to the access point. You can specify a custom path with the path property.

If path does not exist, it will be created with the settings defined in the creationInfo. See Creating Access Points for more details.

Any access point that has been created outside the stack can be imported into your CDK app.

Use the fromAccessPointAttributes() API to import an existing access point.

ts
efs.AccessPoint.fromAccessPointAttributes(this, 'ap', {
  accessPointId: 'fsap-1293c4d9832fo0912',
  fileSystem: efs.FileSystem.fromFileSystemAttributes(this, 'efs', {
    fileSystemId: 'fs-099d3e2f',
    securityGroup: ec2.SecurityGroup.fromSecurityGroupId(this, 'sg', 'sg-51530134'),
  }),
});
python
efs.AccessPoint.from_access_point_attributes(self, "ap",
    access_point_id="fsap-1293c4d9832fo0912",
    file_system=efs.FileSystem.from_file_system_attributes(self, "efs",
        file_system_id="fs-099d3e2f",
        security_group=ec2.SecurityGroup.from_security_group_id(self, "sg", "sg-51530134")
    )
)
java
AccessPoint.fromAccessPointAttributes(this, "ap", AccessPointAttributes.builder()
        .accessPointId("fsap-1293c4d9832fo0912")
        .fileSystem(FileSystem.fromFileSystemAttributes(this, "efs", FileSystemAttributes.builder()
                .fileSystemId("fs-099d3e2f")
                .securityGroup(SecurityGroup.fromSecurityGroupId(this, "sg", "sg-51530134"))
                .build()))
        .build());
csharp
AccessPoint.FromAccessPointAttributes(this, "ap", new AccessPointAttributes {
    AccessPointId = "fsap-1293c4d9832fo0912",
    FileSystem = FileSystem.FromFileSystemAttributes(this, "efs", new FileSystemAttributes {
        FileSystemId = "fs-099d3e2f",
        SecurityGroup = SecurityGroup.FromSecurityGroupId(this, "sg", "sg-51530134")
    })
});
go
efs.AccessPoint_FromAccessPointAttributes(this, jsii.String("ap"), &AccessPointAttributes{
	AccessPointId: jsii.String("fsap-1293c4d9832fo0912"),
	FileSystem: efs.FileSystem_FromFileSystemAttributes(this, jsii.String("efs"), &FileSystemAttributes{
		FileSystemId: jsii.String("fs-099d3e2f"),
		SecurityGroup: ec2.SecurityGroup_FromSecurityGroupId(this, jsii.String("sg"), jsii.String("sg-51530134")),
	}),
})

⚠️ Notice: When importing an Access Point using fromAccessPointAttributes(), you must make sure the mount targets are deployed and their lifecycle state is available. Otherwise, you may encounter the following error when deploying:

EFS file system <ARN of efs> referenced by access point <ARN of access point of EFS> has mount targets created in all availability zones the function will execute in, but not all are in the available life cycle state yet. Please wait for them to become available and try the request again.

Connecting ​

To control who can access the EFS, use the .connections attribute. EFS has a fixed default port, so you don't need to specify the port:

ts
fileSystem.connections.allowDefaultPortFrom(instance);
python
file_system.connections.allow_default_port_from(instance)
java
fileSystem.connections.allowDefaultPortFrom(instance);
csharp
fileSystem.Connections.AllowDefaultPortFrom(instance);
go
fileSystem.Connections.AllowDefaultPortFrom(instance)

Learn more about managing file system network accessibility

Mounting the file system using User Data ​

After you create a file system, you can create mount targets. Then you can mount the file system on EC2 instances, containers, and Lambda functions in your virtual private cloud (VPC).

The following example automatically mounts a file system during instance launch.

ts
fileSystem.connections.allowDefaultPortFrom(instance);

instance.userData.addCommands("yum check-update -y",    // Ubuntu: apt-get -y update
  "yum upgrade -y",                                 // Ubuntu: apt-get -y upgrade
  "yum install -y amazon-efs-utils",                // Ubuntu: apt-get -y install amazon-efs-utils
  "yum install -y nfs-utils",                       // Ubuntu: apt-get -y install nfs-common
  "file_system_id_1=" + fileSystem.fileSystemId,
  "efs_mount_point_1=/mnt/efs/fs1",
  "mkdir -p \"${efs_mount_point_1}\"",
  "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " +
  "echo \"${file_system_id_1}.efs." + Stack.of(this).region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab",
  "mount -a -t efs,nfs4 defaults");
python
file_system.connections.allow_default_port_from(instance)

instance.user_data.add_commands("yum check-update -y", "yum upgrade -y", "yum install -y amazon-efs-utils", "yum install -y nfs-utils", "file_system_id_1=" + file_system.file_system_id, "efs_mount_point_1=/mnt/efs/fs1", "mkdir -p \"${efs_mount_point_1}\"", "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " + "echo \"${file_system_id_1}.efs." + Stack.of(self).region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab", "mount -a -t efs,nfs4 defaults")
java
fileSystem.connections.allowDefaultPortFrom(instance);

instance.userData.addCommands("yum check-update -y", "yum upgrade -y", "yum install -y amazon-efs-utils", "yum install -y nfs-utils", "file_system_id_1=" + fileSystem.getFileSystemId(), "efs_mount_point_1=/mnt/efs/fs1", "mkdir -p \"${efs_mount_point_1}\"", "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " + "echo \"${file_system_id_1}.efs." + Stack.of(this).getRegion() + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab", "mount -a -t efs,nfs4 defaults");
csharp
fileSystem.Connections.AllowDefaultPortFrom(instance);

instance.UserData.AddCommands("yum check-update -y", "yum upgrade -y", "yum install -y amazon-efs-utils", "yum install -y nfs-utils", "file_system_id_1=" + fileSystem.FileSystemId, "efs_mount_point_1=/mnt/efs/fs1", "mkdir -p \"${efs_mount_point_1}\"", "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " + "echo \"${file_system_id_1}.efs." + Stack.Of(this).Region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab", "mount -a -t efs,nfs4 defaults");
go
fileSystem.Connections.AllowDefaultPortFrom(instance)

instance.UserData.AddCommands(jsii.String("yum check-update -y"), jsii.String("yum upgrade -y"), jsii.String("yum install -y amazon-efs-utils"), jsii.String("yum install -y nfs-utils"), jsii.String("file_system_id_1=" + fileSystem.FileSystemId), jsii.String("efs_mount_point_1=/mnt/efs/fs1"), jsii.String("mkdir -p \"${efs_mount_point_1}\""), jsii.String("test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " + "echo \"${file_system_id_1}.efs." + awscdk.stack_Of(this).Region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab"), jsii.String("mount -a -t efs,nfs4 defaults"))

Learn more about mounting EFS file systems

Deleting ​

Since file systems are stateful resources, by default the file system will not be deleted when your stack is deleted.

You can configure the file system to be destroyed on stack deletion by setting a removalPolicy

ts
const fileSystem =  new efs.FileSystem(this, 'EfsFileSystem', {
  vpc: new ec2.Vpc(this, 'VPC'),
  removalPolicy: RemovalPolicy.DESTROY,
});
python
file_system = efs.FileSystem(self, "EfsFileSystem",
    vpc=ec2.Vpc(self, "VPC"),
    removal_policy=RemovalPolicy.DESTROY
)
java
FileSystem fileSystem = FileSystem.Builder.create(this, "EfsFileSystem")
        .vpc(new Vpc(this, "VPC"))
        .removalPolicy(RemovalPolicy.DESTROY)
        .build();
csharp
var fileSystem = new FileSystem(this, "EfsFileSystem", new FileSystemProps {
    Vpc = new Vpc(this, "VPC"),
    RemovalPolicy = RemovalPolicy.DESTROY
});
go
fileSystem := efs.NewFileSystem(this, jsii.String("EfsFileSystem"), &FileSystemProps{
	Vpc: ec2.NewVpc(this, jsii.String("VPC")),
	RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
})

Types ​

NameKindSummary
AccessPointConstruct (L2)Represents the AccessPoint.
FileSystemConstruct (L2)The Elastic File System implementation of IFileSystem.
CfnAccessPointConstruct (L1)The AWS::EFS::AccessPoint resource creates an EFS access point.
CfnFileSystemConstruct (L1)The AWS::EFS::FileSystem resource creates a new, empty file system in Amazon Elastic File System ( Amazon EFS ).
CfnMountTargetConstruct (L1)The AWS::EFS::MountTarget resource is an Amazon EFS resource that creates a mount target for an EFS file system.
AccessPointAttributesStructAttributes that can be specified when importing an AccessPoint.
AccessPointOptionsStructOptions to create an AccessPoint.
AccessPointPropsStructProperties for the AccessPoint.
AclStructPermissions as POSIX ACL.
CfnAccessPoint.AccessPointTagPropertyStructA tag is a key-value pair attached to a file system.
CfnAccessPoint.CreationInfoPropertyStructRequired if the RootDirectory > Path specified does not exist.
CfnAccessPoint.PosixUserPropertyStructThe full POSIX identity, including the user ID, group ID, and any secondary group IDs, on the access point that is used for all file system operations performed by NFS clients using the access point.
CfnAccessPoint.RootDirectoryPropertyStructSpecifies the directory on the Amazon EFS file system that the access point provides access to.
CfnAccessPointPropsStructProperties for defining a CfnAccessPoint.
CfnFileSystem.BackupPolicyPropertyStructThe backup policy turns automatic backups for the file system on or off.
CfnFileSystem.ElasticFileSystemTagPropertyStructA tag is a key-value pair attached to a file system.
CfnFileSystem.FileSystemProtectionPropertyStructDescribes the protection on the file system.
CfnFileSystem.LifecyclePolicyPropertyStructDescribes a policy used by Lifecycle management that specifies when to transition files into and out of the EFS storage classes.
CfnFileSystem.ReplicationConfigurationPropertyStructDescribes the replication configuration for a specific file system.
CfnFileSystem.ReplicationDestinationPropertyStructDescribes the destination file system in the replication configuration.
CfnFileSystemPropsStructProperties for defining a CfnFileSystem.
CfnMountTargetPropsStructProperties for defining a CfnMountTarget.
ExistingFileSystemPropsStructProperties for configuring ReplicationConfiguration to replicate to an existing file system.
FileSystemAttributesStructProperties that describe an existing EFS file system.
FileSystemPropsStructProperties of EFS FileSystem.
IAccessPointInterfaceRepresents an EFS AccessPoint.
IFileSystemInterfaceRepresents an Amazon EFS file system.
LifecyclePolicyEnumEFS Lifecycle Policy, if a file is not accessed for given days, it will move to EFS Infrequent Access or Archive storage.
OneZoneFileSystemPropsStructProperties for configuring ReplicationConfiguration to replicate to a new One Zone file system.
OutOfInfrequentAccessPolicyEnumEFS Out Of Infrequent Access Policy, if a file is accessed given times, it will move back to primary storage class.
PerformanceModeEnumEFS Performance mode.
PosixUserStructRepresents the PosixUser.
RegionalFileSystemPropsStructProperties for configuring ReplicationConfiguration to replicate to a new Regional file system.
ReplicationConfigurationClassEFS Replication Configuration.
ReplicationConfigurationPropsStructProperties for the ReplicationConfiguration.
ReplicationOverwriteProtectionEnumThe status of the file system's replication overwrite protection.
ThroughputModeEnumEFS Throughput mode.