Skip to content

Commit

Permalink
Merge pull request #11513 from c2thorn/sync-main-FEATURE-BRANCH-6.0.0 (
Browse files Browse the repository at this point in the history
…#19210)

Sync main feature branch 6.0.0 - 8/21

[upstream:5041f537b74e607bc605f1fc5cb1b89f428f2a6f]

Signed-off-by: Modular Magician <[email protected]>
  • Loading branch information
modular-magician authored Aug 21, 2024
1 parent 301eeab commit 944e9f0
Show file tree
Hide file tree
Showing 12 changed files with 285 additions and 21 deletions.
3 changes: 3 additions & 0 deletions .changelog/11513.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:none

```
23 changes: 23 additions & 0 deletions google/acctest/resource_test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,40 @@
package acctest

import (
"context"
"errors"
"fmt"
"slices"
"testing"
"time"

tfjson "github.com/hashicorp/terraform-json"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/hashicorp/terraform-plugin-testing/terraform"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
)

// General test utils

var _ plancheck.PlanCheck = expectNoDelete{}

type expectNoDelete struct{}

func (e expectNoDelete) CheckPlan(ctx context.Context, req plancheck.CheckPlanRequest, resp *plancheck.CheckPlanResponse) {
var result error
for _, rc := range req.Plan.ResourceChanges {
if slices.Contains(rc.Change.Actions, tfjson.ActionDelete) {
result = errors.Join(result, fmt.Errorf("expected no deletion of resources, but %s has planned deletion", rc.Address))
}
}
resp.Error = result
}

func ExpectNoDelete() plancheck.PlanCheck {
return expectNoDelete{}
}

// TestExtractResourceAttr navigates a test's state to find the specified resource (or data source) attribute and makes the value
// accessible via the attributeValue string pointer.
func TestExtractResourceAttr(resourceName string, attributeName string, attributeValue *string) resource.TestCheckFunc {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ func TestAccComposerEnvironment_basic(t *testing.T) {
// Checks that all updatable fields can be updated in one apply
// (PATCH for Environments only is per-field)
func TestAccComposerEnvironment_update(t *testing.T) {
// Currently failing
acctest.SkipIfVcr(t)
t.Parallel()

envName := fmt.Sprintf("%s-%d", testComposerEnvironmentPrefix, acctest.RandInt(t))
Expand Down Expand Up @@ -281,6 +283,8 @@ func TestAccComposerEnvironment_withDatabaseConfig(t *testing.T) {
}

func TestAccComposerEnvironment_withWebServerConfig(t *testing.T) {
// Currently failing
acctest.SkipIfVcr(t)
t.Parallel()
envName := fmt.Sprintf("%s-%d", testComposerEnvironmentPrefix, acctest.RandInt(t))
network := fmt.Sprintf("%s-%d", testComposerNetworkPrefix, acctest.RandInt(t))
Expand Down
31 changes: 30 additions & 1 deletion google/services/compute/resource_compute_global_address.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ when purpose=PRIVATE_SERVICE_CONNECT`,
Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"label_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `The fingerprint used for optimistic locking of this resource. Used
internally during updates.`,
},
"terraform_labels": {
Type: schema.TypeMap,
Computed: true,
Expand Down Expand Up @@ -203,6 +209,12 @@ func resourceComputeGlobalAddressCreate(d *schema.ResourceData, meta interface{}
} else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {
obj["name"] = nameProp
}
labelFingerprintProp, err := expandComputeGlobalAddressLabelFingerprint(d.Get("label_fingerprint"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("label_fingerprint"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelFingerprintProp)) && (ok || !reflect.DeepEqual(v, labelFingerprintProp)) {
obj["labelFingerprint"] = labelFingerprintProp
}
ipVersionProp, err := expandComputeGlobalAddressIpVersion(d.Get("ip_version"), d, config)
if err != nil {
return err
Expand Down Expand Up @@ -418,6 +430,9 @@ func resourceComputeGlobalAddressRead(d *schema.ResourceData, meta interface{})
if err := d.Set("labels", flattenComputeGlobalAddressLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading GlobalAddress: %s", err)
}
if err := d.Set("label_fingerprint", flattenComputeGlobalAddressLabelFingerprint(res["labelFingerprint"], d, config)); err != nil {
return fmt.Errorf("Error reading GlobalAddress: %s", err)
}
if err := d.Set("ip_version", flattenComputeGlobalAddressIpVersion(res["ipVersion"], d, config)); err != nil {
return fmt.Errorf("Error reading GlobalAddress: %s", err)
}
Expand Down Expand Up @@ -463,9 +478,15 @@ func resourceComputeGlobalAddressUpdate(d *schema.ResourceData, meta interface{}

d.Partial(true)

if d.HasChange("effective_labels") {
if d.HasChange("label_fingerprint") || d.HasChange("effective_labels") {
obj := make(map[string]interface{})

labelFingerprintProp, err := expandComputeGlobalAddressLabelFingerprint(d.Get("label_fingerprint"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("label_fingerprint"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelFingerprintProp)) {
obj["labelFingerprint"] = labelFingerprintProp
}
labelsProp, err := expandComputeGlobalAddressEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
Expand Down Expand Up @@ -621,6 +642,10 @@ func flattenComputeGlobalAddressLabels(v interface{}, d *schema.ResourceData, co
return transformed
}

func flattenComputeGlobalAddressLabelFingerprint(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}

func flattenComputeGlobalAddressIpVersion(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
Expand Down Expand Up @@ -688,6 +713,10 @@ func expandComputeGlobalAddressName(v interface{}, d tpgresource.TerraformResour
return v, nil
}

func expandComputeGlobalAddressLabelFingerprint(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) {
return v, nil
}

func expandComputeGlobalAddressIpVersion(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) {
return v, nil
}
Expand Down
84 changes: 84 additions & 0 deletions google/services/compute/resource_compute_global_address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,48 @@ import (
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
)

func TestAccComputeGlobalAddress_update(t *testing.T) {
t.Parallel()

context := map[string]interface{}{
"random_suffix": acctest.RandString(t, 10),
}

acctest.VcrTest(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
CheckDestroy: testAccCheckComputeGlobalAddressDestroyProducer(t),
Steps: []resource.TestStep{
{
Config: testAccComputeGlobalAddress_update1(context),
},
{
ResourceName: "google_compute_global_address.foobar",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"labels", "terraform_labels"},
},
{
Config: testAccComputeGlobalAddress_update2(context),
ConfigPlanChecks: resource.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
acctest.ExpectNoDelete(),
},
},
},
{
ResourceName: "google_compute_global_address.foobar",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"labels", "terraform_labels"},
},
},
})
}

func TestAccComputeGlobalAddress_ipv6(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -76,3 +116,47 @@ resource "google_compute_global_address" "foobar" {
}
`, networkName, addressName)
}

func testAccComputeGlobalAddress_update1(context map[string]interface{}) string {
return acctest.Nprintf(`
resource "google_compute_network" "foobar" {
name = "tf-test-address-%{random_suffix}"
}
resource "google_compute_global_address" "foobar" {
address = "172.20.181.0"
description = "Description"
name = "tf-test-address-%{random_suffix}"
labels = {
foo = "bar"
}
ip_version = "IPV4"
prefix_length = 24
address_type = "INTERNAL"
purpose = "VPC_PEERING"
network = google_compute_network.foobar.self_link
}
`, context)
}

func testAccComputeGlobalAddress_update2(context map[string]interface{}) string {
return acctest.Nprintf(`
resource "google_compute_network" "foobar" {
name = "tf-test-address-%{random_suffix}"
}
resource "google_compute_global_address" "foobar" {
address = "172.20.181.0"
description = "Description"
name = "tf-test-address-%{random_suffix}"
labels = {
foo = "baz"
}
ip_version = "IPV4"
prefix_length = 24
address_type = "INTERNAL"
purpose = "VPC_PEERING"
network = google_compute_network.foobar.self_link
}
`, context)
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import (

// Custom Module tests cannot be run in parallel without running into 409 Conflict reponses.
// Run them as individual steps of an update test instead.
func TestAccSecurityCenterManagementFolderSecurityHealthAnalyticsCustomModule(t *testing.T) {
t.Parallel()
func testAccSecurityCenterManagementFolderSecurityHealthAnalyticsCustomModule(t *testing.T) {

context := map[string]interface{}{
"org_id": envvar.GetTestOrgFromEnv(t),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,28 @@ import (
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
)

func TestAccSecurityCenterManagementOrganizationEventThreatDetectionCustomModule(t *testing.T) {
t.Parallel()
func TestAccSecurityCenterManagement(t *testing.T) {
testCases := map[string]func(t *testing.T){
"orgSecurity": testAccSecurityCenterManagementOrganizationSecurityHealthAnalyticsCustomModule,
"folderSecurity": testAccSecurityCenterManagementFolderSecurityHealthAnalyticsCustomModule,
"projectSecurity": testAccSecurityCenterManagementProjectSecurityHealthAnalyticsCustomModule,
"organization": testAccSecurityCenterManagementOrganizationEventThreatDetectionCustomModule,
}

for name, tc := range testCases {
// shadow the tc variable into scope so that when
// the loop continues, if t.Run hasn't executed tc(t)
// yet, we don't have a race condition
// see https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
tc := tc
t.Run(name, func(t *testing.T) {
tc(t)
})
}
}

func testAccSecurityCenterManagementOrganizationEventThreatDetectionCustomModule(t *testing.T) {
// t.Parallel()

context := map[string]interface{}{
"org_id": envvar.GetTestOrgFromEnv(t),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import (

// Custom Module tests cannot be run in parallel without running into 409 Conflict reponses.
// Run them as individual steps of an update test instead.
func TestAccSecurityCenterManagementProjectSecurityHealthAnalyticsCustomModule(t *testing.T) {
t.Parallel()
func testAccSecurityCenterManagementProjectSecurityHealthAnalyticsCustomModule(t *testing.T) {

context := map[string]interface{}{
"random_suffix": acctest.RandString(t, 10),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import (

// Custom Module tests cannot be run in parallel without running into 409 Conflict reponses.
// Run them as individual steps of an update test instead.
func TestAccSecurityCenterManagementOrganizationSecurityHealthAnalyticsCustomModule(t *testing.T) {
t.Parallel()
func testAccSecurityCenterManagementOrganizationSecurityHealthAnalyticsCustomModule(t *testing.T) {

context := map[string]interface{}{
"org_id": envvar.GetTestOrgFromEnv(t),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"google.golang.org/api/googleapi"

"github.com/hashicorp/terraform-provider-google/google/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
Expand Down Expand Up @@ -67,6 +68,52 @@ func isMultiNodePrivateCloud(d *schema.ResourceData) bool {
return false
}

func isPrivateCloudInDeletedState(config *transport_tpg.Config, d *schema.ResourceData, billingProject string, userAgent string) (bool, error) {
baseurl, err := tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}projects/{{project}}/locations/{{location}}/privateClouds/{{name}}")
if err != nil {
return false, err
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: baseurl,
UserAgent: userAgent,
})
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
log.Printf("[DEBUG] No existing private cloud found")
return false, nil
}
return false, err
}
// if resource exists but is marked for deletion
v, ok := res["state"]
if ok && v.(string) == "DELETED" {
log.Printf("[DEBUG] The Private cloud exists and is marked for deletion.")
return true, nil
}
return false, nil
}

// Check if private cloud is absent or if it exists in a deleted state.
func pollCheckForPrivateCloudAbsence(resp map[string]interface{}, respErr error) transport_tpg.PollResult {
if respErr != nil {
if transport_tpg.IsGoogleApiErrorWithCode(respErr, 404) {
return transport_tpg.SuccessPollResult()
}
return transport_tpg.ErrorPollResult(respErr)
}
// if resource exists but is marked for deletion
log.Printf("[DEBUG] Fetching state of the private cloud.")
v, ok := resp["state"]
if ok && v.(string) == "DELETED" {
log.Printf("[DEBUG] The Private cloud has been successfully marked for delayed deletion.")
return transport_tpg.SuccessPollResult()
}
return transport_tpg.PendingStatusPollResult("found")
}

func ResourceVmwareenginePrivateCloud() *schema.Resource {
return &schema.Resource{
Create: resourceVmwareenginePrivateCloudCreate,
Expand Down Expand Up @@ -400,6 +447,21 @@ func resourceVmwareenginePrivateCloudCreate(d *schema.ResourceData, meta interfa
}

headers := make(http.Header)
// Check if the project exists in a deleted state
pcMarkedForDeletion, err := isPrivateCloudInDeletedState(config, d, billingProject, userAgent)
if err != nil {
return fmt.Errorf("Error checking if Private Cloud exists and is marked for deletion: %s", err)
}
if pcMarkedForDeletion {
log.Printf("[DEBUG] Private Cloud exists and is marked for deletion. Triggering UNDELETE of the Private Cloud.\n")
url, err = tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}projects/{{project}}/locations/{{location}}/privateClouds/{{name}}:undelete")
if err != nil {
return err
}
obj = make(map[string]interface{})
} else {
log.Printf("[DEBUG] Private Cloud is not found to be marked for deletion. Triggering CREATE of the Private Cloud.\n")
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Expand Down Expand Up @@ -742,18 +804,11 @@ func resourceVmwareenginePrivateCloudDelete(d *schema.ResourceData, meta interfa
if err != nil {
return res, err
}
// if resource exists but is marked for deletion
log.Printf("[DEBUG] Fetching state of the private cloud.")
v, ok := res["state"]
if ok && v.(string) == "DELETED" {
log.Printf("[DEBUG] The Private cloud has been successfully marked for delayed deletion.")
return nil, nil
}
return res, nil
}
}

err = transport_tpg.PollingWaitTime(privateCloudPollRead(d, meta), transport_tpg.PollCheckForAbsence, "Deleting PrivateCloud", d.Timeout(schema.TimeoutDelete), 10)
err = transport_tpg.PollingWaitTime(privateCloudPollRead(d, meta), pollCheckForPrivateCloudAbsence, "Deleting PrivateCloud", d.Timeout(schema.TimeoutDelete), 10)
if err != nil {
return fmt.Errorf("Error waiting to delete PrivateCloud: %s", err)
}
Expand Down
Loading

0 comments on commit 944e9f0

Please sign in to comment.