|
1 | 1 | package google
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "errors" |
4 | 5 | "fmt"
|
| 6 | + "net/url" |
5 | 7 | "regexp"
|
6 | 8 | "strings"
|
7 | 9 |
|
@@ -85,3 +87,58 @@ func NameFromSelfLinkStateFunc(v interface{}) string {
|
85 | 87 | func StoreResourceName(resourceLink interface{}) string {
|
86 | 88 | return GetResourceNameFromSelfLink(resourceLink.(string))
|
87 | 89 | }
|
| 90 | + |
| 91 | +type LocationType int |
| 92 | + |
| 93 | +const ( |
| 94 | + Zonal LocationType = iota |
| 95 | + Regional |
| 96 | + Global |
| 97 | +) |
| 98 | + |
| 99 | +func GetZonalResourcePropertiesFromSelfLinkOrSchema(d *schema.ResourceData, config *Config) (string, string, string, error) { |
| 100 | + return getResourcePropertiesFromSelfLinkOrSchema(d, config, Zonal) |
| 101 | +} |
| 102 | + |
| 103 | +func GetRegionalResourcePropertiesFromSelfLinkOrSchema(d *schema.ResourceData, config *Config) (string, string, string, error) { |
| 104 | + return getResourcePropertiesFromSelfLinkOrSchema(d, config, Regional) |
| 105 | +} |
| 106 | + |
| 107 | +func getResourcePropertiesFromSelfLinkOrSchema(d *schema.ResourceData, config *Config, locationType LocationType) (string, string, string, error) { |
| 108 | + if selfLink, ok := d.GetOk("self_link"); ok { |
| 109 | + parsed, err := url.Parse(selfLink.(string)) |
| 110 | + if err != nil { |
| 111 | + return "", "", "", err |
| 112 | + } |
| 113 | + |
| 114 | + s := strings.Split(parsed.Path, "/") |
| 115 | + // https://www.googleapis.com/compute/beta/projects/project_name/regions/region_name/instanceGroups/foobarbaz |
| 116 | + // => project_name, region_name, foobarbaz |
| 117 | + return s[4], s[6], s[8], nil |
| 118 | + } else { |
| 119 | + project, err := getProject(d, config) |
| 120 | + if err != nil { |
| 121 | + return "", "", "", err |
| 122 | + } |
| 123 | + |
| 124 | + location := "" |
| 125 | + if locationType == Regional { |
| 126 | + location, err = getRegion(d, config) |
| 127 | + if err != nil { |
| 128 | + return "", "", "", err |
| 129 | + } |
| 130 | + } else if locationType == Zonal { |
| 131 | + location, err = getZone(d, config) |
| 132 | + if err != nil { |
| 133 | + return "", "", "", err |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + n, ok := d.GetOk("name") |
| 138 | + name := n.(string) |
| 139 | + if !ok { |
| 140 | + return "", "", "", errors.New("must provide either `self_link` or `name`") |
| 141 | + } |
| 142 | + return project, location, name, nil |
| 143 | + } |
| 144 | +} |
0 commit comments