smallcasecdkvpcmodule

package module
v0.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2025 License: Apache-2.0 Imports: 9 Imported by: 0

README

cdk-vpc-module

cdk-vpc-module construct library is an open-source extension of the AWS Cloud Development Kit (AWS CDK) to deploy configurable aws vpc and its individual components in less than 50 lines of code and human readable configuration which can be managed by pull requests!

✨ Features

  • ✅ Option to configure custom IPv4 CIDR(10.10.0.0/24)
  • ✅ VPC Peering with route table entry
  • ✅ Configurable NACL as per subnet group
  • ✅ NATGateway as per availabilityZones

Using cdk a vpc can be deployed using the following sample code snippet:

import { Network } from "@smallcase/cdk-vpc-module/lib/constructs/network";
import { aws_ec2 as ec2, App, Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";

export class VPCStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps = {}) {
    const s3EndpointIamPermission = new iam.PolicyStatement({
      actions: ["s3:*"],
      resources: ['arn:aws:s3:::*'],
      principals: [new iam.AnyPrincipal()],
    })
    const monitoringEndpointIamPermission = new iam.PolicyStatement({
      actions: ["*"],
      resources: ['*'],
      principals: [new iam.AnyPrincipal()],
    })
    super(scope, id, props);
    new Network(this, 'NETWORK', {
      vpc: {
        cidr: '10.10.0.0/16',
        subnetConfiguration: [],
      },
      peeringConfigs: {
        "TEST-PEERING": { // this key will be used as your peering id, which you will have to mention below when you configure a route table for your subnets
          peeringVpcId: "vpc-0000",
          tags: {
            "Name": "TEST-PEERING to CREATED-VPC",
            "Description": "Connect"
          }
        }
      },
      subnets: [
        {
          subnetGroupName: 'NATGateway',
          subnetType: ec2.SubnetType.PUBLIC,
          cidrBlock: ['10.10.0.0/28', '10.10.0.16/28', '10.10.0.32/28'],
          availabilityZones: ['ap-south-1a', 'ap-south-1b', 'ap-south-1c'],
          ingressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          routes: [
          ],
          egressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
        },
        {
          subnetGroupName: 'Public',
          subnetType: ec2.SubnetType.PUBLIC,
          cidrBlock: ['10.10.2.0/24', '10.10.3.0/24', '10.10.4.0/24'],
          availabilityZones: ['ap-south-1a', 'ap-south-1b', 'ap-south-1c'],
          ingressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          egressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          routes: [
          ],
          tags: {
            // if you use this vpc for your eks cluster, you have to tag your subnets [read more](https://aws.amazon.com/premiumsupport/knowledge-center/eks-vpc-subnet-discovery/)
            'kubernetes.io/role/elb': '1',
            'kubernetes.io/cluster/TEST-CLUSTER': 'owned',
          },
        },
        {
          subnetGroupName: 'Private',
          subnetType: ec2.SubnetType.PRIVATE_WITH_NAT,
          cidrBlock: ['10.10.5.0/24', '10.10.6.0/24', '10.10.7.0/24'],
          availabilityZones: ['ap-south-1a', 'ap-south-1b', 'ap-south-1c'],
          ingressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          egressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },

          ],
          routes: [
            {
            // if you use this vpc for your eks cluster, you have to tag your subnets [read more](https://aws.amazon.com/premiumsupport/knowledge-center/eks-vpc-subnet-discovery/)
              routerType: ec2.RouterType.VPC_PEERING_CONNECTION,
              destinationCidrBlock: "<destinationCidrBlock>",
              //<Your VPC PeeringConfig KEY, in this example TEST-PEERING will be your ID>
              existingVpcPeeringRouteKey: "TEST-PEERING"
            }
          ],
          tags: {
            'kubernetes.io/role/internal-elb': '1',
            'kubernetes.io/cluster/TEST-CLUSTER': 'owned',
          },
        },
        {
          subnetGroupName: 'Database',
          subnetType: ec2.SubnetType.PRIVATE_WITH_NAT,
          cidrBlock: ['10.10.14.0/27', '10.10.14.32/27', '10.10.14.64/27'],
          availabilityZones: ['ap-south-1a', 'ap-south-1b', 'ap-south-1c'],
          ingressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          egressNetworkACL: [
            {
              cidr: ec2.AclCidr.ipv4('0.0.0.0/0'),
              traffic: ec2.AclTraffic.allTraffic(),
            },
          ],
          routes: [
          ],
          tags: {
          },
        },
      ],
      vpcEndpoints: [
        {
          name: "s3-gw",
          service: ec2.GatewayVpcEndpointAwsService.S3,
          subnetGroupNames: ["Private","Database"],
          externalSubnets: [
            {
              id: "subnet-<id>",
              availabilityZone: "ap-south-1a",
              routeTableId: "rtb-<id>"
            },
            {
              id: "subnet-<id>",
              availabilityZone: "ap-south-1b",
              routeTableId: "rtb-<id>"
            }
          ],
          iamPolicyStatements: [s3EndpointIamPermission]
        },
        {
          name: "da-stag-monitoring-vpe",
          service: ec2.InterfaceVpcEndpointAwsService.CLOUDWATCH_MONITORING,
          subnetGroupNames: ["ManageServicePrivate"],
          iamPolicyStatements: [monitoringEndpointIamPermission],
          securityGroupRules: [
            {
              peer: ec2.Peer.ipv4("10.10.0.0/16"),
              port:  ec2.Port.tcp(443),
              description: "From Test VPC"
            }
          ],
        },
      ]
    });
  }
}
const envDef = {
  account: '<AWS-ID>',
  region: '<AWS-REGION>',
};

const app = new App();

new VPCStack(app, 'TEST', {
  env: envDef,
  terminationProtection: true,
  tags: {
});
app.synth();

Please refer here to check how to use individual resource constructs.

🎬 Quick Start

The quick start shows you how to create an AWS-VPC using this module.

Prerequisites
  • A working aws CLI installation with access to an account and administrator privileges
  • You'll need a recent NodeJS installation

To get going you'll need a CDK project. For details please refer to the detailed guide for CDK.

Create an empty directory on your system.

mkdir aws-quick-start-vpc && cd aws-quick-start-vpc

Bootstrap your CDK project, we will use TypeScript, but you can switch to any other supported language.

npx cdk init sample-vpc  --language typescript
npx cdk bootstrap

Install using NPM:

npm install @smallcase/cdk-vpc-module

Using yarn

yarn add @smallcase/cdk-vpc-module

Check the changed which are to be deployed

~ -> npx cdk diff

Deploy using

~ -> npx cdk deploy

Features Multiple VPC Endpoints: Define and manage multiple VPC Endpoints in one configuration. Flexible Subnet Selection: Attach VPC Endpoints to multiple subnet groups or external subnets. Custom Security Groups: Configure security groups for Interface VPC Endpoints. IAM Policies: Attach custom IAM policies to control access to the VPC Endpoints. Tagging: Apply custom tags to each VPC Endpoint.

Defining VPC Endpoints Configuration You can define multiple VPC Endpoints in the vpcEndpoints: [] configuration array. Each VPC Endpoint can be customized with different subnet groups, IAM policies, security group rules, and tags.

vpcEndpoints: [
  {
    name: "test-s3-gw",
    service: ec2.GatewayVpcEndpointAwsService.S3,
    subnetGroupNames: ["ManageServicePrivate", "ToolPrivate", "Database"],  // Subnet groups for the endpoint
    externalSubnets: [
      {
        id: "subnet-<id>",
        availabilityZone: "ap-south-1a",
        routeTableId: "rtb-<id>",
      },
      {
        id: "subnet-<id>",
        availabilityZone: "ap-south-1b",
        routeTableId: "rtb-<id>",
      }
    ],
    iamPolicyStatements: [s3EndpointIamPermission],  // Custom IAM policy for the endpoint
  },
  {
    name: "DynamoDbGatewayEndpoint",
    service: ec2.GatewayVpcEndpointAwsService.DYNAMODB,
    subnetGroupNames: ["private-subnet"],
    additionalTags: {
      Environment: "Staging",
    },
  },
],

In this example:

The S3 Gateway Endpoint is created in three subnet groups: ManageServicePrivate, ToolPrivate, and Database. External subnets are specified with their IDs, availability zones, and route table IDs for the S3 endpoint. A custom IAM policy (s3EndpointIamPermission) is attached to control access to the S3 endpoint. A DynamoDB Gateway Endpoint is created in the private-subnet with additional tags specifying the environment and ownership.

Configuration Options Here’s a breakdown of the configuration options available:

  1. name: A unique name for the VPC Endpoint.
  2. service: The AWS service the VPC Endpoint connects to (e.g., S3, DynamoDB, Secrets Manager)
  3. subnetGroupNames: The subnet group names where the VPC Endpoint will be deployed.
  4. externalSubnets: Specify external subnets if you need to define subnets manually (each with an id, availabilityZone, and routeTableId).
  5. iamPolicyStatements: (Optional) Attach IAM policy statements to control access to the endpoint.
  6. additionalTags: (Optional) Add custom tags to the VPC Endpoint for easier identification and tracking.

Documentation

Overview

@smallcase/cdk-vpc-module

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Network_IsConstruct

func Network_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Returns: true if `x` is an object created from a class which extends `Construct`. Deprecated: use `x instanceof Construct` instead.

func NewNetwork_Override

func NewNetwork_Override(n Network, scope constructs.Construct, id *string, props *VPCProps)

Types

type AddRouteOptions

type AddRouteOptions struct {
	// What type of router to route this traffic to.
	RouterType awsec2.RouterType `field:"required" json:"routerType" yaml:"routerType"`
	// IPv4 range this route applies to.
	// Default: '0.0.0.0/0'
	//
	DestinationCidrBlock *string `field:"optional" json:"destinationCidrBlock" yaml:"destinationCidrBlock"`
	// IPv6 range this route applies to.
	// Default: - Uses IPv6.
	//
	DestinationIpv6CidrBlock *string `field:"optional" json:"destinationIpv6CidrBlock" yaml:"destinationIpv6CidrBlock"`
	// Whether this route will enable internet connectivity.
	//
	// If true, this route will be added before any AWS resources that depend
	// on internet connectivity in the VPC will be created.
	// Default: false.
	//
	EnablesInternetConnectivity *bool   `field:"optional" json:"enablesInternetConnectivity" yaml:"enablesInternetConnectivity"`
	ExistingVpcPeeringRouteKey  *string `field:"optional" json:"existingVpcPeeringRouteKey" yaml:"existingVpcPeeringRouteKey"`
	RouterId                    *string `field:"optional" json:"routerId" yaml:"routerId"`
}

type IExternalVPEndpointSubnets added in v0.0.10

type IExternalVPEndpointSubnets interface {
	AvailabilityZone() *string
	Id() *string
	RouteTableId() *string
}

type ISubnetsProps

type ISubnetsProps interface {
	AvailabilityZones() *[]*string
	CidrBlock() *[]*string
	EgressNetworkACL() *[]*NetworkACL
	IngressNetworkACL() *[]*NetworkACL
	Routes() *[]*AddRouteOptions
	SubnetGroupName() *string
	SubnetType() awsec2.SubnetType
	Tags() *map[string]*string
	UseSubnetForNAT() *bool
}

type LoadBalancerConfig added in v0.0.13

type LoadBalancerConfig struct {
	Certificates            *[]*string            `field:"optional" json:"certificates" yaml:"certificates"`
	ExistingArn             *string               `field:"optional" json:"existingArn" yaml:"existingArn"`
	ExistingSecurityGroupId *string               `field:"optional" json:"existingSecurityGroupId" yaml:"existingSecurityGroupId"`
	InternetFacing          *bool                 `field:"optional" json:"internetFacing" yaml:"internetFacing"`
	SecurityGroupRules      *[]*SecurityGroupRule `field:"optional" json:"securityGroupRules" yaml:"securityGroupRules"`
	SubnetGroupName         *string               `field:"optional" json:"subnetGroupName" yaml:"subnetGroupName"`
	TargetGroups            *[]*TargetGroupConfig `field:"optional" json:"targetGroups" yaml:"targetGroups"`
}

type Network

type Network interface {
	constructs.Construct
	EndpointOutputs() *map[string]interface{}
	NatProvider() awsec2.NatProvider
	NatSubnets() *[]awsec2.PublicSubnet
	SetNatSubnets(val *[]awsec2.PublicSubnet)
	// The tree node.
	Node() constructs.Node
	PbSubnets() *[]awsec2.PublicSubnet
	SetPbSubnets(val *[]awsec2.PublicSubnet)
	PvSubnets() *[]awsec2.PrivateSubnet
	SetPvSubnets(val *[]awsec2.PrivateSubnet)
	SecurityGroupOutputs() *map[string]awsec2.SecurityGroup
	Subnets() *map[string]*[]awsec2.Subnet
	SetSubnets(val *map[string]*[]awsec2.Subnet)
	Vpc() awsec2.Vpc
	CreateSubnet(option ISubnetsProps, vpc awsec2.Vpc, peeringConnectionId *PeeringConnectionInternalType) *[]awsec2.Subnet
	// Returns a string representation of this construct.
	ToString() *string
}

func NewNetwork

func NewNetwork(scope constructs.Construct, id *string, props *VPCProps) Network

type NetworkACL

type NetworkACL struct {
	Cidr    awsec2.AclCidr    `field:"required" json:"cidr" yaml:"cidr"`
	Traffic awsec2.AclTraffic `field:"required" json:"traffic" yaml:"traffic"`
}

type NetworkLoadBalancerConfig added in v0.0.13

type NetworkLoadBalancerConfig struct {
	SecurityGroupRules      *[]*SecurityGroupRule `field:"required" json:"securityGroupRules" yaml:"securityGroupRules"`
	SubnetGroupName         *string               `field:"required" json:"subnetGroupName" yaml:"subnetGroupName"`
	Certificates            *[]*string            `field:"optional" json:"certificates" yaml:"certificates"`
	ExistingSecurityGroupId *string               `field:"optional" json:"existingSecurityGroupId" yaml:"existingSecurityGroupId"`
	InternetFacing          *bool                 `field:"optional" json:"internetFacing" yaml:"internetFacing"`
}

type PeeringConfig

type PeeringConfig struct {
	PeeringVpcId      *string             `field:"required" json:"peeringVpcId" yaml:"peeringVpcId"`
	Tags              *map[string]*string `field:"required" json:"tags" yaml:"tags"`
	PeerAssumeRoleArn *string             `field:"optional" json:"peerAssumeRoleArn" yaml:"peerAssumeRoleArn"`
	PeerOwnerId       *string             `field:"optional" json:"peerOwnerId" yaml:"peerOwnerId"`
	PeerRegion        *string             `field:"optional" json:"peerRegion" yaml:"peerRegion"`
}

type PeeringConnectionInternalType

type PeeringConnectionInternalType struct {
}

type SecurityGroupRule added in v0.0.10

type SecurityGroupRule struct {
	Peer        interface{} `field:"required" json:"peer" yaml:"peer"`
	Port        awsec2.Port `field:"required" json:"port" yaml:"port"`
	Description *string     `field:"optional" json:"description" yaml:"description"`
}

type TargetGroupConfig added in v0.0.13

type TargetGroupConfig struct {
	ApplicationPort     *float64                                             `field:"required" json:"applicationPort" yaml:"applicationPort"`
	Host                *string                                              `field:"required" json:"host" yaml:"host"`
	HealthCheckPath     *string                                              `field:"optional" json:"healthCheckPath" yaml:"healthCheckPath"`
	HealthCheckPort     *float64                                             `field:"optional" json:"healthCheckPort" yaml:"healthCheckPort"`
	HealthCheckProtocol awselasticloadbalancingv2.Protocol                   `field:"optional" json:"healthCheckProtocol" yaml:"healthCheckProtocol"`
	Priority            *float64                                             `field:"optional" json:"priority" yaml:"priority"`
	Protocol            awselasticloadbalancingv2.ApplicationProtocol        `field:"optional" json:"protocol" yaml:"protocol"`
	ProtocolVersion     awselasticloadbalancingv2.ApplicationProtocolVersion `field:"optional" json:"protocolVersion" yaml:"protocolVersion"`
}

type VPCProps

type VPCProps struct {
	Subnets             *[]ISubnetsProps            `field:"required" json:"subnets" yaml:"subnets"`
	Vpc                 *awsec2.VpcProps            `field:"required" json:"vpc" yaml:"vpc"`
	NatEipAllocationIds *[]*string                  `field:"optional" json:"natEipAllocationIds" yaml:"natEipAllocationIds"`
	PeeringConfigs      *map[string]*PeeringConfig  `field:"optional" json:"peeringConfigs" yaml:"peeringConfigs"`
	VpcEndpoints        *[]*VpcEndpointConfig       `field:"optional" json:"vpcEndpoints" yaml:"vpcEndpoints"`
	VpcEndpointServices *[]*VpcEndpontServiceConfig `field:"optional" json:"vpcEndpointServices" yaml:"vpcEndpointServices"`
}

type VpcEndpointConfig added in v0.0.10

type VpcEndpointConfig struct {
	Name                *string                       `field:"required" json:"name" yaml:"name"`
	Service             interface{}                   `field:"required" json:"service" yaml:"service"`
	SubnetGroupNames    *[]*string                    `field:"required" json:"subnetGroupNames" yaml:"subnetGroupNames"`
	AdditionalTags      *map[string]*string           `field:"optional" json:"additionalTags" yaml:"additionalTags"`
	ExternalSubnets     *[]IExternalVPEndpointSubnets `field:"optional" json:"externalSubnets" yaml:"externalSubnets"`
	IamPolicyStatements *[]awsiam.PolicyStatement     `field:"optional" json:"iamPolicyStatements" yaml:"iamPolicyStatements"`
	SecurityGroupRules  *[]*SecurityGroupRule         `field:"optional" json:"securityGroupRules" yaml:"securityGroupRules"`
}

type VpcEndpontServiceConfig added in v0.0.13

type VpcEndpontServiceConfig struct {
	Alb                *LoadBalancerConfig        `field:"required" json:"alb" yaml:"alb"`
	Name               *string                    `field:"required" json:"name" yaml:"name"`
	Nlb                *NetworkLoadBalancerConfig `field:"required" json:"nlb" yaml:"nlb"`
	AcceptanceRequired *bool                      `field:"optional" json:"acceptanceRequired" yaml:"acceptanceRequired"`
	AdditionalTags     *map[string]*string        `field:"optional" json:"additionalTags" yaml:"additionalTags"`
	AllowedPrincipals  *[]*string                 `field:"optional" json:"allowedPrincipals" yaml:"allowedPrincipals"`
}

Directories

Path Synopsis
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL