Skip to content

Commit 2235055

Browse files
API implementation for fetch Resource Type of data source references (#15048)
1 parent 158793f commit 2235055

File tree

4 files changed

+376
-0
lines changed

4 files changed

+376
-0
lines changed

mmv1/third_party/terraform/provider/provider_mmv1_resources.go.tmpl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ var handwrittenDatasources = map[string]*schema.Resource{
4747
"google_backup_dr_backup": backupdr.DataSourceGoogleCloudBackupDRBackup(),
4848
"google_backup_dr_data_source": backupdr.DataSourceGoogleCloudBackupDRDataSource(),
4949
"google_backup_dr_backup_vault": backupdr.DataSourceGoogleCloudBackupDRBackupVault(),
50+
"google_backup_dr_data_source_references": backupdr.DataSourceGoogleCloudBackupDRDataSourceReferences(),
5051
"google_beyondcorp_app_connection": beyondcorp.DataSourceGoogleBeyondcorpAppConnection(),
5152
"google_beyondcorp_app_connector": beyondcorp.DataSourceGoogleBeyondcorpAppConnector(),
5253
"google_beyondcorp_app_gateway": beyondcorp.DataSourceGoogleBeyondcorpAppGateway(),
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
package backupdr
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
7+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
8+
"github.com/hashicorp/terraform-provider-google/google/tpgresource"
9+
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
10+
)
11+
12+
func DataSourceGoogleCloudBackupDRDataSourceReferences() *schema.Resource {
13+
return &schema.Resource{
14+
Read: dataSourceGoogleCloudBackupDRDataSourceReferencesRead,
15+
Schema: map[string]*schema.Schema{
16+
"location": {
17+
Type: schema.TypeString,
18+
Required: true,
19+
Description: "The location to list the data source references from.",
20+
},
21+
"project": {
22+
Type: schema.TypeString,
23+
Optional: true,
24+
Computed: true,
25+
Description: "The ID of the project in which the resource belongs.",
26+
},
27+
"resource_type": {
28+
Type: schema.TypeString,
29+
Required: true,
30+
Description: `The resource type to get the data source references for. Examples include, "compute.googleapis.com/Instance", "sqladmin.googleapis.com/Instance".`,
31+
},
32+
33+
// Output: a computed list of the data source references found
34+
"data_source_references": {
35+
Type: schema.TypeList,
36+
Computed: true,
37+
Description: "A list of the data source references found.",
38+
Elem: &schema.Resource{
39+
Schema: map[string]*schema.Schema{
40+
"name": {
41+
Type: schema.TypeString,
42+
Computed: true,
43+
},
44+
"data_source": {
45+
Type: schema.TypeString,
46+
Computed: true,
47+
Description: "The underlying data source resource.",
48+
},
49+
"gcp_resource_name": {
50+
Type: schema.TypeString,
51+
Computed: true,
52+
Description: "The GCP resource name for the data source.",
53+
},
54+
"backup_config_state": {
55+
Type: schema.TypeString,
56+
Computed: true,
57+
Description: "The state of the backup config for the data source.",
58+
},
59+
"backup_count": {
60+
Type: schema.TypeInt,
61+
Computed: true,
62+
Description: "The number of backups for the data source.",
63+
},
64+
"last_backup_state": {
65+
Type: schema.TypeString,
66+
Computed: true,
67+
Description: "The state of the last backup.",
68+
},
69+
"last_successful_backup_time": {
70+
Type: schema.TypeString,
71+
Computed: true,
72+
Description: "The last time a successful backup was made.",
73+
},
74+
"resource_type": {
75+
Type: schema.TypeString,
76+
Computed: true,
77+
},
78+
},
79+
},
80+
},
81+
},
82+
}
83+
}
84+
85+
func dataSourceGoogleCloudBackupDRDataSourceReferencesRead(d *schema.ResourceData, meta interface{}) error {
86+
config := meta.(*transport_tpg.Config)
87+
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
88+
if err != nil {
89+
return err
90+
}
91+
92+
project, err := tpgresource.GetProject(d, config)
93+
if err != nil {
94+
return err
95+
}
96+
97+
location := d.Get("location").(string)
98+
resourceType := d.Get("resource_type").(string)
99+
100+
url := fmt.Sprintf("%sprojects/%s/locations/%s/dataSourceReferences:fetchForResourceType?resourceType=%s", config.BackupDRBasePath, project, location, resourceType)
101+
102+
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
103+
Config: config,
104+
Method: "GET",
105+
Project: project,
106+
RawURL: url,
107+
UserAgent: userAgent,
108+
})
109+
if err != nil {
110+
return fmt.Errorf("Error reading DataSourceReferences: %s", err)
111+
}
112+
113+
items, ok := res["dataSourceReferences"].([]interface{})
114+
if !ok {
115+
items = make([]interface{}, 0)
116+
}
117+
118+
flattenedDataSourceReferences, err := flattenDataSourceReferences(items)
119+
if err != nil {
120+
return err
121+
}
122+
123+
if err := d.Set("data_source_references", flattenedDataSourceReferences); err != nil {
124+
return fmt.Errorf("Error setting data_source_references: %s", err)
125+
}
126+
127+
d.SetId(url)
128+
129+
return nil
130+
}
131+
132+
func flattenDataSourceReferences(items []interface{}) ([]map[string]interface{}, error) {
133+
references := make([]map[string]interface{}, 0, len(items))
134+
for _, item := range items {
135+
data, ok := item.(map[string]interface{})
136+
if !ok {
137+
return nil, fmt.Errorf("cannot cast item to map[string]interface{}")
138+
}
139+
140+
ref := map[string]interface{}{
141+
"name": data["name"],
142+
"data_source": data["dataSource"],
143+
"backup_config_state": data["dataSourceBackupConfigState"],
144+
}
145+
146+
// The API returns backup count as a string, so we parse it to an integer.
147+
if v, ok := data["dataSourceBackupCount"].(string); ok {
148+
if i, err := strconv.Atoi(v); err == nil {
149+
ref["backup_count"] = i
150+
}
151+
}
152+
153+
// Flatten the nested dataSourceBackupConfigInfo object.
154+
if configInfo, ok := data["dataSourceBackupConfigInfo"].(map[string]interface{}); ok {
155+
ref["last_backup_state"] = configInfo["lastBackupState"]
156+
ref["last_successful_backup_time"] = configInfo["lastSuccessfulBackupConsistencyTime"]
157+
}
158+
159+
if resourceInfo, ok := data["dataSourceGcpResourceInfo"].(map[string]interface{}); ok {
160+
ref["gcp_resource_name"] = resourceInfo["gcpResourcename"]
161+
ref["resource_type"] = resourceInfo["type"]
162+
}
163+
164+
references = append(references, ref)
165+
}
166+
return references, nil
167+
}
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
package backupdr_test
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
8+
"github.com/hashicorp/terraform-plugin-testing/terraform"
9+
"github.com/hashicorp/terraform-provider-google/google/acctest"
10+
)
11+
12+
func TestAccDataSourceGoogleBackupDRDataSourceReferences_basic(t *testing.T) {
13+
t.Parallel()
14+
15+
projectDsName := "data.google_project.project"
16+
var projectID string
17+
context := map[string]interface{}{
18+
"location": "us-central1",
19+
"resource_type": "sqladmin.googleapis.com/Instance",
20+
"random_suffix": acctest.RandString(t, 10),
21+
}
22+
23+
acctest.VcrTest(t, resource.TestCase{
24+
PreCheck: func() { acctest.AccTestPreCheck(t) },
25+
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
26+
Steps: []resource.TestStep{
27+
{
28+
Config: testAccDataSourceGoogleBackupDRDataSourceReferences_basic(context),
29+
Check: func(s *terraform.State) error {
30+
// Extract project ID from the project data source in the state
31+
project, ok := s.RootModule().Resources[projectDsName]
32+
if !ok {
33+
return fmt.Errorf("project data source not found: %s", projectDsName)
34+
}
35+
projectID = project.Primary.Attributes["project_id"]
36+
37+
return resource.ComposeTestCheckFunc(
38+
// Basic attribute checks
39+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "project", projectID),
40+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "location", context["location"].(string)),
41+
resource.TestCheckResourceAttr("data.google_backup_dr_data_source_references.default", "resource_type", context["resource_type"].(string)),
42+
43+
// Check that the list itself is populated
44+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.#"),
45+
46+
// Checks for existing and new fields within the list
47+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.name"),
48+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.data_source"),
49+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.backup_config_state"),
50+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.gcp_resource_name"),
51+
resource.TestCheckResourceAttrSet("data.google_backup_dr_data_source_references.default", "data_source_references.0.resource_type"),
52+
)(s)
53+
},
54+
},
55+
},
56+
})
57+
}
58+
59+
func testAccDataSourceGoogleBackupDRDataSourceReferences_basic(context map[string]interface{}) string {
60+
return acctest.Nprintf(`
61+
62+
63+
data "google_project" "project" {}
64+
65+
66+
resource "google_service_account" "default" {
67+
account_id = "tf-test-my-custom-%{random_suffix}"
68+
display_name = "Custom SA for VM Instance"
69+
}
70+
71+
72+
resource "google_sql_database_instance" "instance" {
73+
name = "default-%{random_suffix}"
74+
database_version = "MYSQL_8_0"
75+
region = "us-central1"
76+
deletion_protection = false
77+
settings {
78+
tier = "db-f1-micro"
79+
availability_type = "ZONAL"
80+
activation_policy = "ALWAYS"
81+
}
82+
}
83+
84+
85+
resource "google_backup_dr_backup_vault" "my-backup-vault" {
86+
location ="us-central1"
87+
backup_vault_id = "tf-test-bv-%{random_suffix}"
88+
description = "This is a second backup vault built by Terraform."
89+
backup_minimum_enforced_retention_duration = "100000s"
90+
labels = {
91+
foo = "bar1"
92+
bar = "baz1"
93+
}
94+
annotations = {
95+
annotations1 = "bar1"
96+
annotations2 = "baz1"
97+
}
98+
force_update = "true"
99+
force_delete = "true"
100+
allow_missing = "true"
101+
}
102+
103+
104+
resource "google_backup_dr_backup_plan" "foo" {
105+
location = "us-central1"
106+
backup_plan_id = "tf-test-bp-test-%{random_suffix}"
107+
resource_type = "sqladmin.googleapis.com/Instance"
108+
backup_vault = google_backup_dr_backup_vault.my-backup-vault.name
109+
110+
111+
backup_rules {
112+
rule_id = "rule-1"
113+
backup_retention_days = 2
114+
115+
116+
standard_schedule {
117+
recurrence_type = "HOURLY"
118+
hourly_frequency = 6
119+
time_zone = "UTC"
120+
121+
122+
backup_window {
123+
start_hour_of_day = 12
124+
end_hour_of_day = 18
125+
}
126+
}
127+
}
128+
}
129+
130+
131+
resource "google_backup_dr_backup_plan_association" "bpa" {
132+
location = "us-central1"
133+
backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}"
134+
resource = "projects/${data.google_project.project.project_id}/instances/${google_sql_database_instance.instance.name}"
135+
resource_type= "sqladmin.googleapis.com/Instance"
136+
backup_plan = google_backup_dr_backup_plan.foo.name
137+
depends_on = [ google_sql_database_instance.instance ]
138+
}
139+
140+
141+
data "google_backup_dr_data_source_references" "default" {
142+
project = data.google_project.project.project_id
143+
location = "%{location}"
144+
resource_type = "%{resource_type}"
145+
depends_on= [ google_backup_dr_backup_plan_association.bpa ]
146+
}
147+
`, context)
148+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
subcategory: "Backup and DR Service"
3+
description: |-
4+
Get information about Backup and DR data source references.
5+
---
6+
7+
# google_backup_dr_data_source_references
8+
9+
A list of Backup and DR data source references.
10+
11+
~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider.
12+
See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources.
13+
14+
## Example Usage
15+
16+
```hcl
17+
data "google_backup_dr_data_source_references" "my_sql_references" {
18+
location = "us-central1"
19+
resource_type = "sqladmin.googleapis.com/Instance"
20+
}
21+
22+
output "first_sql_reference_name" {
23+
name = data.google_backup_dr_data_source_references.my_sql_references.data_source_references[0].name
24+
}
25+
```
26+
27+
## Argument Reference
28+
29+
The following arguments are supported:
30+
31+
* `location `- (Required) The location of the data source references.
32+
33+
* `resource_type` - (Required) The resource type to get the data source references for. Examples include, "sqladmin.googleapis.com/Instance" , "compute.googleapis.com/Instance" (right now this service not available for compute Instances , it will be added soon )
34+
35+
* `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used.
36+
37+
38+
## Attributes Reference
39+
40+
In addition to the arguments listed above, the following attributes are exported:
41+
42+
* data\_source\_references - A list of the data source references found. Each element of this list has the following attributes:
43+
44+
1. `name`- The full name of the data source reference.
45+
46+
2. `data_source`- The underlying data source resource.
47+
48+
3. `backup_config_state`- The state of the backup config for the data source.
49+
50+
4. `backup_count`- The number of backups for the data source.
51+
52+
5. `last_backup_state`- The state of the last backup.
53+
54+
6. `last_successful_backup_time`- The last time a successful backup was made.
55+
56+
7. `gcp_resource_name`- The GCP resource name for the data source.
57+
58+
8. `resource_type`- The type of the referenced resource.
59+
60+
See [google_backup_dr_data_source_references](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/backup_dr_data_source_references) resource for details of the available attributes.

0 commit comments

Comments
 (0)