Generate google_target_tcp_proxy using Magic Module (#1406)

This commit is contained in:
The Magician 2018-05-01 15:04:56 -07:00 committed by Vincent Roseberry
parent ba7c9f706c
commit 7eac32ab1f
3 changed files with 356 additions and 106 deletions

View File

@ -23,5 +23,6 @@ var GeneratedComputeResourcesMap = map[string]*schema.Resource{
"google_compute_https_health_check": resourceComputeHttpsHealthCheck(), "google_compute_https_health_check": resourceComputeHttpsHealthCheck(),
"google_compute_target_http_proxy": resourceComputeTargetHttpProxy(), "google_compute_target_http_proxy": resourceComputeTargetHttpProxy(),
"google_compute_target_ssl_proxy": resourceComputeTargetSslProxy(), "google_compute_target_ssl_proxy": resourceComputeTargetSslProxy(),
"google_compute_target_tcp_proxy": resourceComputeTargetTcpProxy(),
"google_compute_vpn_gateway": resourceComputeVpnGateway(), "google_compute_vpn_gateway": resourceComputeVpnGateway(),
} }

View File

@ -1,62 +1,84 @@
// ----------------------------------------------------------------------------
//
// *** 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 package google
import ( import (
"fmt" "fmt"
"log" "log"
"strconv" "strconv"
"time"
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/compute/v1" "github.com/hashicorp/terraform/helper/validation"
compute "google.golang.org/api/compute/v1"
) )
func resourceComputeTargetTcpProxy() *schema.Resource { func resourceComputeTargetTcpProxy() *schema.Resource {
return &schema.Resource{ return &schema.Resource{
Create: resourceComputeTargetTcpProxyCreate, Create: resourceComputeTargetTcpProxyCreate,
Read: resourceComputeTargetTcpProxyRead, Read: resourceComputeTargetTcpProxyRead,
Delete: resourceComputeTargetTcpProxyDelete,
Update: resourceComputeTargetTcpProxyUpdate, Update: resourceComputeTargetTcpProxyUpdate,
Delete: resourceComputeTargetTcpProxyDelete,
Importer: &schema.ResourceImporter{ Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough, State: resourceComputeTargetTcpProxyImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(240 * time.Second),
Update: schema.DefaultTimeout(240 * time.Second),
Delete: schema.DefaultTimeout(240 * time.Second),
}, },
Schema: map[string]*schema.Schema{ Schema: map[string]*schema.Schema{
"name": &schema.Schema{ "backend_service": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
"name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"description": {
"backend_service": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"proxy_header": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Optional: true, Optional: true,
ForceNew: true,
},
"proxy_header": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NONE", "PROXY_V1", ""}, false),
Default: "NONE", Default: "NONE",
}, },
"creation_timestamp": {
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"proxy_id": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Computed: true, Computed: true,
}, },
"proxy_id": {
"project": &schema.Schema{ Type: schema.TypeInt,
Computed: true,
},
"project": {
Type: schema.TypeString, Type: schema.TypeString,
Optional: true, Optional: true,
Computed: true, Computed: true,
ForceNew: true, ForceNew: true,
}, },
"self_link": {
"self_link": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Computed: true, Computed: true,
}, },
@ -72,61 +94,64 @@ func resourceComputeTargetTcpProxyCreate(d *schema.ResourceData, meta interface{
return err return err
} }
proxy := &compute.TargetTcpProxy{ descriptionProp, err := expandComputeTargetTcpProxyDescription(d.Get("description"), d, config)
Name: d.Get("name").(string), if err != nil {
Service: d.Get("backend_service").(string), return err
ProxyHeader: d.Get("proxy_header").(string), }
Description: d.Get("description").(string), nameProp, err := expandComputeTargetTcpProxyName(d.Get("name"), d, config)
if err != nil {
return err
}
proxyHeaderProp, err := expandComputeTargetTcpProxyProxyHeader(d.Get("proxy_header"), d, config)
if err != nil {
return err
}
serviceProp, err := expandComputeTargetTcpProxyBackendService(d.Get("backend_service"), d, config)
if err != nil {
return err
} }
log.Printf("[DEBUG] TargetTcpProxy insert request: %#v", proxy) obj := map[string]interface{}{
op, err := config.clientCompute.TargetTcpProxies.Insert( "description": descriptionProp,
project, proxy).Do() "name": nameProp,
"proxyHeader": proxyHeaderProp,
"service": serviceProp,
}
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new TargetTcpProxy: %#v", obj)
res, err := Post(config, url, obj)
if err != nil { if err != nil {
return fmt.Errorf("Error creating TargetTcpProxy: %s", err) return fmt.Errorf("Error creating TargetTcpProxy: %s", err)
} }
err = computeOperationWait(config.clientCompute, op, project, "Creating Target Tcp Proxy") // Store the ID now
id, err := replaceVars(d, config, "{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
op := &compute.Operation{}
err = Convert(res, op)
if err != nil { if err != nil {
return err return err
} }
d.SetId(proxy.Name) waitErr := computeOperationWaitTime(
config.clientCompute, op, project, "Creating TargetTcpProxy",
int(d.Timeout(schema.TimeoutCreate).Minutes()))
return resourceComputeTargetTcpProxyRead(d, meta) if waitErr != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create TargetTcpProxy: %s", waitErr)
} }
func resourceComputeTargetTcpProxyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
d.Partial(true)
if d.HasChange("proxy_header") {
proxy_header := d.Get("proxy_header").(string)
proxy_header_payload := &compute.TargetTcpProxiesSetProxyHeaderRequest{
ProxyHeader: proxy_header,
}
op, err := config.clientCompute.TargetTcpProxies.SetProxyHeader(
project, d.Id(), proxy_header_payload).Do()
if err != nil {
return fmt.Errorf("Error updating target: %s", err)
}
err = computeOperationWait(config.clientCompute, op, project, "Updating Target Tcp Proxy")
if err != nil {
return err
}
d.SetPartial("proxy_header")
}
d.Partial(false)
return resourceComputeTargetTcpProxyRead(d, meta) return resourceComputeTargetTcpProxyRead(d, meta)
} }
@ -138,23 +163,129 @@ func resourceComputeTargetTcpProxyRead(d *schema.ResourceData, meta interface{})
return err return err
} }
proxy, err := config.clientCompute.TargetTcpProxies.Get( url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}")
project, d.Id()).Do()
if err != nil { if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Target TCP Proxy %q", d.Get("name").(string))) return err
} }
d.Set("name", proxy.Name) res, err := Get(config, url)
d.Set("backend_service", proxy.Service) if err != nil {
d.Set("proxy_header", proxy.ProxyHeader) return handleNotFoundError(err, d, fmt.Sprintf("ComputeTargetTcpProxy %q", d.Id()))
d.Set("description", proxy.Description) }
d.Set("project", project) if err := d.Set("creation_timestamp", flattenComputeTargetTcpProxyCreationTimestamp(res["creationTimestamp"])); err != nil {
d.Set("self_link", proxy.SelfLink) return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
d.Set("proxy_id", strconv.FormatUint(proxy.Id, 10)) }
if err := d.Set("description", flattenComputeTargetTcpProxyDescription(res["description"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("proxy_id", flattenComputeTargetTcpProxyProxyId(res["id"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("name", flattenComputeTargetTcpProxyName(res["name"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("proxy_header", flattenComputeTargetTcpProxyProxyHeader(res["proxyHeader"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("backend_service", flattenComputeTargetTcpProxyBackendService(res["service"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("self_link", res["selfLink"]); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
return nil return nil
} }
func resourceComputeTargetTcpProxyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
var url string
var res map[string]interface{}
op := &compute.Operation{}
d.Partial(true)
if d.HasChange("proxy_header") {
proxyHeaderProp, err := expandComputeTargetTcpProxyProxyHeader(d.Get("proxy_header"), d, config)
if err != nil {
return err
}
obj := map[string]interface{}{
"proxyHeader": proxyHeaderProp,
}
url, err = replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}/setProxyHeader")
if err != nil {
return err
}
res, err = sendRequest(config, "POST", url, obj)
if err != nil {
return fmt.Errorf("Error updating TargetTcpProxy %q: %s", d.Id(), err)
}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Updating TargetTcpProxy",
int(d.Timeout(schema.TimeoutUpdate).Minutes()))
if err != nil {
return err
}
d.SetPartial("proxy_header")
}
if d.HasChange("backend_service") {
serviceProp, err := expandComputeTargetTcpProxyBackendService(d.Get("backend_service"), d, config)
if err != nil {
return err
}
obj := map[string]interface{}{
"service": serviceProp,
}
url, err = replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}/setBackendService")
if err != nil {
return err
}
res, err = sendRequest(config, "POST", url, obj)
if err != nil {
return fmt.Errorf("Error updating TargetTcpProxy %q: %s", d.Id(), err)
}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Updating TargetTcpProxy",
int(d.Timeout(schema.TimeoutUpdate).Minutes()))
if err != nil {
return err
}
d.SetPartial("backend_service")
}
d.Partial(false)
return resourceComputeTargetTcpProxyRead(d, meta)
}
func resourceComputeTargetTcpProxyDelete(d *schema.ResourceData, meta interface{}) error { func resourceComputeTargetTcpProxyDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config) config := meta.(*Config)
@ -163,19 +294,94 @@ func resourceComputeTargetTcpProxyDelete(d *schema.ResourceData, meta interface{
return err return err
} }
// Delete the TargetTcpProxy url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}")
log.Printf("[DEBUG] TargetTcpProxy delete request") if err != nil {
op, err := config.clientCompute.TargetTcpProxies.Delete( return err
project, d.Id()).Do() }
if err != nil {
return fmt.Errorf("Error deleting TargetTcpProxy: %s", err) log.Printf("[DEBUG] Deleting TargetTcpProxy %q", d.Id())
} res, err := Delete(config, url)
if err != nil {
err = computeOperationWait(config.clientCompute, op, project, "Deleting Target Tcp Proxy") return fmt.Errorf("Error deleting TargetTcpProxy %q: %s", d.Id(), err)
}
op := &compute.Operation{}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Deleting TargetTcpProxy",
int(d.Timeout(schema.TimeoutDelete).Minutes()))
if err != nil { if err != nil {
return err return err
} }
d.SetId("")
return nil return nil
} }
func resourceComputeTargetTcpProxyImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
parseImportId([]string{"projects/(?P<project>[^/]+)/global/targetTcpProxies/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config)
// Replace import id for the resource id
id, err := replaceVars(d, config, "{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenComputeTargetTcpProxyCreationTimestamp(v interface{}) interface{} {
return v
}
func flattenComputeTargetTcpProxyDescription(v interface{}) interface{} {
return v
}
func flattenComputeTargetTcpProxyProxyId(v interface{}) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.Atoi(strVal); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenComputeTargetTcpProxyName(v interface{}) interface{} {
return v
}
func flattenComputeTargetTcpProxyProxyHeader(v interface{}) interface{} {
return v
}
func flattenComputeTargetTcpProxyBackendService(v interface{}) interface{} {
return v
}
func expandComputeTargetTcpProxyDescription(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandComputeTargetTcpProxyName(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandComputeTargetTcpProxyProxyHeader(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandComputeTargetTcpProxyBackendService(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
f, err := parseGlobalFieldValue("backendServices", v.(string), "project", d, config, true)
if err != nil {
return nil, fmt.Errorf("Invalid value for backend_service: %s", err)
}
return f.RelativeLink(), nil
}

View File

@ -1,18 +1,37 @@
--- ---
# ----------------------------------------------------------------------------
#
# *** 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.
#
# ----------------------------------------------------------------------------
layout: "google" layout: "google"
page_title: "Google: google_compute_target_tcp_proxy" page_title: "Google: google_compute_target_tcp_proxy"
sidebar_current: "docs-google-compute-target-tcp-proxy" sidebar_current: "docs-google-compute-target-tcp-proxy"
description: |- description: |-
Creates a Target TCP Proxy resource in GCE. Represents a TargetTcpProxy resource, which is used by one or more
global forwarding rule to route incoming TCP requests to a Backend
service.
--- ---
# google\_compute\_target\_tcp\_proxy # google\_compute\_target\_tcp\_proxy
Creates a target TCP proxy resource in GCE. For more information see Represents a TargetTcpProxy resource, which is used by one or more
[the official global forwarding rule to route incoming TCP requests to a Backend
documentation](https://cloud.google.com/compute/docs/load-balancing/tcp-ssl/tcp-proxy) and service.
[API](https://cloud.google.com/compute/docs/reference/latest/targetTcpProxies).
To get more information about TargetTcpProxy, see:
* [API documentation](https://cloud.google.com/compute/docs/reference/latest/targetTcpProxies)
* How-to Guides
* [Setting Up TCP proxy for Google Cloud Load Balancing](https://cloud.google.com/compute/docs/load-balancing/tcp-ssl/tcp-proxy)
## Example Usage ## Example Usage
@ -46,35 +65,59 @@ resource "google_compute_health_check" "default" {
The following arguments are supported: The following arguments are supported:
* `name` - (Required) A unique name for the resource, required by GCE. Changing * `name` -
this forces a new resource to be created. (Required)
Name of the resource. Provided by the client when the resource is
created. 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.
* `backend_service` -
(Required)
A reference to BackendService resource
* `backend_service` - (Required) The URL of a Backend Service resource to receive the matched traffic.
- - - - - -
* `proxy_header` - (Optional) Type of proxy header to append before sending * `description` -
data to the backend, either NONE or PROXY_V1 (default NONE). (Optional)
An optional description of this resource.
* `proxy_header` -
(Optional)
Specifies the type of proxy header to append before sending data to
the backend, either NONE or PROXY_V1. The default is NONE.
* `project` (Optional) The ID of the project in which the resource belongs.
If it is not provided, the provider project is used.
* `description` - (Optional) A description of this resource. Changing this
forces a new resource to be created.
* `project` - (Optional) The ID of the project in which the resource belongs. If it
is not provided, the provider project is used.
## Attributes Reference ## Attributes Reference
In addition to the arguments listed above, the following computed attributes are In addition to the arguments listed above, the following computed attributes are exported:
exported:
* `proxy_id` - A unique ID assigned by GCE.
* `creation_timestamp` -
Creation timestamp in RFC3339 text format.
* `proxy_id` -
The unique identifier for the resource.
* `self_link` - The URI of the created resource. * `self_link` - The URI of the created resource.
## Timeouts
This resource provides the following
[Timeouts](/docs/configuration/resources.html#timeouts) configuration options:
- `create` - Default is 4 minutes.
- `update` - Default is 4 minutes.
- `delete` - Default is 4 minutes.
## Import ## Import
TCP proxy can be imported using the `name`, e.g. TargetTcpProxy can be imported using any of these accepted formats:
``` ```
$ terraform import google_compute_target_tcp_proxy.default test $ terraform import google_compute_target_tcp_proxy.default projects/{{project}}/global/targetTcpProxies/{{name}}
$ terraform import google_compute_target_tcp_proxy.default {{project}}/{{name}}
$ terraform import google_compute_target_tcp_proxy.default {{name}}
``` ```