github.com/Hashicorp/packer@v1.3.2/builder/googlecompute/networking.go (about)

     1  package googlecompute
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // This method will build a network and subnetwork ID from the provided
     9  // instance config, and return them in that order.
    10  func getNetworking(c *InstanceConfig) (string, string, error) {
    11  	networkId := c.Network
    12  	subnetworkId := c.Subnetwork
    13  
    14  	// Apply network naming requirements per
    15  	// https://cloud.google.com/compute/docs/reference/latest/instances#resource
    16  	switch c.Network {
    17  	// It is possible to omit the network property as long as a subnet is
    18  	// specified. That will be validated later.
    19  	case "":
    20  		break
    21  	// This special short name should be expanded.
    22  	case "default":
    23  		networkId = "global/networks/default"
    24  	// A value other than "default" was provided for the network name.
    25  	default:
    26  		// If the value doesn't contain a slash, we assume it's not a full or
    27  		// partial URL. We will expand it into a partial URL here and avoid
    28  		// making an API call to discover the network as it's common for the
    29  		// caller to not have permission against network discovery APIs.
    30  		if !strings.Contains(c.Network, "/") {
    31  			networkId = "projects/" + c.NetworkProjectId + "/global/networks/" + c.Network
    32  		}
    33  	}
    34  
    35  	// Apply subnetwork naming requirements per
    36  	// https://cloud.google.com/compute/docs/reference/latest/instances#resource
    37  	switch c.Subnetwork {
    38  	case "":
    39  		// You can't omit both subnetwork and network
    40  		if networkId == "" {
    41  			return networkId, subnetworkId, fmt.Errorf("both network and subnetwork were empty.")
    42  		}
    43  		// An empty subnetwork is only valid for networks in legacy mode or
    44  		// auto-subnet mode. We could make an API call to get that information
    45  		// about the network, but it's common for the caller to not have
    46  		// permission to that API. We'll proceed assuming they're correct in
    47  		// omitting the subnetwork and let the compute.insert API surface an
    48  		// error about an invalid network configuration if it exists.
    49  		break
    50  	default:
    51  		// If the value doesn't contain a slash, we assume it's not a full or
    52  		// partial URL. We will expand it into a partial URL here and avoid
    53  		// making a call to discover the subnetwork.
    54  		if !strings.Contains(c.Subnetwork, "/") {
    55  			subnetworkId = "projects/" + c.NetworkProjectId + "/regions/" + c.Region + "/subnetworks/" + c.Subnetwork
    56  		}
    57  	}
    58  	return networkId, subnetworkId, nil
    59  }