如何使用 AWS CDK 将 EFS 附加和挂载到我的 EC2 实例

How to attach and mount an EFS to my EC2 instance using AWS CDK

我想使用 AWS CDK 自动将 EFS 安装到我的 EC2 instance

我创建了文件系统:

        self.file_system = efs.FileSystem(
            scope=self,
            id="Efs",
            vpc=self.vpc,
            file_system_name="EFS",
            removal_policy=RemovalPolicy.DESTROY,
        )

和 Ec2 实例:

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

现在我需要做什么才能连接它们?我在控制台上看到很多这样做的例子,但到目前为止我还没有找到在 AWS CDK 中这样做的方法。

您可以在创建 EFS 和 EC2 之后在您创建的 EFS 上调用连接:

file_system.connections.allow_default_port_from(instance)

你的情况:

self.file_system.connections.allow_default_port_from(self.ec2_instance)

这是文档: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_efs/README.html#connecting

如果启动时需要挂载,可以通过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")

此处的文档片段: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_efs/README.html#mounting-the-file-system-using-user-data