Пример #1
0
func verifyAndCreateVPC(c *ec2.EC2, config *Config) error {

	dvi := &ec2.DescribeVpcsInput{}
	dvo, err := c.DescribeVpcs(dvi)
	if err != nil {
		return err
	}

	vpc := &ec2.Vpc{}
	vpcexists := false
	for i := range dvo.Vpcs {
		if *dvo.Vpcs[i].CidrBlock == config.VPC {
			vpc = dvo.Vpcs[i]
			vpcexists = true
			config.VpcId = *dvo.Vpcs[i].VpcId
			//fmt.Println("VPC already exists.")
		}
	}

	if vpcexists {

		err = createSecurityGroups(c, config)
		if err != nil {
			fmt.Println("Failed to create security groups.")
			panic(err)
		}

		/*
			sgids := getSecurityGroupIds(c,config,
			err = applySecurityGroups(c, config)
			if err != nil {
				fmt.Println("Failed to apply security groups.")
				panic(err)
			}
		*/

		dsi := &ec2.DescribeSubnetsInput{}
		dso, err := c.DescribeSubnets(dsi)
		if err != nil {
			panic(err)
		}

		haspriv := false
		haspub := false
		for i := range dso.Subnets {
			if *dso.Subnets[i].CidrBlock == config.PublicNet {
				//fmt.Println("Subnet for public VPC already exists.")
				config.PublicSubnetId = *dso.Subnets[i].SubnetId
				haspub = true
				continue
			}

			if *dso.Subnets[i].CidrBlock == config.PrivateNet {
				//fmt.Println("Subnet for private VPC already exists.")
				config.PrivateSubnetId = *dso.Subnets[i].SubnetId
				haspriv = true
				continue
			}
		}

		if haspub && haspriv {
			return nil
		}

		cso1, cso2, err := createSubnets(c, config)
		if err != nil {
			panic(err)
		}
		config.PublicSubnetId = *cso1.Subnet.SubnetId
		config.PrivateSubnetId = *cso2.Subnet.SubnetId

		_, err = createPrivateRouteTable(c, config)
		if err != nil {
			panic(err)
		}

		return createGateway(c, vpc, cso1.Subnet.SubnetId)

	}

	cvi := &ec2.CreateVpcInput{CidrBlock: &config.VPC}
	cvo, err := c.CreateVpc(cvi)

	if err != nil {
		return err
	}
	config.VpcId = *cvo.Vpc.VpcId
	fmt.Println("Created new VPC: " + config.VpcId)

	//fmt.Println(cvo)
	err = createSecurityGroups(c, config)
	if err != nil {
		fmt.Println("Failed to create security groups.")
		panic(err)
	}

	/*
		err = applySecurityGroups(c, config)
		if err != nil {
			fmt.Println("Failed to apply security groups.")
			panic(err)
		}
	*/

	cso1, cso2, err := createSubnets(c, config)
	config.PublicSubnetId = *cso1.Subnet.SubnetId
	config.PrivateSubnetId = *cso2.Subnet.SubnetId

	_, err = createPrivateRouteTable(c, config)
	if err != nil {
		panic(err)
	}

	return createGateway(c, cvo.Vpc, cso1.Subnet.SubnetId)

}