From 69364fa9d4271e681918cf8a20a8b50c07eac062 Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Mon, 12 Sep 2022 12:46:00 +0000 Subject: [PATCH] feat: apigee NAT address resource (#6475) * feat: apigee NAT address resource * fix: matching example file name for Apigee NAT Address * Apigee NAT address add test for naming Signed-off-by: Modular Magician --- .changelog/6475.txt | 3 + google/provider.go | 5 +- google/resource_apigee_instance.go | 2 +- google/resource_apigee_nat_address.go | 249 ++++++++++++++++++ ...ource_apigee_nat_address_generated_test.go | 154 +++++++++++ website/docs/r/apigee_instance.html.markdown | 2 +- .../docs/r/apigee_nat_address.html.markdown | 163 ++++++++++++ 7 files changed, 574 insertions(+), 4 deletions(-) create mode 100644 .changelog/6475.txt create mode 100644 google/resource_apigee_nat_address.go create mode 100644 google/resource_apigee_nat_address_generated_test.go create mode 100644 website/docs/r/apigee_nat_address.html.markdown diff --git a/.changelog/6475.txt b/.changelog/6475.txt new file mode 100644 index 00000000000..b1d39f6a66c --- /dev/null +++ b/.changelog/6475.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +Apigee: Added Apigee NAT address resource `google_apigee_nat_address` +``` diff --git a/google/provider.go b/google/provider.go index 4836688ba81..98e8f92b07b 100644 --- a/google/provider.go +++ b/google/provider.go @@ -888,9 +888,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 232 +// Generated resources: 233 // Generated IAM resources: 138 -// Total generated resources: 370 +// Total generated resources: 371 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -925,6 +925,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_apigee_instance_attachment": resourceApigeeInstanceAttachment(), "google_apigee_envgroup_attachment": resourceApigeeEnvgroupAttachment(), "google_apigee_endpoint_attachment": resourceApigeeEndpointAttachment(), + "google_apigee_nat_address": resourceApigeeNatAddress(), "google_app_engine_domain_mapping": resourceAppEngineDomainMapping(), "google_app_engine_firewall_rule": resourceAppEngineFirewallRule(), "google_app_engine_standard_app_version": resourceAppEngineStandardAppVersion(), diff --git a/google/resource_apigee_instance.go b/google/resource_apigee_instance.go index c7966e0433d..45558f53de9 100644 --- a/google/resource_apigee_instance.go +++ b/google/resource_apigee_instance.go @@ -108,7 +108,7 @@ Input format: "a.b.c.d/22"`, Computed: true, Optional: true, ForceNew: true, - Description: `The size of the CIDR block range that will be reserved by the instance. For valid values, + Description: `The size of the CIDR block range that will be reserved by the instance. For valid values, see [CidrRange](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.instances#CidrRange) on the documentation.`, }, "host": { diff --git a/google/resource_apigee_nat_address.go b/google/resource_apigee_nat_address.go new file mode 100644 index 00000000000..de09e5d4fd9 --- /dev/null +++ b/google/resource_apigee_nat_address.go @@ -0,0 +1,249 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceApigeeNatAddress() *schema.Resource { + return &schema.Resource{ + Create: resourceApigeeNatAddressCreate, + Read: resourceApigeeNatAddressRead, + Delete: resourceApigeeNatAddressDelete, + + Importer: &schema.ResourceImporter{ + State: resourceApigeeNatAddressImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The Apigee instance associated with the Apigee environment, +in the format 'organizations/{{org_name}}/instances/{{instance_name}}'.`, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Resource ID of the NAT address.`, + }, + "ip_address": { + Type: schema.TypeString, + Computed: true, + Description: `The allocated NAT IP address.`, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Description: `State of the NAT IP address.`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceApigeeNatAddressCreate(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{}) + nameProp, err := expandApigeeNatAddressName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp + } + + url, err := replaceVars(d, config, "{{ApigeeBasePath}}{{instance_id}}/natAddresses") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new NatAddress: %#v", obj) + billingProject := "" + + // 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 NatAddress: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + // Use the resource in the operation response to populate + // identity fields and d.Id() before read + var opRes map[string]interface{} + err = apigeeOperationWaitTimeWithResponse( + config, res, &opRes, "Creating NatAddress", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create NatAddress: %s", err) + } + + if err := d.Set("name", flattenApigeeNatAddressName(opRes["name"], d, config)); err != nil { + return err + } + + // This may have caused the ID to update - update it if so. + id, err = replaceVars(d, config, "{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating NatAddress %q: %#v", d.Id(), res) + + return resourceApigeeNatAddressRead(d, meta) +} + +func resourceApigeeNatAddressRead(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, "{{ApigeeBasePath}}{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + // 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("ApigeeNatAddress %q", d.Id())) + } + + if err := d.Set("name", flattenApigeeNatAddressName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading NatAddress: %s", err) + } + if err := d.Set("ip_address", flattenApigeeNatAddressIpAddress(res["ipAddress"], d, config)); err != nil { + return fmt.Errorf("Error reading NatAddress: %s", err) + } + if err := d.Set("state", flattenApigeeNatAddressState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading NatAddress: %s", err) + } + + return nil +} + +func resourceApigeeNatAddressDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + url, err := replaceVars(d, config, "{{ApigeeBasePath}}{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting NatAddress %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, "NatAddress") + } + + err = apigeeOperationWaitTime( + config, res, "Deleting NatAddress", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting NatAddress %q: %#v", d.Id(), res) + return nil +} + +func resourceApigeeNatAddressImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + + // current import_formats cannot import fields with forward slashes in their value + if err := parseImportId([]string{ + "(?P.+)/natAddresses/(?P.+)", + "(?P.+)/(?P.+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenApigeeNatAddressName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeNatAddressIpAddress(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeNatAddressState(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandApigeeNatAddressName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} diff --git a/google/resource_apigee_nat_address_generated_test.go b/google/resource_apigee_nat_address_generated_test.go new file mode 100644 index 00000000000..18ccc371f5e --- /dev/null +++ b/google/resource_apigee_nat_address_generated_test.go @@ -0,0 +1,154 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccApigeeNatAddress_apigeeNatAddressBasicTestExample(t *testing.T) { + skipIfVcr(t) + t.Parallel() + + context := map[string]interface{}{ + "org_id": getTestOrgFromEnv(t), + "billing_account": getTestBillingAccountFromEnv(t), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckApigeeNatAddressDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccApigeeNatAddress_apigeeNatAddressBasicTestExample(context), + }, + { + ResourceName: "google_apigee_nat_address.apigee_nat_address", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"instance_id"}, + }, + }, + }) +} + +func testAccApigeeNatAddress_apigeeNatAddressBasicTestExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_project" "project" { + project_id = "tf-test%{random_suffix}" + name = "tf-test%{random_suffix}" + org_id = "%{org_id}" + billing_account = "%{billing_account}" +} + +resource "google_project_service" "apigee" { + project = google_project.project.project_id + service = "apigee.googleapis.com" +} + +resource "google_project_service" "compute" { + project = google_project.project.project_id + service = "compute.googleapis.com" +} + +resource "google_project_service" "servicenetworking" { + project = google_project.project.project_id + service = "servicenetworking.googleapis.com" +} + +resource "google_compute_network" "apigee_network" { + name = "apigee-network" + project = google_project.project.project_id + depends_on = [google_project_service.compute] +} + +resource "google_compute_global_address" "apigee_range" { + name = "apigee-range" + purpose = "VPC_PEERING" + address_type = "INTERNAL" + prefix_length = 21 + network = google_compute_network.apigee_network.id + project = google_project.project.project_id +} + +resource "google_service_networking_connection" "apigee_vpc_connection" { + network = google_compute_network.apigee_network.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.apigee_range.name] + depends_on = [google_project_service.servicenetworking] +} + +resource "google_apigee_organization" "apigee_org" { + analytics_region = "us-central1" + project_id = google_project.project.project_id + authorized_network = google_compute_network.apigee_network.id + depends_on = [ + google_service_networking_connection.apigee_vpc_connection, + google_project_service.apigee, + ] +} + +resource "google_apigee_instance" "apigee_instance" { + name = "apigee-instance" + location = "us-central1" + org_id = google_apigee_organization.apigee_org.id +} + +resource "google_apigee_nat_address" "apigee_nat_address" { + name = "tf-test%{random_suffix}" + instance_id = google_apigee_instance.apigee_instance.id +} +`, context) +} + +func testAccCheckApigeeNatAddressDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_apigee_nat_address" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{ApigeeBasePath}}{{instance_id}}/natAddresses/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("ApigeeNatAddress still exists at %s", url) + } + } + + return nil + } +} diff --git a/website/docs/r/apigee_instance.html.markdown b/website/docs/r/apigee_instance.html.markdown index 47929d57249..f63b2ae72a8 100644 --- a/website/docs/r/apigee_instance.html.markdown +++ b/website/docs/r/apigee_instance.html.markdown @@ -243,7 +243,7 @@ The following arguments are supported: * `peering_cidr_range` - (Optional) - The size of the CIDR block range that will be reserved by the instance. For valid values, + The size of the CIDR block range that will be reserved by the instance. For valid values, see [CidrRange](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.instances#CidrRange) on the documentation. * `ip_range` - diff --git a/website/docs/r/apigee_nat_address.html.markdown b/website/docs/r/apigee_nat_address.html.markdown new file mode 100644 index 00000000000..6e7e401b75d --- /dev/null +++ b/website/docs/r/apigee_nat_address.html.markdown @@ -0,0 +1,163 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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. +# +# ---------------------------------------------------------------------------- +subcategory: "Apigee" +page_title: "Google: google_apigee_nat_address" +description: |- + Apigee NAT (network address translation) address. +--- + +# google\_apigee\_nat\_address + +Apigee NAT (network address translation) address. A NAT address is a static external IP address used for Internet egress traffic. This is not avaible for Apigee hybrid. +Apigee NAT addresses are not automatically activated because they might require explicit allow entries on the target systems first. See https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.instances.natAddresses/activate + + +To get more information about NatAddress, see: + +* [API documentation](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.instances.natAddresses) +* How-to Guides + * [Provisioning NAT IPs](https://cloud.google.com/apigee/docs/api-platform/security/nat-provisioning) + +## Example Usage - Apigee Nat Address Basic + + +```hcl +data "google_client_config" "current" {} + +resource "google_compute_network" "apigee_network" { + name = "apigee-network" +} + +resource "google_compute_global_address" "apigee_range" { + name = "apigee-range" + purpose = "VPC_PEERING" + address_type = "INTERNAL" + prefix_length = 21 + network = google_compute_network.apigee_network.id +} + +resource "google_service_networking_connection" "apigee_vpc_connection" { + network = google_compute_network.apigee_network.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.apigee_range.name] +} + +resource "google_kms_key_ring" "apigee_keyring" { + name = "apigee-keyring" + location = "us-central1" +} + +resource "google_kms_crypto_key" "apigee_key" { + name = "apigee-key" + key_ring = google_kms_key_ring.apigee_keyring.id + + lifecycle { + prevent_destroy = true + } +} + +resource "google_project_service_identity" "apigee_sa" { + provider = google-beta + project = google_project.project.project_id + service = google_project_service.apigee.service +} + +resource "google_kms_crypto_key_iam_binding" "apigee_sa_keyuser" { + crypto_key_id = google_kms_crypto_key.apigee_key.id + role = "roles/cloudkms.cryptoKeyEncrypterDecrypter" + + members = [ + "serviceAccount:${google_project_service_identity.apigee_sa.email}", + ] +} + +resource "google_apigee_organization" "apigee_org" { + analytics_region = "us-central1" + display_name = "apigee-org" + description = "Terraform-provisioned Apigee Org." + project_id = data.google_client_config.current.project + authorized_network = google_compute_network.apigee_network.id + runtime_database_encryption_key_name = google_kms_crypto_key.apigee_key.id + + depends_on = [ + google_service_networking_connection.apigee_vpc_connection, + google_kms_crypto_key_iam_binding.apigee_sa_keyuser, + ] +} + +resource "google_apigee_instance" "apigee_instance" { + name = "apigee-instance" + location = "us-central1" + description = "Terraform-managed Apigee Runtime Instance" + display_name = "apigee-instance" + org_id = google_apigee_organization.apigee_org.id + disk_encryption_key_name = google_kms_crypto_key.apigee_key.id +} + +resource "google_apigee_nat_address" "apigee-nat" { + name = "tf-test%{random_suffix}" + instance_id = google_apigee_instance.apigee_instance.id +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + Resource ID of the NAT address. + +* `instance_id` - + (Required) + The Apigee instance associated with the Apigee environment, + in the format `organizations/{{org_name}}/instances/{{instance_name}}`. + + +- - - + + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{instance_id}}/natAddresses/{{name}}` + +* `ip_address` - + The allocated NAT IP address. + +* `state` - + State of the NAT IP address. + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 30 minutes. +- `delete` - Default is 30 minutes. + +## Import + + +NatAddress can be imported using any of these accepted formats: + +``` +$ terraform import google_apigee_nat_address.default {{instance_id}}/natAddresses/{{name}} +$ terraform import google_apigee_nat_address.default {{instance_id}}/{{name}} +```