Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Appengine's firewall rules. #271

Merged
merged 1 commit into from
Jan 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion google-beta/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package google
import (
"fmt"
"regexp"
"strconv"
"strings"
)

Expand All @@ -25,7 +26,35 @@ func parseImportId(idRegexes []string, d TerraformResourceData, config *Config)
// Starting at index 1, the first match is the full string.
for i := 1; i < len(fieldValues); i++ {
fieldName := re.SubexpNames()[i]
d.Set(fieldName, fieldValues[i])
fieldValue := fieldValues[i]
// Because we do not know at this point whether 'fieldName'
// corresponds to a TypeString or a TypeInteger in the resource
// schema, we need to determine the type in an unintutitive way.
// We call d.Get, because examining the empty value is the easiest
// way to get that out. Normally, we would be able to just
// use a try/catch pattern - try as a string, and if that doesn't
// work, try as an integer, and if that doesn't work, return the
// error. Unfortunately, this is not possible here - during tests,
// d.Set(...) will panic if there is an error.
val, _ := d.GetOk(fieldName)
if _, ok := val.(string); val == nil || ok {
if err = d.Set(fieldName, fieldValue); err != nil {
return err
}
} else if _, ok := val.(int); ok {
if intVal, atoiErr := strconv.Atoi(fieldValue); atoiErr == nil {
// If the value can be parsed as an integer, we try to set the
// value as an integer.
if err = d.Set(fieldName, intVal); err != nil {
return err
}
} else {
return fmt.Errorf("%s appears to be an integer, but %v cannot be parsed as an int", fieldName, fieldValue)
}
} else {
return fmt.Errorf(
"cannot handle %s, which currently has value %v, and should be set to %#v, during import", fieldName, val, fieldValue)
}
}

// The first id format is applied first and contains all the fields.
Expand Down
1 change: 1 addition & 0 deletions google-beta/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
GeneratedFilestoreResourcesMap,
GeneratedAccessContextManagerResourcesMap,
// end beta-only products
GeneratedAppengineResourcesMap,
GeneratedComputeResourcesMap,
GeneratedDnsResourcesMap,
GeneratedRedisResourcesMap,
Expand Down
21 changes: 21 additions & 0 deletions google-beta/provider_appengine_gen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// ----------------------------------------------------------------------------
//
// *** 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 "github.com/hashicorp/terraform/helper/schema"

var GeneratedAppengineResourcesMap = map[string]*schema.Resource{
"google_appengine_firewall_rule": resourceAppengineFirewallRule(),
}
301 changes: 301 additions & 0 deletions google-beta/resource_appengine_firewall_rule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
// ----------------------------------------------------------------------------
//
// *** 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"
"strings"
"time"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)

func resourceAppengineFirewallRule() *schema.Resource {
return &schema.Resource{
Create: resourceAppengineFirewallRuleCreate,
Read: resourceAppengineFirewallRuleRead,
Update: resourceAppengineFirewallRuleUpdate,
Delete: resourceAppengineFirewallRuleDelete,

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

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{
"action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"UNSPECIFIED_ACTION", "ALLOW", "DENY"}, false),
},
"source_range": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}

func resourceAppengineFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

obj := make(map[string]interface{})
descriptionProp, err := expandAppengineFirewallRuleDescription(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
}
sourceRangeProp, err := expandAppengineFirewallRuleSourceRange(d.Get("source_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("source_range"); !isEmptyValue(reflect.ValueOf(sourceRangeProp)) && (ok || !reflect.DeepEqual(v, sourceRangeProp)) {
obj["sourceRange"] = sourceRangeProp
}
actionProp, err := expandAppengineFirewallRuleAction(d.Get("action"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("action"); !isEmptyValue(reflect.ValueOf(actionProp)) && (ok || !reflect.DeepEqual(v, actionProp)) {
obj["action"] = actionProp
}
priorityProp, err := expandAppengineFirewallRulePriority(d.Get("priority"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("priority"); !isEmptyValue(reflect.ValueOf(priorityProp)) && (ok || !reflect.DeepEqual(v, priorityProp)) {
obj["priority"] = priorityProp
}

url, err := replaceVars(d, config, "https://appengine.googleapis.com/v1/apps/{{project}}/firewall/ingressRules")
if err != nil {
return err
}

log.Printf("[DEBUG] Creating new FirewallRule: %#v", obj)
res, err := sendRequestWithTimeout(config, "POST", url, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating FirewallRule: %s", err)
}

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

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

return resourceAppengineFirewallRuleRead(d, meta)
}

func resourceAppengineFirewallRuleRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

url, err := replaceVars(d, config, "https://appengine.googleapis.com/v1/apps/{{project}}/firewall/ingressRules/{{priority}}")
if err != nil {
return err
}

res, err := sendRequest(config, "GET", url, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("AppengineFirewallRule %q", d.Id()))
}

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

if err := d.Set("description", flattenAppengineFirewallRuleDescription(res["description"], d)); err != nil {
return fmt.Errorf("Error reading FirewallRule: %s", err)
}
if err := d.Set("source_range", flattenAppengineFirewallRuleSourceRange(res["sourceRange"], d)); err != nil {
return fmt.Errorf("Error reading FirewallRule: %s", err)
}
if err := d.Set("action", flattenAppengineFirewallRuleAction(res["action"], d)); err != nil {
return fmt.Errorf("Error reading FirewallRule: %s", err)
}
if err := d.Set("priority", flattenAppengineFirewallRulePriority(res["priority"], d)); err != nil {
return fmt.Errorf("Error reading FirewallRule: %s", err)
}

return nil
}

func resourceAppengineFirewallRuleUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

obj := make(map[string]interface{})
descriptionProp, err := expandAppengineFirewallRuleDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
sourceRangeProp, err := expandAppengineFirewallRuleSourceRange(d.Get("source_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("source_range"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, sourceRangeProp)) {
obj["sourceRange"] = sourceRangeProp
}
actionProp, err := expandAppengineFirewallRuleAction(d.Get("action"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("action"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, actionProp)) {
obj["action"] = actionProp
}
priorityProp, err := expandAppengineFirewallRulePriority(d.Get("priority"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("priority"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, priorityProp)) {
obj["priority"] = priorityProp
}

url, err := replaceVars(d, config, "https://appengine.googleapis.com/v1/apps/{{project}}/firewall/ingressRules/{{priority}}")
if err != nil {
return err
}

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

if d.HasChange("description") {
updateMask = append(updateMask, "description")
}

if d.HasChange("source_range") {
updateMask = append(updateMask, "sourceRange")
}

if d.HasChange("action") {
updateMask = append(updateMask, "action")
}

if d.HasChange("priority") {
updateMask = append(updateMask, "priority")
}
// 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 = sendRequestWithTimeout(config, "PATCH", url, obj, d.Timeout(schema.TimeoutUpdate))

if err != nil {
return fmt.Errorf("Error updating FirewallRule %q: %s", d.Id(), err)
}

return resourceAppengineFirewallRuleRead(d, meta)
}

func resourceAppengineFirewallRuleDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

url, err := replaceVars(d, config, "https://appengine.googleapis.com/v1/apps/{{project}}/firewall/ingressRules/{{priority}}")
if err != nil {
return err
}

var obj map[string]interface{}
log.Printf("[DEBUG] Deleting FirewallRule %q", d.Id())
res, err := sendRequestWithTimeout(config, "DELETE", url, obj, d.Timeout(schema.TimeoutDelete))
if err != nil {
return handleNotFoundError(err, d, "FirewallRule")
}

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

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

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

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

func flattenAppengineFirewallRuleDescription(v interface{}, d *schema.ResourceData) interface{} {
return v
}

func flattenAppengineFirewallRuleSourceRange(v interface{}, d *schema.ResourceData) interface{} {
return v
}

func flattenAppengineFirewallRuleAction(v interface{}, d *schema.ResourceData) interface{} {
return v
}

func flattenAppengineFirewallRulePriority(v interface{}, d *schema.ResourceData) 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 expandAppengineFirewallRuleDescription(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}

func expandAppengineFirewallRuleSourceRange(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}

func expandAppengineFirewallRuleAction(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}

func expandAppengineFirewallRulePriority(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil
}
Loading