Created
March 29, 2023 20:27
-
-
Save sebnyberg/9a3ad6a5433fd7c90e509af02d88d797 to your computer and use it in GitHub Desktop.
ChatGPT module thing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/pulumi/pulumi-aws/sdk/v4/go/aws/ec2" | |
"github.com/pulumi/pulumi/sdk/v3/go/pulumi" | |
) | |
type VpcArgs struct { | |
Name string | |
CidrBlock string | |
SubnetCidrs []string | |
SecurityTags map[string]string | |
EnableNatGateway bool | |
} | |
type Vpc struct { | |
pulumi.ResourceState | |
Vpc *ec2.Vpc | |
Subnets []*ec2.Subnet | |
SecurityGroup *ec2.SecurityGroup | |
NatGatewayEips []*ec2.Eip | |
NatGateways []*ec2.NatGateway | |
} | |
func NewVpc(ctx *pulumi.Context, name string, args *VpcArgs) (*Vpc, error) { | |
// Create the VPC | |
vpc, err := ec2.NewVpc(ctx, name, &ec2.VpcArgs{ | |
CidrBlock: pulumi.String(args.CidrBlock), | |
}) | |
if err != nil { | |
return nil, err | |
} | |
// Create the subnets | |
var subnets []*ec2.Subnet | |
for _, cidr := range args.SubnetCidrs { | |
subnet, err := ec2.NewSubnet(ctx, name+"-"+cidr, &ec2.SubnetArgs{ | |
VpcId: vpc.ID(), | |
CidrBlock: pulumi.String(cidr), | |
}) | |
if err != nil { | |
return nil, err | |
} | |
subnets = append(subnets, subnet) | |
} | |
// Create the security group | |
securityGroup, err := ec2.NewSecurityGroup(ctx, name+"-sg", &ec2.SecurityGroupArgs{ | |
VpcId: vpc.ID(), | |
Tags: pulumi.Map(args.SecurityTags), | |
Ingress: ec2.SecurityGroupIngressArray{}, | |
Egress: ec2.SecurityGroupEgressArray{}, | |
}) | |
if err != nil { | |
return nil, err | |
} | |
// Create NAT gateways and EIPs if enabled | |
var natGatewayEips []*ec2.Eip | |
var natGateways []*ec2.NatGateway | |
if args.EnableNatGateway { | |
// Create an EIP for each subnet | |
for _, subnet := range subnets { | |
eip, err := ec2.NewEip(ctx, name+"-eip-"+subnet.ID(), &ec2.EipArgs{ | |
Vpc: pulumi.Bool(true), | |
}) | |
if err != nil { | |
return nil, err | |
} | |
natGatewayEips = append(natGatewayEips, eip) | |
// Create a NAT gateway for each subnet using the EIP | |
natGateway, err := ec2.NewNatGateway(ctx, name+"-natgw-"+subnet.ID(), &ec2.NatGatewayArgs{ | |
SubnetId: subnet.ID(), | |
AllocationId: eip.AllocationId, | |
}) | |
if err != nil { | |
return nil, err | |
} | |
natGateways = append(natGateways, natGateway) | |
} | |
} | |
// Return the VPC, subnets, security group, NAT gateways, and EIPs as a component resource | |
return &Vpc{ | |
Vpc: vpc, | |
Subnets: subnets, | |
SecurityGroup: securityGroup, | |
NatGatewayEips: natGatewayEips, | |
NatGateways: natGateways, | |
}, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment