Skip to content

Add data source for retrieving the ancestors for a project #9326

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/13029.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-datasource
`google_project_ancestry`
```
1 change: 1 addition & 0 deletions google-beta/provider/provider_mmv1_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ var handwrittenDatasources = map[string]*schema.Resource{
"google_privileged_access_manager_entitlement": privilegedaccessmanager.DataSourceGooglePrivilegedAccessManagerEntitlement(),
"google_project": resourcemanager.DataSourceGoogleProject(),
"google_projects": resourcemanager.DataSourceGoogleProjects(),
"google_project_ancestry": resourcemanager.DataSourceGoogleProjectAncestry(),
"google_project_organization_policy": resourcemanager.DataSourceGoogleProjectOrganizationPolicy(),
"google_project_service": resourcemanager.DataSourceGoogleProjectService(),
"google_pubsub_subscription": pubsub.DataSourceGooglePubsubSubscription(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package resourcemanager

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
"google.golang.org/api/cloudresourcemanager/v1"
)

func DataSourceGoogleProjectAncestry() *schema.Resource {
return &schema.Resource{
Read: datasourceGoogleProjectAncestryRead,
Schema: map[string]*schema.Schema{
"ancestors": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"org_id": {
Type: schema.TypeString,
Computed: true,
},
"parent_id": {
Type: schema.TypeString,
Computed: true,
},
"parent_type": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
},
},
}
}

func datasourceGoogleProjectAncestryRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}

project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for ancestry: %s", err)
}

request := &cloudresourcemanager.GetAncestryRequest{}
response, err := config.NewResourceManagerClient(userAgent).Projects.GetAncestry(project, request).Context(context.Background()).Do()
if err != nil {
return fmt.Errorf("Error retrieving project ancestry: %s", err)
}

ancestors := make([]map[string]interface{}, 0)
var orgID string
var parentID string
var parentType string

for _, a := range response.Ancestor {
if a.ResourceId == nil {
continue
}

ancestorData := map[string]interface{}{
"id": a.ResourceId.Id,
"type": a.ResourceId.Type,
}

ancestors = append(ancestors, ancestorData)

if a.ResourceId.Type == "organization" {
orgID = a.ResourceId.Id
}
}

if err := d.Set("ancestors", ancestors); err != nil {
return fmt.Errorf("Error setting ancestors: %s", err)
}

if err := d.Set("org_id", orgID); err != nil {
return fmt.Errorf("Error setting org_id: %s", err)
}

if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error setting project: %s", err)
}

if len(ancestors) > 1 {
parent := ancestors[1]
if id, ok := parent["id"].(string); ok {
parentID = id
}
if pType, ok := parent["type"].(string); ok {
parentType = pType
}

if err := d.Set("parent_id", parentID); err != nil {
return fmt.Errorf("Error setting parent_id: %s", err)
}

if err := d.Set("parent_type", parentType); err != nil {
return fmt.Errorf("Error setting parent_type: %s", err)
}
}

d.SetId(fmt.Sprintf("projects/%s", project))

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package resourcemanager_test

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar"
)

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

// Common resource configuration
staticPrefix := "tf-test-"
randomSuffix := "-" + acctest.RandString(t, 10)
orgID := envvar.GetTestOrgFromEnv(t)

// Configuration of resources
folderThanos := staticPrefix + "thanos" + randomSuffix
folderLoki := staticPrefix + "loki" + randomSuffix
folderUltron := staticPrefix + "ultron" + randomSuffix
projectThor := staticPrefix + "thor" + randomSuffix
projectIronMan := staticPrefix + "ironman" + randomSuffix
projectCap := staticPrefix + "cap" + randomSuffix
projectHulk := staticPrefix + "hulk" + randomSuffix

// Configuration map used in test deployment
context := map[string]interface{}{
"org_id": orgID,
"folder_thanos": folderThanos,
"folder_loki": folderLoki,
"folder_ultron": folderUltron,
"project_thor": projectThor,
"project_ironman": projectIronMan,
"project_cap": projectCap,
"project_hulk": projectHulk,
}

acctest.VcrTest(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
Steps: []resource.TestStep{
{
Config: testAccCheckGoogleProjectAncestryConfig(context),
Check: resource.ComposeTestCheckFunc(
// Project thor under organization
resource.TestCheckResourceAttr("data.google_project_ancestry.thor", "ancestors.#", "2"),
resource.TestCheckResourceAttr("data.google_project_ancestry.thor", "ancestors.0.type", "project"),
resource.TestCheckResourceAttr("data.google_project_ancestry.thor", "ancestors.1.type", "organization"),

// Project ironman under organization and thanos
resource.TestCheckResourceAttr("data.google_project_ancestry.ironman", "ancestors.#", "3"),
resource.TestCheckResourceAttr("data.google_project_ancestry.ironman", "ancestors.0.type", "project"),
resource.TestCheckResourceAttr("data.google_project_ancestry.ironman", "ancestors.1.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.ironman", "ancestors.2.type", "organization"),

// Project cap under organization, thanos and loki
resource.TestCheckResourceAttr("data.google_project_ancestry.cap", "ancestors.#", "4"),
resource.TestCheckResourceAttr("data.google_project_ancestry.cap", "ancestors.0.type", "project"),
resource.TestCheckResourceAttr("data.google_project_ancestry.cap", "ancestors.1.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.cap", "ancestors.2.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.cap", "ancestors.3.type", "organization"),

// Project hulk under organization, thanos, loki and ultron
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.#", "5"),
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.0.type", "project"),
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.1.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.2.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.3.type", "folder"),
resource.TestCheckResourceAttr("data.google_project_ancestry.hulk", "ancestors.4.type", "organization"),
),
},
},
})
}

func testAccCheckGoogleProjectAncestryConfig(context map[string]interface{}) string {
return fmt.Sprintf(`
locals {
org_id = "%s"
folder_thanos = "%s"
folder_loki = "%s"
folder_ultron = "%s"
project_thor = "%s"
project_ironman = "%s"
project_cap = "%s"
project_hulk = "%s"
}

resource "google_folder" "thanos" {
deletion_protection = false
display_name = local.folder_thanos
parent = "organizations/${local.org_id}"
}

resource "google_folder" "loki" {
deletion_protection = false
display_name = local.folder_loki
parent = google_folder.thanos.name
}

resource "google_folder" "ultron" {
deletion_protection = false
display_name = local.folder_ultron
parent = google_folder.loki.name
}

resource "google_project" "thor" {
deletion_policy = "DELETE"
name = local.project_thor
org_id = local.org_id
project_id = local.project_thor
}

resource "google_project" "ironman" {
deletion_policy = "DELETE"
folder_id = google_folder.thanos.id
name = local.project_ironman
project_id = local.project_ironman
}

resource "google_project" "cap" {
deletion_policy = "DELETE"
folder_id = google_folder.loki.id
name = local.project_cap
project_id = local.project_cap
}

resource "google_project" "hulk" {
deletion_policy = "DELETE"
folder_id = google_folder.ultron.id
name = local.project_hulk
project_id = local.project_hulk
}

data "google_project_ancestry" "thor" {
project = google_project.thor.project_id
}

data "google_project_ancestry" "ironman" {
project = google_project.ironman.project_id
}

data "google_project_ancestry" "cap" {
project = google_project.cap.project_id
}

data "google_project_ancestry" "hulk" {
project = google_project.hulk.project_id
}
`,
context["org_id"].(string),
context["folder_thanos"].(string),
context["folder_loki"].(string),
context["folder_ultron"].(string),
context["project_thor"].(string),
context["project_ironman"].(string),
context["project_cap"].(string),
context["project_hulk"].(string),
)
}
41 changes: 41 additions & 0 deletions website/docs/d/project_ancestry.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
subcategory: "Cloud Platform"
description: |-
Retrieve the ancestors for a project.
---

# google_project_ancestry

Retrieve the ancestors for a project.
See the [REST API](https://cloud.google.com/resource-manager/reference/rest/v1/projects/getAncestry) for more details.

## Example Usage

```hcl
data "google_project_ancestry" "example" {
project_id = "example-project"
}
```

## Argument Reference

The following arguments are supported:

* `project` - (Optional) The ID of the project. If it is not provided, the provider project is used.

## Attributes Reference

The following attributes are exported:

* `ancestors` - A list of the project's ancestors. Structure is [defined below](#nested_ancestors).

<a name="nested_ancestors"></a>The `ancestors` block supports:

* `id` - If it's a project, the `project_id` is exported, else the numeric folder id or organization id.
* `type` - One of `"project"`, `"folder"` or `"organization"`.

---

* `org_id` - The optional user-assigned display name of the project.
* `parent_id` - The parent's id.
* `parent_type` - One of `"folder"` or `"organization"`.