I'd like to automatically mount an EFS
to my EC2 instance
using AWS CDK.
I created the file system:
self.file_system = efs.FileSystem(
scope=self,
id="Efs",
vpc=self.vpc,
file_system_name="EFS",
removal_policy=RemovalPolicy.DESTROY,
)
and the Ec2 instance:
self.ec2_instance = ec2.Instance(
scope=self,
id="ec2Instance",
instance_name="my_ec2_instance",
instance_type=ec2.InstanceType.of(
instance_class=ec2.InstanceClass.BURSTABLE2,
instance_size=ec2.InstanceSize.MICRO,
),
machine_image=ec2.AmazonLinuxImage(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
),
vpc=self.vpc,
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
key_name="ec2-key-pair",
security_group=ec2_security_group,
)
Now what do I need to do to get them attached? I see many examples of doing this on the console, but so far I haven't found a way to do it in AWS CDK.
CodePudding user response:
You can just call connect on your created EFS after you created both EFS and EC2:
file_system.connections.allow_default_port_from(instance)
In your case:
self.file_system.connections.allow_default_port_from(self.ec2_instance)
Here is the documentation: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_efs/README.html#connecting
If you need to mount it during launch, you can execute code via the user data of ec2:
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")
Documentaion pieces here: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_efs/README.html#mounting-the-file-system-using-user-data