Skip to content

Commit f6f5644

Browse files
API implementation for fetch Resource Type of data source references (#15048) (#10672)
[upstream:22350553354dd17b816e799d5bb05ad3daf63599] Signed-off-by: Modular Magician <[email protected]>
1 parent 97e7160 commit f6f5644

File tree

5 files changed

+425
-0
lines changed

5 files changed

+425
-0
lines changed

.changelog/15048.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:new-datasource
2+
`google_backup_dr_data_source_references`
3+
```

google-beta/provider/provider_mmv1_resources.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ var handwrittenDatasources = map[string]*schema.Resource{
218218
"google_backup_dr_backup": backupdr.DataSourceGoogleCloudBackupDRBackup(),
219219
"google_backup_dr_data_source": backupdr.DataSourceGoogleCloudBackupDRDataSource(),
220220
"google_backup_dr_backup_vault": backupdr.DataSourceGoogleCloudBackupDRBackupVault(),
221+
"google_backup_dr_data_source_references": backupdr.DataSourceGoogleCloudBackupDRDataSourceReferences(),
221222
"google_beyondcorp_app_connection": beyondcorp.DataSourceGoogleBeyondcorpAppConnection(),
222223
"google_beyondcorp_app_connector": beyondcorp.DataSourceGoogleBeyondcorpAppConnector(),
223224
"google_beyondcorp_app_gateway": beyondcorp.DataSourceGoogleBeyondcorpAppGateway(),
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
// Copyright (c) HashiCorp, Inc.
2+
// SPDX-License-Identifier: MPL-2.0
3+
// ----------------------------------------------------------------------------
4+
//
5+
// *** AUTO GENERATED CODE *** Type: Handwritten ***
6+
//
7+
// ----------------------------------------------------------------------------
8+
//
9+
// This code is generated by Magic Modules using the following:
10+
//
11+
// Source file: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference.go
12+
//
13+
// DO NOT EDIT this file directly. Any changes made to this file will be
14+
// overwritten during the next generation cycle.
15+
//
16+
// ----------------------------------------------------------------------------
17+
package backupdr
18+
19+
import (
20+
"fmt"
21+
"strconv"
22+
23+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
24+
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
25+
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
26+
)
27+
28+
func DataSourceGoogleCloudBackupDRDataSourceReferences() *schema.Resource {
29+
return &schema.Resource{
30+
Read: dataSourceGoogleCloudBackupDRDataSourceReferencesRead,
31+
Schema: map[string]*schema.Schema{
32+
"location": {
33+
Type: schema.TypeString,
34+
Required: true,
35+
Description: "The location to list the data source references from.",
36+
},
37+
"project": {
38+
Type: schema.TypeString,
39+
Optional: true,
40+
Computed: true,
41+
Description: "The ID of the project in which the resource belongs.",
42+
},
43+
"resource_type": {
44+
Type: schema.TypeString,
45+
Required: true,
46+
Description: `The resource type to get the data source references for. Examples include, "compute.googleapis.com/Instance", "sqladmin.googleapis.com/Instance".`,
47+
},
48+
49+
// Output: a computed list of the data source references found
50+
"data_source_references": {
51+
Type: schema.TypeList,
52+
Computed: true,
53+
Description: "A list of the data source references found.",
54+
Elem: &schema.Resource{
55+
Schema: map[string]*schema.Schema{
56+
"name": {
57+
Type: schema.TypeString,
58+
Computed: true,
59+
},
60+
"data_source": {
61+
Type: schema.TypeString,
62+
Computed: true,
63+
Description: "The underlying data source resource.",
64+
},
65+
"gcp_resource_name": {
66+
Type: schema.TypeString,
67+
Computed: true,
68+
Description: "The GCP resource name for the data source.",
69+
},
70+
"backup_config_state": {
71+
Type: schema.TypeString,
72+
Computed: true,
73+
Description: "The state of the backup config for the data source.",
74+
},
75+
"backup_count": {
76+
Type: schema.TypeInt,
77+
Computed: true,
78+
Description: "The number of backups for the data source.",
79+
},
80+
"last_backup_state": {
81+
Type: schema.TypeString,
82+
Computed: true,
83+
Description: "The state of the last backup.",
84+
},
85+
"last_successful_backup_time": {
86+
Type: schema.TypeString,
87+
Computed: true,
88+
Description: "The last time a successful backup was made.",
89+
},
90+
"resource_type": {
91+
Type: schema.TypeString,
92+
Computed: true,
93+
},
94+
},
95+
},
96+
},
97+
},
98+
}
99+
}
100+
101+
func dataSourceGoogleCloudBackupDRDataSourceReferencesRead(d *schema.ResourceData, meta interface{}) error {
102+
config := meta.(*transport_tpg.Config)
103+
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
104+
if err != nil {
105+
return err
106+
}
107+
108+
project, err := tpgresource.GetProject(d, config)
109+
if err != nil {
110+
return err
111+
}
112+
113+
location := d.Get("location").(string)
114+
resourceType := d.Get("resource_type").(string)
115+
116+
url := fmt.Sprintf("%sprojects/%s/locations/%s/dataSourceReferences:fetchForResourceType?resourceType=%s", config.BackupDRBasePath, project, location, resourceType)
117+
118+
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
119+
Config: config,
120+
Method: "GET",
121+
Project: project,
122+
RawURL: url,
123+
UserAgent: userAgent,
124+
})
125+
if err != nil {
126+
return fmt.Errorf("Error reading DataSourceReferences: %s", err)
127+
}
128+
129+
items, ok := res["dataSourceReferences"].([]interface{})
130+
if !ok {
131+
items = make([]interface{}, 0)
132+
}
133+
134+
flattenedDataSourceReferences, err := flattenDataSourceReferences(items)
135+
if err != nil {
136+
return err
137+
}
138+
139+
if err := d.Set("data_source_references", flattenedDataSourceReferences); err != nil {
140+
return fmt.Errorf("Error setting data_source_references: %s", err)
141+
}
142+
143+
d.SetId(url)
144+
145+
return nil
146+
}
147+
148+
func flattenDataSourceReferences(items []interface{}) ([]map[string]interface{}, error) {
149+
references := make([]map[string]interface{}, 0, len(items))
150+
for _, item := range items {
151+
data, ok := item.(map[string]interface{})
152+
if !ok {
153+
return nil, fmt.Errorf("cannot cast item to map[string]interface{}")
154+
}
155+
156+
ref := map[string]interface{}{
157+
"name": data["name"],
158+
"data_source": data["dataSource"],
159+
"backup_config_state": data["dataSourceBackupConfigState"],
160+
}
161+
162+
// The API returns backup count as a string, so we parse it to an integer.
163+
if v, ok := data["dataSourceBackupCount"].(string); ok {
164+
if i, err := strconv.Atoi(v); err == nil {
165+
ref["backup_count"] = i
166+
}
167+
}
168+
169+
// Flatten the nested dataSourceBackupConfigInfo object.
170+
if configInfo, ok := data["dataSourceBackupConfigInfo"].(map[string]interface{}); ok {
171+
ref["last_backup_state"] = configInfo["lastBackupState"]
172+
ref["last_successful_backup_time"] = configInfo["lastSuccessfulBackupConsistencyTime"]
173+
}
174+
175+
if resourceInfo, ok := data["dataSourceGcpResourceInfo"].(map[string]interface{}); ok {
176+
ref["gcp_resource_name"] = resourceInfo["gcpResourcename"]
177+
ref["resource_type"] = resourceInfo["type"]
178+
}
179+
180+
references = append(references, ref)
181+
}
182+
return references, nil
183+
}
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Copyright (c) HashiCorp, Inc.
2+
// SPDX-License-Identifier: MPL-2.0
3+
// ----------------------------------------------------------------------------
4+
//
5+
// *** AUTO GENERATED CODE *** Type: Handwritten ***
6+
//
7+
// ----------------------------------------------------------------------------
8+
//
9+
// This code is generated by Magic Modules using the following:
10+
//
11+
// Source file: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference_test.go
12+
//
13+
// DO NOT EDIT this file directly. Any changes made to this file will be
14+
// overwritten during the next generation cycle.
15+
//
16+
// ----------------------------------------------------------------------------
17+
package backupdr_test
18+
19+
import (
20+
"fmt"
21+
"testing"
22+
23+
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
24+
"github.com/hashicorp/terraform-plugin-testing/terraform"
25+
"github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest"
26+
)
27+
28+
func TestAccDataSourceGoogleBackupDRDataSourceReferences_basic(t *testing.T) {
29+
t.Parallel()
30+
31+
projectDsName := "data.google_project.project"
32+
var projectID string
33+
context := map[string]interface{}{
34+
"location": "us-central1",
35+
"resource_type": "sqladmin.googleapis.com/Instance",
36+
"random_suffix": acctest.RandString(t, 10),
37+
}
38+
39+
acctest.VcrTest(t, resource.TestCase{
40+
PreCheck: func() { acctest.AccTestPreCheck(t) },
41+
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
42+
Steps: []resource.TestStep{
43+
{
44+
Config: testAccDataSourceGoogleBackupDRDataSourceReferences_basic(context),
45+
Check: func(s *terraform.State) error {
46+
// Extract project ID from the project data source in the state
47+
project, ok := s.RootModule().Resources[projectDsName]
48+
if !ok {
49+
return fmt.Errorf("project data source not found: %s", projectDsName)
50+
}
51+
projectID = project.Primary.Attributes["project_id"]
52+
53+
return resource.ComposeTestCheckFunc(
54+
// Basic attribute checks
55+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "project", projectID),
56+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "location", context["location"].(string)),
57+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "resource_type", context["resource_type"].(string)),
58+
59+
// Check that the list itself is populated
60+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.#"),
61+
62+
// Checks for existing and new fields within the list
63+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.name"),
64+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.data_source"),
65+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.backup_config_state"),
66+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.gcp_resource_name"),
67+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.resource_type"),
68+
)(s)
69+
},
70+
},
71+
},
72+
})
73+
}
74+
75+
func testAccDataSourceGoogleBackupDRDataSourceReferences_basic(context map[string]interface{}) string {
76+
return acctest.Nprintf(`
77+
78+
79+
data "google_project" "project" {}
80+
81+
82+
resource "google_service_account" "default" {
83+
account_id = "tf-test-my-custom-%{random_suffix}"
84+
display_name = "Custom SA for VM Instance"
85+
}
86+
87+
88+
resource "google_sql_database_instance" "instance" {
89+
name = "default-%{random_suffix}"
90+
database_version = "MYSQL_8_0"
91+
region = "us-central1"
92+
deletion_protection = false
93+
settings {
94+
tier = "db-f1-micro"
95+
availability_type = "ZONAL"
96+
activation_policy = "ALWAYS"
97+
}
98+
}
99+
100+
101+
resource "google_backup_dr_backup_vault" "my-backup-vault" {
102+
location ="us-central1"
103+
backup_vault_id = "tf-test-bv-%{random_suffix}"
104+
description = "This is a second backup vault built by Terraform."
105+
backup_minimum_enforced_retention_duration = "100000s"
106+
labels = {
107+
foo = "bar1"
108+
bar = "baz1"
109+
}
110+
annotations = {
111+
annotations1 = "bar1"
112+
annotations2 = "baz1"
113+
}
114+
force_update = "true"
115+
force_delete = "true"
116+
allow_missing = "true"
117+
}
118+
119+
120+
resource "google_backup_dr_backup_plan" "foo" {
121+
location = "us-central1"
122+
backup_plan_id = "tf-test-bp-test-%{random_suffix}"
123+
resource_type = "sqladmin.googleapis.com/Instance"
124+
backup_vault = google_backup_dr_backup_vault.my-backup-vault.name
125+
126+
127+
backup_rules {
128+
rule_id = "rule-1"
129+
backup_retention_days = 2
130+
131+
132+
standard_schedule {
133+
recurrence_type = "HOURLY"
134+
hourly_frequency = 6
135+
time_zone = "UTC"
136+
137+
138+
backup_window {
139+
start_hour_of_day = 12
140+
end_hour_of_day = 18
141+
}
142+
}
143+
}
144+
}
145+
146+
147+
resource "google_backup_dr_backup_plan_association" "bpa" {
148+
location = "us-central1"
149+
backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}"
150+
resource = "projects/${data.google_project.project.project_id}/instances/${google_sql_database_instance.instance.name}"
151+
resource_type= "sqladmin.googleapis.com/Instance"
152+
backup_plan = google_backup_dr_backup_plan.foo.name
153+
depends_on = [ google_sql_database_instance.instance ]
154+
}
155+
156+
157+
data "google_backup_dr_data_source_references" "default" {
158+
project = data.google_project.project.project_id
159+
location = "%{location}"
160+
resource_type = "%{resource_type}"
161+
depends_on= [ google_backup_dr_backup_plan_association.bpa ]
162+
}
163+
`, context)
164+
}

0 commit comments

Comments
 (0)