Skip to content
v2.273.0

Subnet L2 construct ​

Represents a new VPC subnet resource.

Example ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  taskSubnets: {
    subnets: [ec2.Subnet.fromSubnetId(this, 'subnet', 'VpcISOLATEDSubnet1Subnet80F07FA0')],
  },
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    task_subnets=ec2.SubnetSelection(
        subnets=[ec2.Subnet.from_subnet_id(self, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")]
    )
)
java
Cluster cluster;

ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .memoryLimitMiB(1024)
        .desiredCount(1)
        .cpu(512)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .taskSubnets(SubnetSelection.builder()
                .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                .build())
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    TaskSubnets = new SubnetSelection {
        Subnets = new [] { Subnet.FromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0") }
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	TaskSubnets: &SubnetSelection{
		Subnets: []ISubnet{
			ec2.Subnet_FromSubnetId(this, jsii.String("subnet"), jsii.String("VpcISOLATEDSubnet1Subnet80F07FA0")),
		},
	},
})

Initializer ​

ts
new Subnet(scope: Construct, id: string, props: SubnetProps)
python
Subnet(scope: Construct, id: str, props: SubnetProps)
java
new Subnet(Construct scope, String id, SubnetProps props)
csharp
new Subnet(Construct scope, string id, SubnetProps props)
go
NewSubnet(Scope Construct, Id *string, Props SubnetProps)

Construct Props ​

assignIpv6AddressOnCreationbooleanassign_ipv6_address_on_creationboolassignIpv6AddressOnCreationBooleanAssignIpv6AddressOnCreationboolAssignIpv6AddressOnCreation*bool= false#
Indicates whether a network interface created in this subnet receives an IPv6 address.

If you specify AssignIpv6AddressOnCreation, you must also specify Ipv6CidrBlock.

availabilityZonestringavailability_zonestravailabilityZoneStringAvailabilityZonestringAvailabilityZone*stringrequired#
The availability zone for the subnet.
cidrBlockstringcidr_blockstrcidrBlockStringCidrBlockstringCidrBlock*stringrequired#
The CIDR notation for this subnet.
ipv6CidrBlockstringipv6_cidr_blockstripv6CidrBlockStringIpv6CidrBlockstringIpv6CidrBlock*string= no IPv6 CIDR block.#
The IPv6 CIDR block.

If you specify AssignIpv6AddressOnCreation, you must also specify Ipv6CidrBlock.

mapPublicIpOnLaunchbooleanmap_public_ip_on_launchboolmapPublicIpOnLaunchBooleanMapPublicIpOnLaunchboolMapPublicIpOnLaunch*bool= true in Subnet.Public, false in …#
Controls if a public IP is associated to an instance at launch.
default

Default: true in Subnet.Public, false in Subnet.Private or Subnet.Isolated.

vpcIdstringvpc_idstrvpcIdStringVpcIdstringVpcId*stringrequired#
The VPC which this subnet is part of.

Properties ​

availabilityZonestringavailability_zonestravailabilityZoneStringAvailabilityZonestringAvailabilityZone*stringrequired#
The Availability Zone the subnet is located in.
dependencyElementsIDependable[]dependency_elementstyping.List[IDependable]dependencyElementsList<IDependable>DependencyElementsIDependable[]DependencyElements*[]IDependablerequired#
Parts of this VPC subnet.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

internetConnectivityEstablishedIDependableinternet_connectivity_establishedIDependableinternetConnectivityEstablishedIDependableInternetConnectivityEstablishedIDependableInternetConnectivityEstablishedIDependablerequired#
Dependable that can be depended upon to force internet connectivity established on the VPC.
ipv4CidrBlockstringipv4_cidr_blockstripv4CidrBlockStringIpv4CidrBlockstringIpv4CidrBlock*stringrequired#
The IPv4 CIDR block for this subnet.
networkAclINetworkAclnetwork_aclINetworkAclnetworkAclINetworkAclNetworkAclINetworkAclNetworkAclINetworkAclrequired#
Network ACL associated with this Subnet.
notes

Upon creation, this is the default ACL which allows all traffic, except explicit DENY entries that you add.

You can replace it with a custom ACL which denies all traffic except the explicit ALLOW entries that you add by creating a NetworkAcl object and calling associateNetworkAcl().

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
routeTableIRouteTableroute_tableIRouteTablerouteTableIRouteTableRouteTableIRouteTableRouteTableIRouteTablerequired#
The routeTableId attached to this subnet.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
subnetAvailabilityZonestringsubnet_availability_zonestrsubnetAvailabilityZoneStringSubnetAvailabilityZonestringSubnetAvailabilityZone*stringrequired#
subnetIdstringsubnet_idstrsubnetIdStringSubnetIdstringSubnetId*stringrequired#
The subnetId for this particular subnet.
subnetIpv6CidrBlocksstring[]subnet_ipv6_cidr_blockstyping.List[str]subnetIpv6CidrBlocksList<String>SubnetIpv6CidrBlocksstring[]SubnetIpv6CidrBlocks*[]*stringrequired#
subnetNetworkAclAssociationIdstringsubnet_network_acl_association_idstrsubnetNetworkAclAssociationIdStringSubnetNetworkAclAssociationIdstringSubnetNetworkAclAssociationId*stringrequired#
subnetOutpostArnstringsubnet_outpost_arnstrsubnetOutpostArnStringSubnetOutpostArnstringSubnetOutpostArn*stringrequired#
The Amazon Resource Name (ARN) of the Outpost for this subnet (if one exists).
subnetRefSubnetReferencesubnet_refSubnetReferencesubnetRefSubnetReferenceSubnetRefSubnetReferenceSubnetRefSubnetReferencerequired#
A reference to a Subnet resource.
subnetVpcIdstringsubnet_vpc_idstrsubnetVpcIdStringSubnetVpcIdstringSubnetVpcId*stringrequired#

Methods ​

addDefaultInternetRoute(gatewayId: string, gatewayAttachment: IDependable): voiddef add_default_internet_route(self, gateway_id: str, gateway_attachment: IDependable) -> Nonepublic void addDefaultInternetRoute(String gatewayId, IDependable gatewayAttachment)public void AddDefaultInternetRoute(string gatewayId, IDependable gatewayAttachment)func AddDefaultInternetRoute(GatewayId *string, GatewayAttachment IDependable)#
Create a default route that points to a passed IGW, with a dependency on the IGW's attachment to the VPC.
2 parameters

Parameters

  • gatewayIdgateway_idgatewayIdgatewayIdGatewayId — the logical ID (ref) of the gateway attached to your VPC.
  • gatewayAttachmentgateway_attachmentgatewayAttachmentgatewayAttachmentGatewayAttachment — the gateway attachment construct to be added as a dependency.
addDefaultNatRoute(natGatewayId: string): voiddef add_default_nat_route(self, nat_gateway_id: str) -> Nonepublic void addDefaultNatRoute(String natGatewayId)public void AddDefaultNatRoute(string natGatewayId)func AddDefaultNatRoute(NatGatewayId *string)#
Adds an entry to this subnets route table that points to the passed NATGatewayId.
1 parameter

Parameters

  • natGatewayIdnat_gateway_idnatGatewayIdnatGatewayIdNatGatewayId — The ID of the NAT gateway.
addIpv6DefaultEgressOnlyInternetRoute(gatewayId: string): voiddef add_ipv6_default_egress_only_internet_route(self, gateway_id: str) -> Nonepublic void addIpv6DefaultEgressOnlyInternetRoute(String gatewayId)public void AddIpv6DefaultEgressOnlyInternetRoute(string gatewayId)func AddIpv6DefaultEgressOnlyInternetRoute(GatewayId *string)#
Create a default IPv6 route that points to a passed EIGW.
1 parameter

Parameters

  • gatewayIdgateway_idgatewayIdgatewayIdGatewayId — the logical ID (ref) of the gateway attached to your VPC.
addIpv6DefaultInternetRoute(gatewayId: string, gatewayAttachment?: IDependable): voiddef add_ipv6_default_internet_route(self, gateway_id: str, gateway_attachment: typing.Optional[IDependable] = None) -> Nonepublic void addIpv6DefaultInternetRoute(String gatewayId, IDependable gatewayAttachment)public void AddIpv6DefaultInternetRoute(string gatewayId, IDependable? gatewayAttachment = null)func AddIpv6DefaultInternetRoute(GatewayId *string, GatewayAttachment IDependable)#
Create a default IPv6 route that points to a passed IGW, with a dependency on the IGW's attachment to the VPC.
2 parameters

Parameters

  • gatewayIdgateway_idgatewayIdgatewayIdGatewayId — the logical ID (ref) of the gateway attached to your VPC.
  • gatewayAttachmentgateway_attachmentgatewayAttachmentgatewayAttachmentGatewayAttachment — the gateway attachment construct to be added as a dependency.
addIpv6Nat64Route(natGatewayId: string): voiddef add_ipv6_nat64_route(self, nat_gateway_id: str) -> Nonepublic void addIpv6Nat64Route(String natGatewayId)public void AddIpv6Nat64Route(string natGatewayId)func AddIpv6Nat64Route(NatGatewayId *string)#
Adds an entry to this subnets route table that points to the passed NATGatewayId.

Uses the known 64:ff9b::/96 prefix.

1 parameter

Parameters

  • natGatewayIdnat_gateway_idnatGatewayIdnatGatewayIdNatGatewayId — The ID of the NAT gateway.
addRoute(id: string, options: AddRouteOptions): voiddef add_route(self, id: str, options: AddRouteOptions) -> Nonepublic void addRoute(String id, AddRouteOptions options)public void AddRoute(string id, AddRouteOptions options)func AddRoute(Id *string, Options AddRouteOptions)#
Adds an entry to this subnets route table.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

associateNetworkAcl(id: string, networkAcl: INetworkAcl): voiddef associate_network_acl(self, id: str, network_acl: INetworkAcl) -> Nonepublic void associateNetworkAcl(String id, INetworkAcl networkAcl)public void AssociateNetworkAcl(string id, INetworkAcl networkAcl)func AssociateNetworkAcl(Id *string, NetworkAcl INetworkAcl)#
Associate a Network ACL with this subnet.
fromSubnetAttributes(scope: Construct, id: string, attrs: SubnetAttributes): ISubnet@staticmethod def from_subnet_attributes(scope: Construct, id: str, attrs: SubnetAttributes) -> ISubnetpublic static ISubnet fromSubnetAttributes(Construct scope, String id, SubnetAttributes attrs)public static ISubnet FromSubnetAttributes(Construct scope, string id, SubnetAttributes attrs)func FromSubnetAttributes(Scope Construct, Id *string, Attrs SubnetAttributes) ISubnetstatic#
fromSubnetId(scope: Construct, id: string, subnetId: string): ISubnet@staticmethod def from_subnet_id(scope: Construct, id: str, subnet_id: str) -> ISubnetpublic static ISubnet fromSubnetId(Construct scope, String id, String subnetId)public static ISubnet FromSubnetId(Construct scope, string id, string subnetId)func FromSubnetId(Scope Construct, Id *string, SubnetId *string) ISubnetstatic#
Import existing subnet from id.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
isVpcSubnet(x: any): boolean@staticmethod def is_vpc_subnet(x: Any) -> boolpublic static Boolean isVpcSubnet(Object x)public static bool IsVpcSubnet(object x)func IsVpcSubnet(X interface{}) *boolstatic#
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.