Skip to content

Commit

Permalink
Add Pub/Sub Lite reservation support to terraform. (#5284) (#10263)
Browse files Browse the repository at this point in the history
* Add Pub/Sub Lite reservation support to terraform.

Also fix doc links for Pub/Sub Lite.

* Add Pub/Sub Lite reservation support to terraform.

Also fix doc links for Pub/Sub Lite.

* Add Pub/Sub Lite reservation support to terraform.

Also fix doc links for Pub/Sub Lite.

* Add Pub/Sub Lite reservation support to terraform.

Also fix doc links for Pub/Sub Lite.

* Update to expander to use 'locations' instead of 'regions'.

Co-authored-by: Nathan Mckinley <[email protected]>
Signed-off-by: Modular Magician <[email protected]>

Co-authored-by: Nathan Mckinley <[email protected]>
  • Loading branch information
modular-magician and nat-henderson authored Oct 6, 2021
1 parent 46db67f commit 2bd0903
Show file tree
Hide file tree
Showing 11 changed files with 762 additions and 6 deletions.
6 changes: 6 additions & 0 deletions .changelog/5284.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```release-note:new-resource
`google_pubsub_lite_reservation`
```
```release-note:enhancement
pubsub: Added support for references to `google_pubsub_lite_reservation` to `google_pubsub_lite_topic`.
```
5 changes: 3 additions & 2 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -814,9 +814,9 @@ func Provider() *schema.Provider {
return provider
}

// Generated resources: 213
// Generated resources: 214
// Generated IAM resources: 90
// Total generated resources: 303
// Total generated resources: 304
func ResourceMap() map[string]*schema.Resource {
resourceMap, _ := ResourceMapWithErrors()
return resourceMap
Expand Down Expand Up @@ -1083,6 +1083,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
"google_pubsub_topic_iam_policy": ResourceIamPolicy(PubsubTopicIamSchema, PubsubTopicIamUpdaterProducer, PubsubTopicIdParseFunc),
"google_pubsub_subscription": resourcePubsubSubscription(),
"google_pubsub_schema": resourcePubsubSchema(),
"google_pubsub_lite_reservation": resourcePubsubLiteReservation(),
"google_pubsub_lite_topic": resourcePubsubLiteTopic(),
"google_pubsub_lite_subscription": resourcePubsubLiteSubscription(),
"google_redis_instance": resourceRedisInstance(),
Expand Down
302 changes: 302 additions & 0 deletions google/resource_pubsub_lite_reservation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// 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"
"strings"
"time"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourcePubsubLiteReservation() *schema.Resource {
return &schema.Resource{
Create: resourcePubsubLiteReservationCreate,
Read: resourcePubsubLiteReservationRead,
Update: resourcePubsubLiteReservationUpdate,
Delete: resourcePubsubLiteReservationDelete,

Importer: &schema.ResourceImporter{
State: resourcePubsubLiteReservationImport,
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Description: `Name of the reservation.`,
},
"throughput_capacity": {
Type: schema.TypeInt,
Required: true,
Description: `The reserved throughput capacity. Every unit of throughput capacity is
equivalent to 1 MiB/s of published messages or 2 MiB/s of subscribed
messages.`,
},
"region": {
Type: schema.TypeString,
Optional: true,
Description: `The region of the pubsub lite reservation.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}

func resourcePubsubLiteReservationCreate(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{})
throughputCapacityProp, err := expandPubsubLiteReservationThroughputCapacity(d.Get("throughput_capacity"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("throughput_capacity"); !isEmptyValue(reflect.ValueOf(throughputCapacityProp)) && (ok || !reflect.DeepEqual(v, throughputCapacityProp)) {
obj["throughputCapacity"] = throughputCapacityProp
}

url, err := replaceVars(d, config, "{{PubsubLiteBasePath}}projects/{{project}}/locations/{{region}}/reservations?reservationId={{name}}")
if err != nil {
return err
}

log.Printf("[DEBUG] Creating new Reservation: %#v", obj)
billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Reservation: %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 Reservation: %s", err)
}

// Store the ID now
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{region}}/reservations/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

log.Printf("[DEBUG] Finished creating Reservation %q: %#v", d.Id(), res)

return resourcePubsubLiteReservationRead(d, meta)
}

func resourcePubsubLiteReservationRead(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, "{{PubsubLiteBasePath}}projects/{{project}}/locations/{{region}}/reservations/{{name}}")
if err != nil {
return err
}

billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Reservation: %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("PubsubLiteReservation %q", d.Id()))
}

if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Reservation: %s", err)
}

if err := d.Set("throughput_capacity", flattenPubsubLiteReservationThroughputCapacity(res["throughputCapacity"], d, config)); err != nil {
return fmt.Errorf("Error reading Reservation: %s", err)
}

return nil
}

func resourcePubsubLiteReservationUpdate(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 Reservation: %s", err)
}
billingProject = project

obj := make(map[string]interface{})
throughputCapacityProp, err := expandPubsubLiteReservationThroughputCapacity(d.Get("throughput_capacity"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("throughput_capacity"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, throughputCapacityProp)) {
obj["throughputCapacity"] = throughputCapacityProp
}

url, err := replaceVars(d, config, "{{PubsubLiteBasePath}}projects/{{project}}/locations/{{region}}/reservations/{{name}}")
if err != nil {
return err
}

log.Printf("[DEBUG] Updating Reservation %q: %#v", d.Id(), obj)
updateMask := []string{}

if d.HasChange("throughput_capacity") {
updateMask = append(updateMask, "throughputCapacity")
}
// updateMask is a URL parameter but not present in the schema, so replaceVars
// won't set it
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
if err != nil {
return err
}

// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}

res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))

if err != nil {
return fmt.Errorf("Error updating Reservation %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating Reservation %q: %#v", d.Id(), res)
}

return resourcePubsubLiteReservationRead(d, meta)
}

func resourcePubsubLiteReservationDelete(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 Reservation: %s", err)
}
billingProject = project

url, err := replaceVars(d, config, "{{PubsubLiteBasePath}}projects/{{project}}/locations/{{region}}/reservations/{{name}}")
if err != nil {
return err
}

var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Reservation %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, "Reservation")
}

log.Printf("[DEBUG] Finished deleting Reservation %q: %#v", d.Id(), res)
return nil
}

func resourcePubsubLiteReservationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"projects/(?P<project>[^/]+)/locations/(?P<region>[^/]+)/reservations/(?P<name>[^/]+)",
"(?P<project>[^/]+)/(?P<region>[^/]+)/(?P<name>[^/]+)",
"(?P<region>[^/]+)/(?P<name>[^/]+)",
"(?P<name>[^/]+)",
}, d, config); err != nil {
return nil, err
}

// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{region}}/reservations/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

return []*schema.ResourceData{d}, nil
}

func flattenPubsubLiteReservationThroughputCapacity(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 expandPubsubLiteReservationThroughputCapacity(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
Loading

0 comments on commit 2bd0903

Please sign in to comment.