Redis resource (#1485)

<!-- This change is generated by MagicModules. -->
/cc @danawillow
This commit is contained in:
The Magician 2018-05-23 11:25:48 -07:00 committed by Dana Hoffman
parent cac3502bac
commit 488b9e86f3
6 changed files with 838 additions and 8 deletions

View File

@ -16,4 +16,6 @@ package google
import "github.com/hashicorp/terraform/helper/schema"
var GeneratedRedisResourcesMap = map[string]*schema.Resource{}
var GeneratedRedisResourcesMap = map[string]*schema.Resource{
"google_redis_instance": resourceRedisInstance(),
}

64
google/redis_operation.go Normal file
View File

@ -0,0 +1,64 @@
package google
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/resource"
"google.golang.org/api/redis/v1beta1"
)
type RedisOperationWaiter struct {
Service *redis.ProjectsLocationsService
Op *redis.Operation
}
func (w *RedisOperationWaiter) RefreshFunc() resource.StateRefreshFunc {
return func() (interface{}, string, error) {
op, err := w.Service.Operations.Get(w.Op.Name).Do()
if err != nil {
return nil, "", err
}
log.Printf("[DEBUG] Got %v while polling for operation %s's 'done' status", op.Done, w.Op.Name)
return op, fmt.Sprint(op.Done), nil
}
}
func (w *RedisOperationWaiter) Conf() *resource.StateChangeConf {
return &resource.StateChangeConf{
Pending: []string{"false"},
Target: []string{"true"},
Refresh: w.RefreshFunc(),
}
}
func redisOperationWait(service *redis.Service, op *redis.Operation, project, activity string) error {
return redisOperationWaitTime(service, op, project, activity, 4)
}
func redisOperationWaitTime(service *redis.Service, op *redis.Operation, project, activity string, timeoutMin int) error {
w := &RedisOperationWaiter{
Service: service.Projects.Locations,
Op: op,
}
state := w.Conf()
state.Delay = 10 * time.Second
state.Timeout = time.Duration(timeoutMin) * time.Minute
state.MinTimeout = 2 * time.Second
opRaw, err := state.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for %s: %s", activity, err)
}
op = opRaw.(*redis.Operation)
if op.Error != nil {
return fmt.Errorf("Error code %v, message: %s", op.Error.Code, op.Error.Message)
}
return nil
}

View File

@ -0,0 +1,515 @@
// ----------------------------------------------------------------------------
//
// *** 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"
"github.com/hashicorp/terraform/helper/validation"
redis "google.golang.org/api/redis/v1beta1"
)
func resourceRedisInstance() *schema.Resource {
return &schema.Resource{
Create: resourceRedisInstanceCreate,
Read: resourceRedisInstanceRead,
Delete: resourceRedisInstanceDelete,
Importer: &schema.ResourceImporter{
State: resourceRedisInstanceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(360 * time.Second),
Delete: schema.DefaultTimeout(240 * time.Second),
},
Schema: map[string]*schema.Schema{
"memory_size_gb": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"alternative_location_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"authorized_network": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"location_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"redis_version": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"reserved_ip_range": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"tier": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"BASIC", "STANDARD_HA", ""}, false),
Default: "BASIC",
},
"region": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"current_location_id": {
Type: schema.TypeString,
Computed: true,
},
"host": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceRedisInstanceCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
alternativeLocationIdProp, err := expandRedisInstanceAlternativeLocationId(d.Get("alternative_location_id"), d, config)
if err != nil {
return err
}
authorizedNetworkProp, err := expandRedisInstanceAuthorizedNetwork(d.Get("authorized_network"), d, config)
if err != nil {
return err
}
displayNameProp, err := expandRedisInstanceDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
}
labelsProp, err := expandRedisInstanceLabels(d.Get("labels"), d, config)
if err != nil {
return err
}
locationIdProp, err := expandRedisInstanceLocationId(d.Get("location_id"), d, config)
if err != nil {
return err
}
nameProp, err := expandRedisInstanceName(d.Get("name"), d, config)
if err != nil {
return err
}
memorySizeGbProp, err := expandRedisInstanceMemorySizeGb(d.Get("memory_size_gb"), d, config)
if err != nil {
return err
}
redisVersionProp, err := expandRedisInstanceRedisVersion(d.Get("redis_version"), d, config)
if err != nil {
return err
}
reservedIpRangeProp, err := expandRedisInstanceReservedIpRange(d.Get("reserved_ip_range"), d, config)
if err != nil {
return err
}
tierProp, err := expandRedisInstanceTier(d.Get("tier"), d, config)
if err != nil {
return err
}
regionProp, err := expandRedisInstanceRegion(d.Get("region"), d, config)
if err != nil {
return err
}
obj := map[string]interface{}{
"alternativeLocationId": alternativeLocationIdProp,
"authorizedNetwork": authorizedNetworkProp,
"displayName": displayNameProp,
"labels": labelsProp,
"locationId": locationIdProp,
"name": nameProp,
"memorySizeGb": memorySizeGbProp,
"redisVersion": redisVersionProp,
"reservedIpRange": reservedIpRangeProp,
"tier": tierProp,
"region": regionProp,
}
obj, err = resourceRedisInstanceEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://redis.googleapis.com/v1beta1/projects/{{project}}/locations/{{region}}/instances?instanceId={{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Instance: %#v", obj)
res, err := Post(config, url, obj)
if err != nil {
return fmt.Errorf("Error creating Instance: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "{{project}}/{{region}}/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
op := &redis.Operation{}
err = Convert(res, op)
if err != nil {
return err
}
waitErr := redisOperationWaitTime(
config.clientRedis, op, project, "Creating Instance",
int(d.Timeout(schema.TimeoutCreate).Minutes()))
if waitErr != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Instance: %s", waitErr)
}
log.Printf("[DEBUG] Finished creating Instance %q: %#v", d.Id(), res)
return resourceRedisInstanceRead(d, meta)
}
func resourceRedisInstanceRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://redis.googleapis.com/v1beta1/projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {
return err
}
res, err := Get(config, url)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("RedisInstance %q", d.Id()))
}
res, err = resourceRedisInstanceDecoder(d, meta, res)
if err != nil {
return err
}
if err := d.Set("alternative_location_id", flattenRedisInstanceAlternativeLocationId(res["alternativeLocationId"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("authorized_network", flattenRedisInstanceAuthorizedNetwork(res["authorizedNetwork"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("create_time", flattenRedisInstanceCreateTime(res["createTime"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("current_location_id", flattenRedisInstanceCurrentLocationId(res["currentLocationId"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("display_name", flattenRedisInstanceDisplayName(res["displayName"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("host", flattenRedisInstanceHost(res["host"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("labels", flattenRedisInstanceLabels(res["labels"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("location_id", flattenRedisInstanceLocationId(res["locationId"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("name", flattenRedisInstanceName(res["name"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("memory_size_gb", flattenRedisInstanceMemorySizeGb(res["memorySizeGb"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("port", flattenRedisInstancePort(res["port"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("redis_version", flattenRedisInstanceRedisVersion(res["redisVersion"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("reserved_ip_range", flattenRedisInstanceReservedIpRange(res["reservedIpRange"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("tier", flattenRedisInstanceTier(res["tier"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("region", flattenRedisInstanceRegion(res["region"])); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
return nil
}
func resourceRedisInstanceDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://redis.googleapis.com/v1beta1/projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Deleting Instance %q", d.Id())
res, err := Delete(config, url)
if err != nil {
return fmt.Errorf("Error deleting Instance %q: %s", d.Id(), err)
}
op := &redis.Operation{}
err = Convert(res, op)
if err != nil {
return err
}
err = redisOperationWaitTime(
config.clientRedis, op, project, "Deleting Instance",
int(d.Timeout(schema.TimeoutDelete).Minutes()))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Instance %q: %#v", d.Id(), res)
return nil
}
func resourceRedisInstanceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
parseImportId([]string{"projects/(?P<project>[^/]+)/locations/(?P<region>[^/]+)/instances/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<region>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config)
// Replace import id for the resource id
id, err := replaceVars(d, config, "{{project}}/{{region}}/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenRedisInstanceAlternativeLocationId(v interface{}) interface{} {
return v
}
func flattenRedisInstanceAuthorizedNetwork(v interface{}) interface{} {
return v
}
func flattenRedisInstanceCreateTime(v interface{}) interface{} {
return v
}
func flattenRedisInstanceCurrentLocationId(v interface{}) interface{} {
return v
}
func flattenRedisInstanceDisplayName(v interface{}) interface{} {
return v
}
func flattenRedisInstanceHost(v interface{}) interface{} {
return v
}
func flattenRedisInstanceLabels(v interface{}) interface{} {
return v
}
func flattenRedisInstanceLocationId(v interface{}) interface{} {
return v
}
func flattenRedisInstanceName(v interface{}) interface{} {
return NameFromSelfLinkStateFunc(v)
}
func flattenRedisInstanceMemorySizeGb(v interface{}) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenRedisInstancePort(v interface{}) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenRedisInstanceRedisVersion(v interface{}) interface{} {
return v
}
func flattenRedisInstanceReservedIpRange(v interface{}) interface{} {
return v
}
func flattenRedisInstanceTier(v interface{}) interface{} {
return v
}
func flattenRedisInstanceRegion(v interface{}) interface{} {
return v
}
func expandRedisInstanceAlternativeLocationId(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceAuthorizedNetwork(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceDisplayName(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceLabels(v interface{}, d *schema.ResourceData, config *Config) (map[string]string, error) {
if v == nil {
return map[string]string{}, nil
}
m := make(map[string]string)
for k, val := range v.(map[string]interface{}) {
m[k] = val.(string)
}
return m, nil
}
func expandRedisInstanceLocationId(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceName(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
region, err := getRegion(d, config)
if err != nil {
return nil, err
}
return fmt.Sprintf("projects/%s/locations/%s/instances/%s", project, region, v.(string)), nil
}
func expandRedisInstanceMemorySizeGb(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceRedisVersion(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceReservedIpRange(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceTier(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandRedisInstanceRegion(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
func resourceRedisInstanceEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
delete(obj, "region")
return obj, nil
}
func resourceRedisInstanceDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) {
config := meta.(*Config)
region, err := getRegion(d, config)
if err != nil {
return nil, err
}
res["region"] = region
return res, nil
}

View File

@ -0,0 +1,88 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccRedisInstance_basic(t *testing.T) {
t.Parallel()
name := acctest.RandomWithPrefix("tf-test")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckComputeAddressDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccRedisInstance_basic(name),
},
resource.TestStep{
ResourceName: "google_redis_instance.test",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccRedisInstance_full(t *testing.T) {
t.Parallel()
name := acctest.RandomWithPrefix("tf-test")
network := acctest.RandomWithPrefix("tf-test")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckComputeAddressDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccRedisInstance_full(name, network),
},
resource.TestStep{
ResourceName: "google_redis_instance.test",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccRedisInstance_basic(name string) string {
return fmt.Sprintf(`
resource "google_redis_instance" "test" {
name = "%s"
memory_size_gb = 1
}`, name)
}
func testAccRedisInstance_full(name, network string) string {
return fmt.Sprintf(`
resource "google_compute_network" "test" {
name = "%s"
}
resource "google_redis_instance" "test" {
name = "%s"
tier = "STANDARD_HA"
memory_size_gb = 1
region = "us-central1"
location_id = "us-central1-a"
alternative_location_id = "us-central1-f"
redis_version = "REDIS_3_2"
display_name = "Terraform Test Instance"
reserved_ip_range = "192.168.0.0/29"
labels {
my_key = "my_val"
other_key = "other_val"
}
}`, name, network)
}

View File

@ -0,0 +1,168 @@
---
# ----------------------------------------------------------------------------
#
# *** 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_redis_instance"
sidebar_current: "docs-google-redis-instance"
description: |-
A Google Cloud Redis instance.
---
# google\_redis\_instance
A Google Cloud Redis instance.
To get more information about Instance, see:
* [API documentation](https://cloud.google.com/memorystore/docs/redis/reference/rest/)
* How-to Guides
* [Official Documentation](https://cloud.google.com/memorystore/docs/redis/)
## Example Usage
### Basic Usage
```hcl
resource "google_redis_instance" "test" {
name = "%s"
memory_size_gb = 1
}
```
### Full Usage
```hcl
resource "google_compute_network" "test" {
name = "%s"
}
resource "google_redis_instance" "test" {
name = "%s"
tier = "STANDARD_HA"
memory_size_gb = 1
region = "us-central1"
location_id = "us-central1-a"
alternative_location_id = "us-central1-f"
redis_version = "REDIS_3_2"
display_name = "Terraform Test Instance"
reserved_ip_range = "192.168.0.0/29"
labels {
my_key = "my_val"
other_key = "other_val"
}
}
```
## Argument Reference
The following arguments are supported:
* `name` -
(Required)
The ID of the instance or a fully qualified identifier for the instance.
* `memory_size_gb` -
(Required)
Redis memory size in GiB.
- - -
* `alternative_location_id` -
(Optional)
Only applicable to STANDARD_HA tier which protects the instance
against zonal failures by provisioning it across two zones.
If provided, it must be a different zone from the one provided in
[locationId].
* `authorized_network` -
(Optional)
The full name of the Google Compute Engine network to which the
instance is connected. If left unspecified, the default network
will be used.
* `display_name` -
(Optional)
An arbitrary and optional user-provided name for the instance.
* `labels` -
(Optional)
Resource labels to represent user provided metadata.
* `location_id` -
(Optional)
The zone where the instance will be provisioned. If not provided,
the service will choose a zone for the instance. For STANDARD_HA tier,
instances will be created across two zones for protection against
zonal failures. If [alternativeLocationId] is also provided, it must
be different from [locationId].
* `redis_version` -
(Optional)
The version of Redis software. If not provided, latest supported
version will be used. Updating the version will perform an
upgrade/downgrade to the new version. Currently, the supported values
are REDIS_3_2 for Redis 3.2.
* `reserved_ip_range` -
(Optional)
The CIDR range of internal addresses that are reserved for this
instance. If not provided, the service will choose an unused /29
block, for example, 10.0.0.0/29 or 192.168.0.0/29. Ranges must be
unique and non-overlapping with existing subnets in an authorized
network.
* `tier` -
(Optional)
The service tier of the instance. Must be one of these values:
- BASIC: standalone instance
- STANDARD_HA: highly available primary/replica instances
* `region` -
(Optional)
The name of the Redis region of the instance.
* `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:
* `create_time` -
The time the instance was created in RFC3339 UTC "Zulu" format,
accurate to nanoseconds.
* `current_location_id` -
The current zone where the Redis endpoint is placed.
For Basic Tier instances, this will always be the same as the
[locationId] provided by the user at creation time. For Standard Tier
instances, this can be either [locationId] or [alternativeLocationId]
and can change after a failover event.
* `host` -
Hostname or IP address of the exposed Redis endpoint used by clients
to connect to the service.
* `port` -
The port number of the exposed Redis endpoint.
## Timeouts
This resource provides the following
[Timeouts](/docs/configuration/resources.html#timeouts) configuration options:
- `create` - Default is 6 minutes.
- `delete` - Default is 4 minutes.
## Import
Instance can be imported using any of these accepted formats:
```
$ terraform import google_redis_instance.default projects/{{project}}/locations/{{region}}/instances/{{name}}
$ terraform import google_redis_instance.default {{project}}/{{region}}/{{name}}
$ terraform import google_redis_instance.default {{name}}
```

View File

@ -86,13 +86,6 @@ In addition to the arguments listed above, the following computed attributes are
Time of creation
## 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