diff --git a/.changelog/4317.txt b/.changelog/4317.txt new file mode 100644 index 00000000000..6a7212a39ad --- /dev/null +++ b/.changelog/4317.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +apigee_organization +``` diff --git a/google/apigee_operation.go b/google/apigee_operation.go new file mode 100644 index 00000000000..c20a7cc0817 --- /dev/null +++ b/google/apigee_operation.go @@ -0,0 +1,76 @@ +// ---------------------------------------------------------------------------- +// +// *** 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 ( + "encoding/json" + "fmt" + "time" +) + +type ApigeeOperationWaiter struct { + Config *Config + UserAgent string + CommonOperationWaiter +} + +func (w *ApigeeOperationWaiter) QueryOp() (interface{}, error) { + if w == nil { + return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") + } + // Returns the proper get. + url := fmt.Sprintf("https://apigee.googleapis.com/v1/%s", w.CommonOperationWaiter.Op.Name) + + return sendRequest(w.Config, "GET", "", url, w.UserAgent, nil) +} + +func createApigeeWaiter(config *Config, op map[string]interface{}, activity, userAgent string) (*ApigeeOperationWaiter, error) { + if val, ok := op["name"]; !ok || val == "" { + // An operation could also be indicated with a "metadata" field. + if _, ok := op["metadata"]; !ok { + // This was a synchronous call - there is no operation to wait for. + return nil, nil + } + } + w := &ApigeeOperationWaiter{ + Config: config, + UserAgent: userAgent, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +// nolint: deadcode,unused +func apigeeOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, activity, userAgent string, timeout time.Duration) error { + w, err := createApigeeWaiter(config, op, activity, userAgent) + if err != nil || w == nil { + // If w is nil, the op was synchronous. + return err + } + if err := OperationWait(w, activity, timeout, config.PollInterval); err != nil { + return err + } + return json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response) +} + +func apigeeOperationWaitTime(config *Config, op map[string]interface{}, activity, userAgent string, timeout time.Duration) error { + w, err := createApigeeWaiter(config, op, activity, userAgent) + if err != nil || w == nil { + // If w is nil, the op was synchronous. + return err + } + return OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/google/config.go b/google/config.go index 28fc4f796f6..6d77ccf9865 100644 --- a/google/config.go +++ b/google/config.go @@ -86,6 +86,7 @@ type Config struct { AccessApprovalBasePath string AccessContextManagerBasePath string ActiveDirectoryBasePath string + ApigeeBasePath string AppEngineBasePath string BigQueryBasePath string BigqueryDataTransferBasePath string @@ -164,6 +165,7 @@ type Config struct { var AccessApprovalDefaultBasePath = "https://accessapproval.googleapis.com/v1/" var AccessContextManagerDefaultBasePath = "https://accesscontextmanager.googleapis.com/v1/" var ActiveDirectoryDefaultBasePath = "https://managedidentities.googleapis.com/v1/" +var ApigeeDefaultBasePath = "https://apigee.googleapis.com/v1/" var AppEngineDefaultBasePath = "https://appengine.googleapis.com/v1/" var BigQueryDefaultBasePath = "https://bigquery.googleapis.com/bigquery/v2/" var BigqueryDataTransferDefaultBasePath = "https://bigquerydatatransfer.googleapis.com/v1/" @@ -952,6 +954,7 @@ func ConfigureBasePaths(c *Config) { c.AccessApprovalBasePath = AccessApprovalDefaultBasePath c.AccessContextManagerBasePath = AccessContextManagerDefaultBasePath c.ActiveDirectoryBasePath = ActiveDirectoryDefaultBasePath + c.ApigeeBasePath = ApigeeDefaultBasePath c.AppEngineBasePath = AppEngineDefaultBasePath c.BigQueryBasePath = BigQueryDefaultBasePath c.BigqueryDataTransferBasePath = BigqueryDataTransferDefaultBasePath diff --git a/google/provider.go b/google/provider.go index df1fa09b214..d92107822fd 100644 --- a/google/provider.go +++ b/google/provider.go @@ -159,6 +159,14 @@ func Provider() *schema.Provider { "GOOGLE_ACTIVE_DIRECTORY_CUSTOM_ENDPOINT", }, ActiveDirectoryDefaultBasePath), }, + "apigee_custom_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateCustomEndpoint, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{ + "GOOGLE_APIGEE_CUSTOM_ENDPOINT", + }, ApigeeDefaultBasePath), + }, "app_engine_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -705,9 +713,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 180 +// Generated resources: 181 // Generated IAM resources: 75 -// Total generated resources: 255 +// Total generated resources: 256 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -729,6 +737,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_access_context_manager_gcp_user_access_binding": resourceAccessContextManagerGcpUserAccessBinding(), "google_active_directory_domain": resourceActiveDirectoryDomain(), "google_active_directory_domain_trust": resourceActiveDirectoryDomainTrust(), + "google_apigee_organization": resourceApigeeOrganization(), "google_app_engine_domain_mapping": resourceAppEngineDomainMapping(), "google_app_engine_firewall_rule": resourceAppEngineFirewallRule(), "google_app_engine_standard_app_version": resourceAppEngineStandardAppVersion(), @@ -1160,6 +1169,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.AccessApprovalBasePath = d.Get("access_approval_custom_endpoint").(string) config.AccessContextManagerBasePath = d.Get("access_context_manager_custom_endpoint").(string) config.ActiveDirectoryBasePath = d.Get("active_directory_custom_endpoint").(string) + config.ApigeeBasePath = d.Get("apigee_custom_endpoint").(string) config.AppEngineBasePath = d.Get("app_engine_custom_endpoint").(string) config.BigQueryBasePath = d.Get("big_query_custom_endpoint").(string) config.BigqueryDataTransferBasePath = d.Get("bigquery_data_transfer_custom_endpoint").(string) diff --git a/google/resource_apigee_organization.go b/google/resource_apigee_organization.go new file mode 100644 index 00000000000..5be5620b63c --- /dev/null +++ b/google/resource_apigee_organization.go @@ -0,0 +1,492 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceApigeeOrganization() *schema.Resource { + return &schema.Resource{ + Create: resourceApigeeOrganizationCreate, + Read: resourceApigeeOrganizationRead, + Update: resourceApigeeOrganizationUpdate, + Delete: resourceApigeeOrganizationDelete, + + Importer: &schema.ResourceImporter{ + State: resourceApigeeOrganizationImport, + }, + + 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{ + "project_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The project ID associated with the Apigee organization.`, + }, + "analytics_region": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).`, + }, + "authorized_network": { + Type: schema.TypeString, + Optional: true, + Description: `Compute Engine network used for Service Networking to be peered with Apigee runtime instances. +See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). +Valid only when 'RuntimeType' is set to CLOUD. The value can be updated only when there are no runtime instances. For example: "default".`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `Description of the Apigee organization.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `The display name of the Apigee organization.`, + }, + "runtime_database_encryption_key_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. +Update is not allowed after the organization is created. +If not specified, a Google-Managed encryption key will be used. +Valid only when 'RuntimeType' is CLOUD. For example: 'projects/foo/locations/us/keyRings/bar/cryptoKeys/baz'.`, + }, + "runtime_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{"CLOUD", "HYBRID", ""}, false), + Description: `Runtime type of the Apigee organization based on the Apigee subscription purchased. Default value: "CLOUD" Possible values: ["CLOUD", "HYBRID"]`, + Default: "CLOUD", + }, + "ca_certificate": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Base64-encoded public certificate for the root CA of the Apigee organization. +Valid only when 'RuntimeType' is CLOUD. A base64-encoded string.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Name of the Apigee organization.`, + }, + "subscription_type": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Subscription type of the Apigee organization. +Valid values include trial (free, limited, and for evaluation purposes only) or paid (full subscription has been purchased).`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceApigeeOrganizationCreate(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{}) + displayNameProp, err := expandApigeeOrganizationDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandApigeeOrganizationDescription(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 + } + analyticsRegionProp, err := expandApigeeOrganizationAnalyticsRegion(d.Get("analytics_region"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("analytics_region"); !isEmptyValue(reflect.ValueOf(analyticsRegionProp)) && (ok || !reflect.DeepEqual(v, analyticsRegionProp)) { + obj["analyticsRegion"] = analyticsRegionProp + } + authorizedNetworkProp, err := expandApigeeOrganizationAuthorizedNetwork(d.Get("authorized_network"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("authorized_network"); !isEmptyValue(reflect.ValueOf(authorizedNetworkProp)) && (ok || !reflect.DeepEqual(v, authorizedNetworkProp)) { + obj["authorizedNetwork"] = authorizedNetworkProp + } + runtimeTypeProp, err := expandApigeeOrganizationRuntimeType(d.Get("runtime_type"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("runtime_type"); !isEmptyValue(reflect.ValueOf(runtimeTypeProp)) && (ok || !reflect.DeepEqual(v, runtimeTypeProp)) { + obj["runtimeType"] = runtimeTypeProp + } + runtimeDatabaseEncryptionKeyNameProp, err := expandApigeeOrganizationRuntimeDatabaseEncryptionKeyName(d.Get("runtime_database_encryption_key_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("runtime_database_encryption_key_name"); !isEmptyValue(reflect.ValueOf(runtimeDatabaseEncryptionKeyNameProp)) && (ok || !reflect.DeepEqual(v, runtimeDatabaseEncryptionKeyNameProp)) { + obj["runtimeDatabaseEncryptionKeyName"] = runtimeDatabaseEncryptionKeyNameProp + } + + obj, err = resourceApigeeOrganizationEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ApigeeBasePath}}organizations?parent=projects/{{project_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new Organization: %#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 Organization: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "organizations/{{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 Organization", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create Organization: %s", err) + } + + if err := d.Set("name", flattenApigeeOrganizationName(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, "organizations/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating Organization %q: %#v", d.Id(), res) + + return resourceApigeeOrganizationRead(d, meta) +} + +func resourceApigeeOrganizationRead(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}}organizations/{{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("ApigeeOrganization %q", d.Id())) + } + + if err := d.Set("name", flattenApigeeOrganizationName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("display_name", flattenApigeeOrganizationDisplayName(res["displayName"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("description", flattenApigeeOrganizationDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("analytics_region", flattenApigeeOrganizationAnalyticsRegion(res["analyticsRegion"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("authorized_network", flattenApigeeOrganizationAuthorizedNetwork(res["authorizedNetwork"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("runtime_type", flattenApigeeOrganizationRuntimeType(res["runtimeType"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("subscription_type", flattenApigeeOrganizationSubscriptionType(res["subscriptionType"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("ca_certificate", flattenApigeeOrganizationCaCertificate(res["caCertificate"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + if err := d.Set("runtime_database_encryption_key_name", flattenApigeeOrganizationRuntimeDatabaseEncryptionKeyName(res["runtimeDatabaseEncryptionKeyName"], d, config)); err != nil { + return fmt.Errorf("Error reading Organization: %s", err) + } + + return nil +} + +func resourceApigeeOrganizationUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + obj := make(map[string]interface{}) + displayNameProp, err := expandApigeeOrganizationDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandApigeeOrganizationDescription(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 + } + analyticsRegionProp, err := expandApigeeOrganizationAnalyticsRegion(d.Get("analytics_region"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("analytics_region"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, analyticsRegionProp)) { + obj["analyticsRegion"] = analyticsRegionProp + } + authorizedNetworkProp, err := expandApigeeOrganizationAuthorizedNetwork(d.Get("authorized_network"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("authorized_network"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, authorizedNetworkProp)) { + obj["authorizedNetwork"] = authorizedNetworkProp + } + runtimeTypeProp, err := expandApigeeOrganizationRuntimeType(d.Get("runtime_type"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("runtime_type"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, runtimeTypeProp)) { + obj["runtimeType"] = runtimeTypeProp + } + runtimeDatabaseEncryptionKeyNameProp, err := expandApigeeOrganizationRuntimeDatabaseEncryptionKeyName(d.Get("runtime_database_encryption_key_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("runtime_database_encryption_key_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, runtimeDatabaseEncryptionKeyNameProp)) { + obj["runtimeDatabaseEncryptionKeyName"] = runtimeDatabaseEncryptionKeyNameProp + } + + obj, err = resourceApigeeOrganizationEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ApigeeBasePath}}organizations/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating Organization %q: %#v", d.Id(), obj) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "PUT", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return fmt.Errorf("Error updating Organization %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating Organization %q: %#v", d.Id(), res) + } + + err = apigeeOperationWaitTime( + config, res, "Updating Organization", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + + return resourceApigeeOrganizationRead(d, meta) +} + +func resourceApigeeOrganizationDelete(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}}organizations/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting Organization %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, "Organization") + } + + err = apigeeOperationWaitTime( + config, res, "Deleting Organization", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting Organization %q: %#v", d.Id(), res) + return nil +} + +func resourceApigeeOrganizationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + + // current import_formats can't import fields with forward slashes in their value + if err := parseImportId([]string{"(?P.+)"}, d, config); err != nil { + return nil, err + } + + parts := strings.Split(d.Get("name").(string), "/") + + var projectId string + switch len(parts) { + case 1: + projectId = parts[0] + case 2: + projectId = parts[1] + default: + return nil, fmt.Errorf( + "Saw %s when the name is expected to have shape %s or %s", + d.Get("name"), + "{{name}}", + "organizations/{{name}}", + ) + } + + if err := d.Set("name", projectId); err != nil { + return nil, fmt.Errorf("Error setting organization: %s", err) + } + + if err := d.Set("project_id", projectId); err != nil { + return nil, fmt.Errorf("Error setting organization: %s", err) + } + return []*schema.ResourceData{d}, nil +} + +func flattenApigeeOrganizationName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationAnalyticsRegion(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationAuthorizedNetwork(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationRuntimeType(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationSubscriptionType(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationCaCertificate(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenApigeeOrganizationRuntimeDatabaseEncryptionKeyName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandApigeeOrganizationDisplayName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandApigeeOrganizationDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandApigeeOrganizationAnalyticsRegion(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandApigeeOrganizationAuthorizedNetwork(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandApigeeOrganizationRuntimeType(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandApigeeOrganizationRuntimeDatabaseEncryptionKeyName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func resourceApigeeOrganizationEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { + obj["name"] = d.Get("project_id").(string) + return obj, nil +} diff --git a/google/resource_apigee_organization_generated_test.go b/google/resource_apigee_organization_generated_test.go new file mode 100644 index 00000000000..643a1e5c94c --- /dev/null +++ b/google/resource_apigee_organization_generated_test.go @@ -0,0 +1,145 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccApigeeOrganization_apigeeOrganizationCloudBasicTestExample(t *testing.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, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckApigeeOrganizationDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccApigeeOrganization_apigeeOrganizationCloudBasicTestExample(context), + }, + { + ResourceName: "google_apigee_organization.org", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"project_id"}, + }, + }, + }) +} + +func testAccApigeeOrganization_apigeeOrganizationCloudBasicTestExample(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 = 16 + 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" "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, + ] +} +`, context) +} + +func testAccCheckApigeeOrganizationDestroyProducer(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_organization" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{ApigeeBasePath}}organizations/{{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("ApigeeOrganization still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/resource_apigee_organization_sweeper_test.go b/google/resource_apigee_organization_sweeper_test.go new file mode 100644 index 00000000000..cde7e45716f --- /dev/null +++ b/google/resource_apigee_organization_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** 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 ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("ApigeeOrganization", &resource.Sweeper{ + Name: "ApigeeOrganization", + F: testSweepApigeeOrganization, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepApigeeOrganization(region string) error { + resourceName := "ApigeeOrganization" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sharedConfigForRegion(region) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) + return err + } + + err = config.LoadAndValidate(context.Background()) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) + return err + } + + t := &testing.T{} + billingId := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://apigee.googleapis.com/v1/organizations", "?")[0] + listUrl, err := replaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := sendRequest(config, "GET", config.Project, listUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["organizations"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // Keep count of items that aren't sweepable for logging. + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + if obj["name"] == nil { + log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) + return nil + } + + name := GetResourceNameFromSelfLink(obj["name"].(string)) + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://apigee.googleapis.com/v1/organizations/{{name}}" + deleteUrl, err := replaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/website/docs/r/apigee_organization.html.markdown b/website/docs/r/apigee_organization.html.markdown new file mode 100644 index 00000000000..914437807cd --- /dev/null +++ b/website/docs/r/apigee_organization.html.markdown @@ -0,0 +1,213 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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. +# +# ---------------------------------------------------------------------------- +subcategory: "Apigee" +layout: "google" +page_title: "Google: google_apigee_organization" +sidebar_current: "docs-google-apigee-organization" +description: |- + An `Organization` is the top-level container in Apigee. +--- + +# google\_apigee\_organization + +An `Organization` is the top-level container in Apigee. + + +To get more information about Organization, see: + +* [API documentation](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations) +* How-to Guides + * [Creating an API organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org) + +## Example Usage - Apigee Organization Cloud 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 = 16 + 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_apigee_organization" "org" { + analytics_region = "us-central1" + project_id = data.google_client_config.current.project + authorized_network = google_compute_network.apigee_network.id + depends_on = [google_service_networking_connection.apigee_vpc_connection] +} +``` +## Example Usage - Apigee Organization Cloud Full + + +```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 = 16 + 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" "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_key.apigee_key.id + + depends_on = [ + google_service_networking_connection.apigee_vpc_connection, + google_kms_crypto_key_iam_binding.apigee_sa_keyuser, + ] +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `project_id` - + (Required) + The project ID associated with the Apigee organization. + + +- - - + + +* `display_name` - + (Optional) + The display name of the Apigee organization. + +* `description` - + (Optional) + Description of the Apigee organization. + +* `analytics_region` - + (Optional) + Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org). + +* `authorized_network` - + (Optional) + Compute Engine network used for Service Networking to be peered with Apigee runtime instances. + See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). + Valid only when `RuntimeType` is set to CLOUD. The value can be updated only when there are no runtime instances. For example: "default". + +* `runtime_type` - + (Optional) + Runtime type of the Apigee organization based on the Apigee subscription purchased. + Default value is `CLOUD`. + Possible values are `CLOUD` and `HYBRID`. + +* `runtime_database_encryption_key_name` - + (Optional) + Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. + Update is not allowed after the organization is created. + If not specified, a Google-Managed encryption key will be used. + Valid only when `RuntimeType` is CLOUD. For example: `projects/foo/locations/us/keyRings/bar/cryptoKeys/baz`. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `organizations/{{name}}` + +* `name` - + Output only. Name of the Apigee organization. + +* `subscription_type` - + Output only. Subscription type of the Apigee organization. + Valid values include trial (free, limited, and for evaluation purposes only) or paid (full subscription has been purchased). + +* `ca_certificate` - + Output only. Base64-encoded public certificate for the root CA of the Apigee organization. + Valid only when `RuntimeType` is CLOUD. A base64-encoded string. + + +## 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 + + +Organization can be imported using any of these accepted formats: + +``` +$ terraform import google_apigee_organization.default organizations/{{name}} +$ terraform import google_apigee_organization.default {{name}} +``` diff --git a/website/google.erb b/website/google.erb index 1ce07504c3c..be9aa1b4c49 100644 --- a/website/google.erb +++ b/website/google.erb @@ -147,6 +147,22 @@ +
  • + Apigee + +
  • +
  • App Engine