vpc.go

44 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
package digitalocean

import (
	"fmt"
	"strings"

	"congo.gg/pkg/platform"
	"github.com/digitalocean/godo"
)

// CreateVPC creates a VPC network in the specified region.
func (b *backend) CreateVPC(name, region, description string) (string, error) {
	doRegion, ok := regions[platform.Region(region)]
	if !ok {
		doRegion = region // Allow raw DO region slugs
	}

	vpc, _, err := b.client.VPCs.Create(b.ctx, &godo.VPCCreateRequest{
		Name:        name,
		RegionSlug:  doRegion,
		Description: description,
	})
	if err != nil {
		if strings.Contains(err.Error(), "already exists") {
			return b.GetVPC(name)
		}
		return "", fmt.Errorf("create VPC: %w", err)
	}
	return vpc.ID, nil
}

// GetVPC finds a VPC by name and returns its ID.
func (b *backend) GetVPC(name string) (string, error) {
	vpcs, _, err := b.client.VPCs.List(b.ctx, nil)
	if err != nil {
		return "", fmt.Errorf("list VPCs: %w", err)
	}
	for _, v := range vpcs {
		if v.Name == name {
			return v.ID, nil
		}
	}
	return "", fmt.Errorf("VPC %q not found", name)
}