I’m trying to connect an EFS volume to an EC2 instance using the AWS CDK in Python.
Create my instance
instance = ec2.CfnInstance(stack, cdk.Stack.of(stack).stack_name,
key_name="key-name",
subnet_id="subnet-123",
security_group_ids=["sg-123"],
iam_instance_profile="profile-name",
instance_type="t3.medium",
image_id="ami-08d4ac5b634553e16",
block_device_mappings=[ec2.CfnInstance.BlockDeviceMappingProperty(
device_name="/dev/sda1",
ebs=ec2.CfnInstance.EbsProperty(
delete_on_termination=True,
volume_size=12,
volume_type="gp3"
)
)],
user_data=cdk.Fn.base64(init_script.render()),
tags=
[cdk.CfnTag(
key="Name",
value=cdk.Stack.of(stack).stack_name
)])
Create my EFS file system
fs = efs.FileSystem(self, "fs:{}".format(cdk.Stack.of(self).stack_name),
vpc=ec2.Vpc.from_lookup(self, "vpc-123"),
encrypted=True,
file_system_name="fs:{}".format(cdk.Stack.of(self).stack_name),
performance_mode=efs.PerformanceMode.GENERAL_PURPOSE,
security_group=ec2.SecurityGroup.from_security_group_id(self, "sg", "sg-123")
)
Connect fs to the instance
fs.connections.allow_default_port_from(instance)
Get the following error on the fs.connections.allow_default_port_from(instance) line
jsii.errors.JSIIError: Cannot read properties of undefined (reading '_securityGroupRules')
The documentation/guide that I’ve been following is here. In attempting to figure this out, I can confirm that my security group is part of the connections object. In the AWS console I can confirm that there are in fact security group rules attached to this security group. I know I’m missing something, I’m just confused at this point and not sure how to proceed.
>Solution :
allow_default_port_from takes an argument of type IConnectable, like an ec2.Instance. It only works with higher-level L2 constructs. You’re trying to pass a ec2.CfnInstance construct, which is not compatible.
Your options:
-
Use the L2
ec2.Instanceconstruct, it is much more feature-rich and support CDK abstractions such as this one -
Create a
ec2.Connectionsobjects yourself, passing it the security group of yourCfnInstance.