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_target_http_proxy": resourceComputeTargetHttpProxy(),
"google_compute_target_ssl_proxy": resourceComputeTargetSslProxy(),
"google_compute_target_tcp_proxy": resourceComputeTargetTcpProxy(),
"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
import (
"fmt"
"log"
"strconv"
"time"
"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 {
return &schema.Resource{
Create: resourceComputeTargetTcpProxyCreate,
Read: resourceComputeTargetTcpProxyRead,
Delete: resourceComputeTargetTcpProxyDelete,
Update: resourceComputeTargetTcpProxyUpdate,
Delete: resourceComputeTargetTcpProxyDelete,
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{
"name": &schema.Schema{
"backend_service": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"backend_service": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"proxy_header": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "NONE",
},
"description": &schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"proxy_id": &schema.Schema{
"proxy_header": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NONE", "PROXY_V1", ""}, false),
Default: "NONE",
},
"creation_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"project": &schema.Schema{
"proxy_id": {
Type: schema.TypeInt,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"self_link": &schema.Schema{
"self_link": {
Type: schema.TypeString,
Computed: true,
},
@ -72,61 +94,64 @@ func resourceComputeTargetTcpProxyCreate(d *schema.ResourceData, meta interface{
return err
}
proxy := &compute.TargetTcpProxy{
Name: d.Get("name").(string),
Service: d.Get("backend_service").(string),
ProxyHeader: d.Get("proxy_header").(string),
Description: d.Get("description").(string),
descriptionProp, err := expandComputeTargetTcpProxyDescription(d.Get("description"), d, config)
if err != nil {
return err
}
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)
op, err := config.clientCompute.TargetTcpProxies.Insert(
project, proxy).Do()
obj := map[string]interface{}{
"description": descriptionProp,
"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 {
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 {
return err
}
d.SetId(proxy.Name)
waitErr := computeOperationWaitTime(
config.clientCompute, op, project, "Creating TargetTcpProxy",
int(d.Timeout(schema.TimeoutCreate).Minutes()))
return resourceComputeTargetTcpProxyRead(d, meta)
}
func resourceComputeTargetTcpProxyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
if waitErr != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create TargetTcpProxy: %s", waitErr)
}
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)
}
@ -138,23 +163,129 @@ func resourceComputeTargetTcpProxyRead(d *schema.ResourceData, meta interface{})
return err
}
proxy, err := config.clientCompute.TargetTcpProxies.Get(
project, d.Id()).Do()
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}")
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Target TCP Proxy %q", d.Get("name").(string)))
return err
}
d.Set("name", proxy.Name)
d.Set("backend_service", proxy.Service)
d.Set("proxy_header", proxy.ProxyHeader)
d.Set("description", proxy.Description)
d.Set("project", project)
d.Set("self_link", proxy.SelfLink)
d.Set("proxy_id", strconv.FormatUint(proxy.Id, 10))
res, err := Get(config, url)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("ComputeTargetTcpProxy %q", d.Id()))
}
if err := d.Set("creation_timestamp", flattenComputeTargetTcpProxyCreationTimestamp(res["creationTimestamp"])); err != nil {
return fmt.Errorf("Error reading TargetTcpProxy: %s", err)
}
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
}
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 {
config := meta.(*Config)
@ -163,19 +294,94 @@ func resourceComputeTargetTcpProxyDelete(d *schema.ResourceData, meta interface{
return err
}
// Delete the TargetTcpProxy
log.Printf("[DEBUG] TargetTcpProxy delete request")
op, err := config.clientCompute.TargetTcpProxies.Delete(
project, d.Id()).Do()
if err != nil {
return fmt.Errorf("Error deleting TargetTcpProxy: %s", err)
}
err = computeOperationWait(config.clientCompute, op, project, "Deleting Target Tcp Proxy")
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/global/targetTcpProxies/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Deleting TargetTcpProxy %q", d.Id())
res, err := Delete(config, url)
if err != nil {
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 {
return err
}
d.SetId("")
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"
page_title: "Google: google_compute_target_tcp_proxy"
sidebar_current: "docs-google-compute-target-tcp-proxy"
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
Creates a target TCP proxy resource in GCE. For more information see
[the official
documentation](https://cloud.google.com/compute/docs/load-balancing/tcp-ssl/tcp-proxy) and
[API](https://cloud.google.com/compute/docs/reference/latest/targetTcpProxies).
Represents a TargetTcpProxy resource, which is used by one or more
global forwarding rule to route incoming TCP requests to a Backend
service.
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
@ -46,35 +65,59 @@ resource "google_compute_health_check" "default" {
The following arguments are supported:
* `name` - (Required) A unique name for the resource, required by GCE. Changing
this forces a new resource to be created.
* `name` -
(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
data to the backend, either NONE or PROXY_V1 (default NONE).
* `description` -
(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
In addition to the arguments listed above, the following computed attributes are
exported:
* `proxy_id` - A unique ID assigned by GCE.
In addition to the arguments listed above, the following computed attributes are exported:
* `creation_timestamp` -
Creation timestamp in RFC3339 text format.
* `proxy_id` -
The unique identifier for the 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
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}}
```