Skip to content
v2.273.0

PublicSubnet L2 construct ​

Represents a public VPC subnet resource.

Example ​

ts
// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
import { aws_ec2 as ec2 } from 'aws-cdk-lib';
const publicSubnet = new ec2.PublicSubnet(this, 'MyPublicSubnet', {
  availabilityZone: 'availabilityZone',
  cidrBlock: 'cidrBlock',
  vpcId: 'vpcId',

  // the properties below are optional
  assignIpv6AddressOnCreation: false,
  ipv6CidrBlock: 'ipv6CidrBlock',
  mapPublicIpOnLaunch: false,
});
python
# The code below shows an example of how to instantiate this type.
# The values are placeholders you should change.
from aws_cdk import aws_ec2 as ec2

public_subnet = ec2.PublicSubnet(self, "MyPublicSubnet",
    availability_zone="availabilityZone",
    cidr_block="cidrBlock",
    vpc_id="vpcId",

    # the properties below are optional
    assign_ipv6_address_on_creation=False,
    ipv6_cidr_block="ipv6CidrBlock",
    map_public_ip_on_launch=False
)
java
// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
import software.amazon.awscdk.services.ec2.*;

PublicSubnet publicSubnet = PublicSubnet.Builder.create(this, "MyPublicSubnet")
        .availabilityZone("availabilityZone")
        .cidrBlock("cidrBlock")
        .vpcId("vpcId")

        // the properties below are optional
        .assignIpv6AddressOnCreation(false)
        .ipv6CidrBlock("ipv6CidrBlock")
        .mapPublicIpOnLaunch(false)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
using Amazon.CDK.AWS.EC2;

var publicSubnet = new PublicSubnet(this, "MyPublicSubnet", new PublicSubnetProps {
    AvailabilityZone = "availabilityZone",
    CidrBlock = "cidrBlock",
    VpcId = "vpcId",

    // the properties below are optional
    AssignIpv6AddressOnCreation = false,
    Ipv6CidrBlock = "ipv6CidrBlock",
    MapPublicIpOnLaunch = false
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
import "github.com/aws/aws-cdk-go/awscdk"

publicSubnet := awscdk.Aws_ec2.NewPublicSubnet(this, jsii.String("MyPublicSubnet"), &PublicSubnetProps{
	AvailabilityZone: jsii.String("availabilityZone"),
	CidrBlock: jsii.String("cidrBlock"),
	VpcId: jsii.String("vpcId"),

	// the properties below are optional
	AssignIpv6AddressOnCreation: jsii.Boolean(false),
	Ipv6CidrBlock: jsii.String("ipv6CidrBlock"),
	MapPublicIpOnLaunch: jsii.Boolean(false),
})

Initializer ​

ts
new PublicSubnet(scope: Construct, id: string, props: PublicSubnetProps)
python
PublicSubnet(scope: Construct, id: str, props: PublicSubnetProps)
java
new PublicSubnet(Construct scope, String id, PublicSubnetProps props)
csharp
new PublicSubnet(Construct scope, string id, PublicSubnetProps props)
go
NewPublicSubnet(Scope Construct, Id *string, Props PublicSubnetProps)

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.
addNatGateway(eipAllocationId?: string, options?: AddNatGatewayOptions): CfnNatGatewaydef add_nat_gateway(self, eip_allocation_id: typing.Optional[str] = None, options: typing.Optional[AddNatGatewayOptions] = None) -> CfnNatGatewaypublic CfnNatGateway addNatGateway(String eipAllocationId, AddNatGatewayOptions options)public CfnNatGateway AddNatGateway(string? eipAllocationId = null, AddNatGatewayOptions? options = null)func AddNatGateway(EipAllocationId *string, Options AddNatGatewayOptions) CfnNatGateway#
Creates a new managed NAT gateway attached to this public subnet.

Also adds the EIP for the managed NAT.

2 parameters · returns

Parameters

  • eipAllocationIdeip_allocation_ideipAllocationIdeipAllocationIdEipAllocationId — Allocation ID of an Elastic IP address to assign to the NAT gateway.
  • optionsoptionsoptionsoptionsOptions — Additional options for the NAT gateway.

Returns: A ref to the NAT Gateway ID

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.
fromPublicSubnetAttributes(scope: Construct, id: string, attrs: PublicSubnetAttributes): IPublicSubnet@staticmethod def from_public_subnet_attributes(scope: Construct, id: str, attrs: PublicSubnetAttributes) -> IPublicSubnetpublic static IPublicSubnet fromPublicSubnetAttributes(Construct scope, String id, PublicSubnetAttributes attrs)public static IPublicSubnet FromPublicSubnetAttributes(Construct scope, string id, PublicSubnetAttributes attrs)func FromPublicSubnetAttributes(Scope Construct, Id *string, Attrs PublicSubnetAttributes) IPublicSubnetstatic#
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.