diff --git a/.changelog/4855.txt b/.changelog/4855.txt new file mode 100644 index 0000000000..cd42ceb244 --- /dev/null +++ b/.changelog/4855.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_compute_service_attachment` +``` diff --git a/google-beta/provider.go b/google-beta/provider.go index 6c1117fcba..47eec6b424 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -847,9 +847,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 224 +// Generated resources: 225 // Generated IAM resources: 117 -// Total generated resources: 341 +// Total generated resources: 342 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -999,6 +999,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_managed_ssl_certificate": resourceComputeManagedSslCertificate(), "google_compute_region_ssl_certificate": resourceComputeRegionSslCertificate(), "google_compute_reservation": resourceComputeReservation(), + "google_compute_service_attachment": resourceComputeServiceAttachment(), "google_compute_ssl_policy": resourceComputeSslPolicy(), "google_compute_subnetwork": resourceComputeSubnetwork(), "google_compute_subnetwork_iam_binding": ResourceIamBinding(ComputeSubnetworkIamSchema, ComputeSubnetworkIamUpdaterProducer, ComputeSubnetworkIdParseFunc), diff --git a/google-beta/resource_compute_service_attachment.go b/google-beta/resource_compute_service_attachment.go new file mode 100644 index 0000000000..8893292054 --- /dev/null +++ b/google-beta/resource_compute_service_attachment.go @@ -0,0 +1,612 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "log" + "reflect" + "strconv" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceComputeServiceAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceComputeServiceAttachmentCreate, + Read: resourceComputeServiceAttachmentRead, + Delete: resourceComputeServiceAttachmentDelete, + + Importer: &schema.ResourceImporter{ + State: resourceComputeServiceAttachmentImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "connection_preference": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The connection preference to use for this service attachment. Valid +values include "ACCEPT_AUTOMATIC", "ACCEPT_MANUAL".`, + }, + "enable_proxy_protocol": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + Description: `If true, enable the proxy protocol which is for supplying client TCP/IP +address data in TCP connections that traverse proxies on their way to +destination servers.`, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Name of the resource. The name must be 1-63 characters long, and +comply with RFC1035. Specifically, the name must be 1-63 characters +long and match the regular expression '[a-z]([-a-z0-9]*[a-z0-9])?' +which means the first character must be a lowercase letter, and all +following characters must be a dash, lowercase letter, or digit, +except the last character, which cannot be a dash.`, + }, + "nat_subnets": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: `An array of subnets that is provided for NAT in this service attachment.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, + }, + "target_service": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + Description: `The URL of a forwarding rule that represents the service identified by +this service attachment.`, + }, + "consumer_accept_lists": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `An array of projects that are allowed to connect to this service +attachment.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "connection_limit": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: `The number of consumer forwarding rules the consumer project can +create.`, + }, + "project_id_or_num": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `A project that is allowed to connect to this service attachment.`, + }, + }, + }, + }, + "consumer_reject_lists": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `An array of projects that are not allowed to connect to this service +attachment.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `An optional description of this resource.`, + }, + "region": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + Description: `URL of the region where the resource resides.`, + }, + "connected_endpoints": { + Type: schema.TypeList, + Computed: true, + Description: `An array of the consumer forwarding rules connected to this service +attachment.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "endpoint": { + Type: schema.TypeString, + Computed: true, + Description: `The URL of the consumer forwarding rule.`, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: `The status of the connection from the consumer forwarding rule to +this service attachment.`, + }, + }, + }, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + "self_link": { + Type: schema.TypeString, + Computed: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceComputeServiceAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + nameProp, err := expandComputeServiceAttachmentName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp + } + descriptionProp, err := expandComputeServiceAttachmentDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + connectionPreferenceProp, err := expandComputeServiceAttachmentConnectionPreference(d.Get("connection_preference"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("connection_preference"); !isEmptyValue(reflect.ValueOf(connectionPreferenceProp)) && (ok || !reflect.DeepEqual(v, connectionPreferenceProp)) { + obj["connectionPreference"] = connectionPreferenceProp + } + targetServiceProp, err := expandComputeServiceAttachmentTargetService(d.Get("target_service"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("target_service"); !isEmptyValue(reflect.ValueOf(targetServiceProp)) && (ok || !reflect.DeepEqual(v, targetServiceProp)) { + obj["targetService"] = targetServiceProp + } + natSubnetsProp, err := expandComputeServiceAttachmentNatSubnets(d.Get("nat_subnets"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("nat_subnets"); !isEmptyValue(reflect.ValueOf(natSubnetsProp)) && (ok || !reflect.DeepEqual(v, natSubnetsProp)) { + obj["natSubnets"] = natSubnetsProp + } + enableProxyProtocolProp, err := expandComputeServiceAttachmentEnableProxyProtocol(d.Get("enable_proxy_protocol"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("enable_proxy_protocol"); !isEmptyValue(reflect.ValueOf(enableProxyProtocolProp)) && (ok || !reflect.DeepEqual(v, enableProxyProtocolProp)) { + obj["enableProxyProtocol"] = enableProxyProtocolProp + } + consumerRejectListsProp, err := expandComputeServiceAttachmentConsumerRejectLists(d.Get("consumer_reject_lists"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("consumer_reject_lists"); !isEmptyValue(reflect.ValueOf(consumerRejectListsProp)) && (ok || !reflect.DeepEqual(v, consumerRejectListsProp)) { + obj["consumerRejectLists"] = consumerRejectListsProp + } + consumerAcceptListsProp, err := expandComputeServiceAttachmentConsumerAcceptLists(d.Get("consumer_accept_lists"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("consumer_accept_lists"); !isEmptyValue(reflect.ValueOf(consumerAcceptListsProp)) && (ok || !reflect.DeepEqual(v, consumerAcceptListsProp)) { + obj["consumerAcceptLists"] = consumerAcceptListsProp + } + regionProp, err := expandComputeServiceAttachmentRegion(d.Get("region"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("region"); !isEmptyValue(reflect.ValueOf(regionProp)) && (ok || !reflect.DeepEqual(v, regionProp)) { + obj["region"] = regionProp + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/serviceAttachments") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new ServiceAttachment: %#v", obj) + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ServiceAttachment: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating ServiceAttachment: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = computeOperationWaitTime( + config, res, project, "Creating ServiceAttachment", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create ServiceAttachment: %s", err) + } + + log.Printf("[DEBUG] Finished creating ServiceAttachment %q: %#v", d.Id(), res) + + return resourceComputeServiceAttachmentRead(d, meta) +} + +func resourceComputeServiceAttachmentRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ServiceAttachment: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("ComputeServiceAttachment %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + + if err := d.Set("name", flattenComputeServiceAttachmentName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("description", flattenComputeServiceAttachmentDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("connection_preference", flattenComputeServiceAttachmentConnectionPreference(res["connectionPreference"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("connected_endpoints", flattenComputeServiceAttachmentConnectedEndpoints(res["connectedEndpoints"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("target_service", flattenComputeServiceAttachmentTargetService(res["targetService"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("nat_subnets", flattenComputeServiceAttachmentNatSubnets(res["natSubnets"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("enable_proxy_protocol", flattenComputeServiceAttachmentEnableProxyProtocol(res["enableProxyProtocol"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("consumer_reject_lists", flattenComputeServiceAttachmentConsumerRejectLists(res["consumerRejectLists"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("consumer_accept_lists", flattenComputeServiceAttachmentConsumerAcceptLists(res["consumerAcceptLists"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("region", flattenComputeServiceAttachmentRegion(res["region"], d, config)); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + if err := d.Set("self_link", ConvertSelfLinkToV1(res["selfLink"].(string))); err != nil { + return fmt.Errorf("Error reading ServiceAttachment: %s", err) + } + + return nil +} + +func resourceComputeServiceAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ServiceAttachment: %s", err) + } + billingProject = project + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting ServiceAttachment %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "ServiceAttachment") + } + + err = computeOperationWaitTime( + config, res, project, "Deleting ServiceAttachment", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting ServiceAttachment %q: %#v", d.Id(), res) + return nil +} + +func resourceComputeServiceAttachmentImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/regions/(?P[^/]+)/serviceAttachments/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenComputeServiceAttachmentName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConnectionPreference(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConnectedEndpoints(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + l := v.([]interface{}) + transformed := make([]interface{}, 0, len(l)) + for _, raw := range l { + original := raw.(map[string]interface{}) + if len(original) < 1 { + // Do not include empty json objects coming back from the api + continue + } + transformed = append(transformed, map[string]interface{}{ + "endpoint": flattenComputeServiceAttachmentConnectedEndpointsEndpoint(original["endpoint"], d, config), + "status": flattenComputeServiceAttachmentConnectedEndpointsStatus(original["status"], d, config), + }) + } + return transformed +} +func flattenComputeServiceAttachmentConnectedEndpointsEndpoint(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConnectedEndpointsStatus(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentTargetService(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + return ConvertSelfLinkToV1(v.(string)) +} + +func flattenComputeServiceAttachmentNatSubnets(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + return convertAndMapStringArr(v.([]interface{}), ConvertSelfLinkToV1) +} + +func flattenComputeServiceAttachmentEnableProxyProtocol(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConsumerRejectLists(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConsumerAcceptLists(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + l := v.([]interface{}) + transformed := make([]interface{}, 0, len(l)) + for _, raw := range l { + original := raw.(map[string]interface{}) + if len(original) < 1 { + // Do not include empty json objects coming back from the api + continue + } + transformed = append(transformed, map[string]interface{}{ + "project_id_or_num": flattenComputeServiceAttachmentConsumerAcceptListsProjectIdOrNum(original["projectIdOrNum"], d, config), + "connection_limit": flattenComputeServiceAttachmentConsumerAcceptListsConnectionLimit(original["connectionLimit"], d, config), + }) + } + return transformed +} +func flattenComputeServiceAttachmentConsumerAcceptListsProjectIdOrNum(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeServiceAttachmentConsumerAcceptListsConnectionLimit(v interface{}, d *schema.ResourceData, config *Config) interface{} { + // Handles the string fixed64 format + if strVal, ok := v.(string); ok { + if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil { + return intVal + } + } + + // number values are represented as float64 + if floatVal, ok := v.(float64); ok { + intVal := int(floatVal) + return intVal + } + + return v // let terraform core handle it otherwise +} + +func flattenComputeServiceAttachmentRegion(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + return ConvertSelfLinkToV1(v.(string)) +} + +func expandComputeServiceAttachmentName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentConnectionPreference(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentTargetService(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + f, err := parseRegionalFieldValue("forwardingRules", v.(string), "project", "region", "zone", d, config, true) + if err != nil { + return nil, fmt.Errorf("Invalid value for target_service: %s", err) + } + return f.RelativeLink(), nil +} + +func expandComputeServiceAttachmentNatSubnets(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + l := v.([]interface{}) + req := make([]interface{}, 0, len(l)) + for _, raw := range l { + if raw == nil { + return nil, fmt.Errorf("Invalid value for nat_subnets: nil") + } + f, err := parseRegionalFieldValue("subnetworks", raw.(string), "project", "region", "zone", d, config, true) + if err != nil { + return nil, fmt.Errorf("Invalid value for nat_subnets: %s", err) + } + req = append(req, f.RelativeLink()) + } + return req, nil +} + +func expandComputeServiceAttachmentEnableProxyProtocol(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentConsumerRejectLists(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentConsumerAcceptLists(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + l := v.([]interface{}) + req := make([]interface{}, 0, len(l)) + for _, raw := range l { + if raw == nil { + continue + } + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedProjectIdOrNum, err := expandComputeServiceAttachmentConsumerAcceptListsProjectIdOrNum(original["project_id_or_num"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedProjectIdOrNum); val.IsValid() && !isEmptyValue(val) { + transformed["projectIdOrNum"] = transformedProjectIdOrNum + } + + transformedConnectionLimit, err := expandComputeServiceAttachmentConsumerAcceptListsConnectionLimit(original["connection_limit"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedConnectionLimit); val.IsValid() && !isEmptyValue(val) { + transformed["connectionLimit"] = transformedConnectionLimit + } + + req = append(req, transformed) + } + return req, nil +} + +func expandComputeServiceAttachmentConsumerAcceptListsProjectIdOrNum(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentConsumerAcceptListsConnectionLimit(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeServiceAttachmentRegion(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + f, err := parseGlobalFieldValue("regions", v.(string), "project", d, config, true) + if err != nil { + return nil, fmt.Errorf("Invalid value for region: %s", err) + } + return f.RelativeLink(), nil +} diff --git a/google-beta/resource_compute_service_attachment_generated_test.go b/google-beta/resource_compute_service_attachment_generated_test.go new file mode 100644 index 0000000000..70193dd80a --- /dev/null +++ b/google-beta/resource_compute_service_attachment_generated_test.go @@ -0,0 +1,306 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccComputeServiceAttachment_serviceAttachmentBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + CheckDestroy: testAccCheckComputeServiceAttachmentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeServiceAttachment_serviceAttachmentBasicExample(context), + }, + }, + }) +} + +func testAccComputeServiceAttachment_serviceAttachmentBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_service_attachment" "psc_ilb_service_attachment" { + provider = "google-beta" + + name = "tf-test-my-psc-ilb%{random_suffix}" + region = "us-west2" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_AUTOMATIC" + nat_subnets = [google_compute_subnetwork.psc_ilb_nat.id] + target_service = google_compute_forwarding_rule.psc_ilb_target_service.id +} + +resource "google_compute_address" "psc_ilb_consumer_address" { + provider = "google-beta" + + name = "tf-test-psc-ilb-consumer-address%{random_suffix}" + region = "us-west2" + + subnetwork = "default" + address_type = "INTERNAL" + address = "10.168.0.17" +} + +resource "google_compute_forwarding_rule" "psc_ilb_consumer" { + provider = "google-beta" + + name = "tf-test-psc-ilb-consumer-forwarding-rule%{random_suffix}" + region = "us-west2" + + target = google_compute_service_attachment.psc_ilb_service_attachment.id + load_balancing_scheme = "" # need to override EXTERNAL default when target is a service attachment + network = "default" + ip_address = google_compute_address.psc_ilb_consumer_address.id +} + +resource "google_compute_forwarding_rule" "psc_ilb_target_service" { + provider = "google-beta" + + name = "tf-test-producer-forwarding-rule%{random_suffix}" + region = "us-west2" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.psc_ilb_network.name + subnetwork = google_compute_subnetwork.psc_ilb_producer_subnetwork.name +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + provider = "google-beta" + + name = "tf-test-producer-service%{random_suffix}" + region = "us-west2" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_health_check" "producer_service_health_check" { + provider = "google-beta" + + name = "tf-test-producer-service-health-check%{random_suffix}" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} + +resource "google_compute_network" "psc_ilb_network" { + provider = "google-beta" + + name = "tf-test-psc-ilb-network%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "psc_ilb_producer_subnetwork" { + provider = "google-beta" + + name = "tf-test-psc-ilb-producer-subnetwork%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + ip_cidr_range = "10.0.0.0/16" +} + +resource "google_compute_subnetwork" "psc_ilb_nat" { + provider = "google-beta" + + name = "tf-test-psc-ilb-nat%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + purpose = "PRIVATE_SERVICE_CONNECT" + ip_cidr_range = "10.1.0.0/16" +} +`, context) +} + +func TestAccComputeServiceAttachment_serviceAttachmentExplicitProjectsExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + CheckDestroy: testAccCheckComputeServiceAttachmentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeServiceAttachment_serviceAttachmentExplicitProjectsExample(context), + }, + }, + }) +} + +func testAccComputeServiceAttachment_serviceAttachmentExplicitProjectsExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_service_attachment" "psc_ilb_service_attachment" { + provider = "google-beta" + + name = "tf-test-my-psc-ilb%{random_suffix}" + region = "us-west2" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_MANUAL" + nat_subnets = [google_compute_subnetwork.psc_ilb_nat.id] + target_service = google_compute_forwarding_rule.psc_ilb_target_service.id + + consumer_reject_lists = ["673497134629", "482878270665"] + + consumer_accept_lists { + project_id_or_num = "658859330310" + connection_limit = 4 + } +} + +resource "google_compute_address" "psc_ilb_consumer_address" { + provider = "google-beta" + + name = "tf-test-psc-ilb-consumer-address%{random_suffix}" + region = "us-west2" + + subnetwork = "default" + address_type = "INTERNAL" + address = "10.168.1.17" +} + +resource "google_compute_forwarding_rule" "psc_ilb_consumer" { + provider = "google-beta" + + name = "tf-test-psc-ilb-consumer-forwarding-rule%{random_suffix}" + region = "us-west2" + + target = google_compute_service_attachment.psc_ilb_service_attachment.id + load_balancing_scheme = "" # need to override EXTERNAL default when target is a service attachment + network = "default" + ip_address = google_compute_address.psc_ilb_consumer_address.id +} + +resource "google_compute_forwarding_rule" "psc_ilb_target_service" { + provider = "google-beta" + + name = "tf-test-producer-forwarding-rule%{random_suffix}" + region = "us-west2" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.psc_ilb_network.name + subnetwork = google_compute_subnetwork.psc_ilb_producer_subnetwork.name +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + provider = "google-beta" + + name = "tf-test-producer-service%{random_suffix}" + region = "us-west2" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_health_check" "producer_service_health_check" { + provider = "google-beta" + + name = "tf-test-producer-service-health-check%{random_suffix}" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} + +resource "google_compute_network" "psc_ilb_network" { + provider = "google-beta" + + name = "tf-test-psc-ilb-network%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "psc_ilb_producer_subnetwork" { + provider = "google-beta" + + name = "tf-test-psc-ilb-producer-subnetwork%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + ip_cidr_range = "10.0.0.0/16" +} + +resource "google_compute_subnetwork" "psc_ilb_nat" { + provider = "google-beta" + + name = "tf-test-psc-ilb-nat%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + purpose = "PRIVATE_SERVICE_CONNECT" + ip_cidr_range = "10.1.0.0/16" +} +`, context) +} + +func testAccCheckComputeServiceAttachmentDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_compute_service_attachment" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("ComputeServiceAttachment still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/resource_compute_service_attachment_sweeper_test.go b/google-beta/resource_compute_service_attachment_sweeper_test.go new file mode 100644 index 0000000000..bc73e4eb95 --- /dev/null +++ b/google-beta/resource_compute_service_attachment_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("ComputeServiceAttachment", &resource.Sweeper{ + Name: "ComputeServiceAttachment", + F: testSweepComputeServiceAttachment, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepComputeServiceAttachment(region string) error { + resourceName := "ComputeServiceAttachment" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sharedConfigForRegion(region) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) + return err + } + + err = config.LoadAndValidate(context.Background()) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) + return err + } + + t := &testing.T{} + billingId := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://compute.googleapis.com/compute/beta/projects/{{project}}/regions/{{region}}/serviceAttachments", "?")[0] + listUrl, err := replaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := sendRequest(config, "GET", config.Project, listUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["serviceAttachments"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // Keep count of items that aren't sweepable for logging. + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + if obj["name"] == nil { + log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) + return nil + } + + name := GetResourceNameFromSelfLink(obj["name"].(string)) + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://compute.googleapis.com/compute/beta/projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}" + deleteUrl, err := replaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/website/docs/r/compute_service_attachment.html.markdown b/website/docs/r/compute_service_attachment.html.markdown new file mode 100644 index 0000000000..18eba3b6fd --- /dev/null +++ b/website/docs/r/compute_service_attachment.html.markdown @@ -0,0 +1,374 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Compute Engine" +layout: "google" +page_title: "Google: google_compute_service_attachment" +sidebar_current: "docs-google-compute-service-attachment" +description: |- + Represents a ServiceAttachment resource. +--- + +# google\_compute\_service\_attachment + +Represents a ServiceAttachment resource. + +~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources. + +To get more information about ServiceAttachment, see: + +* [API documentation](https://cloud.google.com/compute/docs/reference/beta/serviceAttachments) +* How-to Guides + * [Configuring Private Service Connect to access services](https://cloud.google.com/vpc/docs/configure-private-service-connect-services) + + +## Example Usage - Service Attachment Basic + + +```hcl +resource "google_compute_service_attachment" "psc_ilb_service_attachment" { + provider = "google-beta" + + name = "my-psc-ilb" + region = "us-west2" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_AUTOMATIC" + nat_subnets = [google_compute_subnetwork.psc_ilb_nat.id] + target_service = google_compute_forwarding_rule.psc_ilb_target_service.id +} + +resource "google_compute_address" "psc_ilb_consumer_address" { + provider = "google-beta" + + name = "psc-ilb-consumer-address" + region = "us-west2" + + subnetwork = "default" + address_type = "INTERNAL" + address = "10.168.0.17" +} + +resource "google_compute_forwarding_rule" "psc_ilb_consumer" { + provider = "google-beta" + + name = "psc-ilb-consumer-forwarding-rule" + region = "us-west2" + + target = google_compute_service_attachment.psc_ilb_service_attachment.id + load_balancing_scheme = "" # need to override EXTERNAL default when target is a service attachment + network = "default" + ip_address = google_compute_address.psc_ilb_consumer_address.id +} + +resource "google_compute_forwarding_rule" "psc_ilb_target_service" { + provider = "google-beta" + + name = "producer-forwarding-rule" + region = "us-west2" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.psc_ilb_network.name + subnetwork = google_compute_subnetwork.psc_ilb_producer_subnetwork.name +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + provider = "google-beta" + + name = "producer-service" + region = "us-west2" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_health_check" "producer_service_health_check" { + provider = "google-beta" + + name = "producer-service-health-check" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} + +resource "google_compute_network" "psc_ilb_network" { + provider = "google-beta" + + name = "psc-ilb-network" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "psc_ilb_producer_subnetwork" { + provider = "google-beta" + + name = "psc-ilb-producer-subnetwork" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + ip_cidr_range = "10.0.0.0/16" +} + +resource "google_compute_subnetwork" "psc_ilb_nat" { + provider = "google-beta" + + name = "psc-ilb-nat" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + purpose = "PRIVATE_SERVICE_CONNECT" + ip_cidr_range = "10.1.0.0/16" +} +``` + +## Example Usage - Service Attachment Explicit Projects + + +```hcl +resource "google_compute_service_attachment" "psc_ilb_service_attachment" { + provider = "google-beta" + + name = "my-psc-ilb" + region = "us-west2" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_MANUAL" + nat_subnets = [google_compute_subnetwork.psc_ilb_nat.id] + target_service = google_compute_forwarding_rule.psc_ilb_target_service.id + + consumer_reject_lists = ["673497134629", "482878270665"] + + consumer_accept_lists { + project_id_or_num = "658859330310" + connection_limit = 4 + } +} + +resource "google_compute_address" "psc_ilb_consumer_address" { + provider = "google-beta" + + name = "psc-ilb-consumer-address" + region = "us-west2" + + subnetwork = "default" + address_type = "INTERNAL" + address = "10.168.1.17" +} + +resource "google_compute_forwarding_rule" "psc_ilb_consumer" { + provider = "google-beta" + + name = "psc-ilb-consumer-forwarding-rule" + region = "us-west2" + + target = google_compute_service_attachment.psc_ilb_service_attachment.id + load_balancing_scheme = "" # need to override EXTERNAL default when target is a service attachment + network = "default" + ip_address = google_compute_address.psc_ilb_consumer_address.id +} + +resource "google_compute_forwarding_rule" "psc_ilb_target_service" { + provider = "google-beta" + + name = "producer-forwarding-rule" + region = "us-west2" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.psc_ilb_network.name + subnetwork = google_compute_subnetwork.psc_ilb_producer_subnetwork.name +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + provider = "google-beta" + + name = "producer-service" + region = "us-west2" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_health_check" "producer_service_health_check" { + provider = "google-beta" + + name = "producer-service-health-check" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} + +resource "google_compute_network" "psc_ilb_network" { + provider = "google-beta" + + name = "psc-ilb-network" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "psc_ilb_producer_subnetwork" { + provider = "google-beta" + + name = "psc-ilb-producer-subnetwork" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + ip_cidr_range = "10.0.0.0/16" +} + +resource "google_compute_subnetwork" "psc_ilb_nat" { + provider = "google-beta" + + name = "psc-ilb-nat" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + purpose = "PRIVATE_SERVICE_CONNECT" + ip_cidr_range = "10.1.0.0/16" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + Name of the resource. The name must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 characters + long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` + which means the first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + +* `connection_preference` - + (Required) + The connection preference to use for this service attachment. Valid + values include "ACCEPT_AUTOMATIC", "ACCEPT_MANUAL". + +* `target_service` - + (Required) + The URL of a forwarding rule that represents the service identified by + this service attachment. + +* `nat_subnets` - + (Required) + An array of subnets that is provided for NAT in this service attachment. + +* `enable_proxy_protocol` - + (Required) + If true, enable the proxy protocol which is for supplying client TCP/IP + address data in TCP connections that traverse proxies on their way to + destination servers. + + +- - - + + +* `description` - + (Optional) + An optional description of this resource. + +* `consumer_reject_lists` - + (Optional) + An array of projects that are not allowed to connect to this service + attachment. + +* `consumer_accept_lists` - + (Optional) + An array of projects that are allowed to connect to this service + attachment. + Structure is documented below. + +* `region` - + (Optional) + URL of the region where the resource resides. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +The `consumer_accept_lists` block supports: + +* `project_id_or_num` - + (Required) + A project that is allowed to connect to this service attachment. + +* `connection_limit` - + (Required) + The number of consumer forwarding rules the consumer project can + create. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}}` + +* `connected_endpoints` - + An array of the consumer forwarding rules connected to this service + attachment. + Structure is documented below. +* `self_link` - The URI of the created resource. + + +The `connected_endpoints` block contains: + +* `endpoint` - + The URL of the consumer forwarding rule. + +* `status` - + The status of the connection from the consumer forwarding rule to + this service attachment. + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + + +ServiceAttachment can be imported using any of these accepted formats: + +``` +$ terraform import google_compute_service_attachment.default projects/{{project}}/regions/{{region}}/serviceAttachments/{{name}} +$ terraform import google_compute_service_attachment.default {{project}}/{{region}}/{{name}} +$ terraform import google_compute_service_attachment.default {{region}}/{{name}} +$ terraform import google_compute_service_attachment.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/google.erb b/website/google.erb index 92be8f9a55..26065f05c6 100644 --- a/website/google.erb +++ b/website/google.erb @@ -1938,6 +1938,10 @@ google_compute_security_policy +
  • + google_compute_service_attachment +
  • +
  • google_compute_shared_vpc_host_project