Skip to content
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

Add data source for retrieving organization iam custom roles #13304

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ var handwrittenDatasources = map[string]*schema.Resource{
"google_oracle_database_cloud_vm_cluster": oracledatabase.DataSourceOracleDatabaseCloudVmCluster(),
"google_organization": resourcemanager.DataSourceGoogleOrganization(),
"google_organizations": resourcemanager.DataSourceGoogleOrganizations(),
"google_organization_iam_custom_roles": resourcemanager.DataSourceGoogleOrganizationIamCustomRoles(),
{{- if ne $.TargetVersionName "ga" }}
"google_parameter_manager_parameter": parametermanager.DataSourceParameterManagerParameter(),
"google_parameter_manager_parameters": parametermanager.DataSourceParameterManagerParameters(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package resourcemanager

import (
"context"
"fmt"
"path"

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

func DataSourceGoogleOrganizationIamCustomRoles() *schema.Resource {
return &schema.Resource{
Read: dataSourceOrganizationIamCustomRoleRead,
Schema: map[string]*schema.Schema{
"org_id": {
Type: schema.TypeString,
Optional: true,
},
"show_deleted": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"view": {
Type: schema.TypeString,
Optional: true,
Default: "BASIC",
ValidateFunc: validateView,
},
"roles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"deleted": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"permissions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"role_id": {
Type: schema.TypeString,
Computed: true,
},
"stage": {
Type: schema.TypeString,
Computed: true,
},
"title": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}

func validateView(val interface{}, key string) ([]string, []error) {
v := val.(string)
var errs []error

if v != "BASIC" && v != "FULL" {
errs = append(errs, fmt.Errorf("%q must be either 'BASIC' or 'FULL', got %q", key, v))
}

return nil, errs
}

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

orgId := d.Get("org_id").(string)

roles := make([]map[string]interface{}, 0)

showDeleted := d.Get("show_deleted").(bool)
view := d.Get("view").(string)

request := config.NewIamClient(userAgent).Organizations.Roles.List("organizations/" + orgId).ShowDeleted(showDeleted).View(view)

err = request.Pages(context.Background(), func(roleList *iam.ListRolesResponse) error {
for _, role := range roleList.Roles {
var permissions []string

switch view {
case "BASIC":
permissions = []string{}
case "FULL":
permissions = role.IncludedPermissions
default:
return fmt.Errorf("Unsupported view type: %s", view)
}

roles = append(roles, map[string]interface{}{
"deleted": role.Deleted,
"description": role.Description,
"id": role.Name,
"name": role.Name,
"permissions": permissions,
"role_id": path.Base(role.Name),
"stage": role.Stage,
"title": role.Title,
})
}
return nil
})

if err != nil {
return fmt.Errorf("Error retrieving organization custom roles: %s", err)
}

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

d.SetId("organizations/" + orgId)

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package resourcemanager_test

import (
"fmt"
"testing"

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

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

orgId := envvar.GetTestOrgFromEnv(t)
roleId := "tfIamCustomRole" + acctest.RandString(t, 10)

acctest.VcrTest(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
Steps: []resource.TestStep{
{
Config: testAccCheckGoogleOrganizationIamCustomRolesConfig(orgId, roleId),
Check: resource.ComposeTestCheckFunc(
// We can't guarantee no organization won't have our custom role as first element, so we'll check set-ness rather than correctness
resource.TestCheckResourceAttrSet("data.google_organization_iam_custom_roles.this", "roles.0.id"),
resource.TestCheckResourceAttrSet("data.google_organization_iam_custom_roles.this", "roles.0.name"),
resource.TestCheckResourceAttrSet("data.google_organization_iam_custom_roles.this", "roles.0.role_id"),
resource.TestCheckResourceAttrSet("data.google_organization_iam_custom_roles.this", "roles.0.stage"),
resource.TestCheckResourceAttrSet("data.google_organization_iam_custom_roles.this", "roles.0.title"),
),
},
},
})
}

func testAccCheckGoogleOrganizationIamCustomRolesConfig(orgId string, roleId string) string {
return fmt.Sprintf(`
locals {
org_id = "%s"
role_id = "%s"
}
resource "google_organization_iam_custom_role" "this" {
org_id = local.org_id
role_id = local.role_id
title = "Terraform Test"
permissions = [
"iam.roles.create",
"iam.roles.delete",
"iam.roles.list",
]
}
data "google_organization_iam_custom_roles" "this" {
org_id = google_organization_iam_custom_role.this.org_id
}
`, orgId, roleId)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
subcategory: "Cloud Platform"
description: |-
Get information about a Google Cloud Organization IAM Custom Roles.
---

# google_organization_iam_custom_roles

Get information about a Google Cloud Organization IAM Custom Roles.
Note that you must have the `roles/iam.organizationRoleViewer`.
See [the official documentation](https://cloud.google.com/iam/docs/creating-custom-roles)
and [API](https://cloud.google.com/iam/docs/reference/rest/v1/organizations.roles/list).

```hcl
data "google_organization_iam_custom_roles" "example" {
org_id = "1234567890"
show_deleted = true
view = "FULL"
}
```

## Argument Reference

The following arguments are supported:

* `org_id` - (Required) The numeric ID of the organization.

* `show_deleted` - (Optional) Include Roles that have been deleted. Defaults to `false`.

* `view` - (Optional) When `"FULL"` is specified, the `permissions` field is returned, which includes a list of all permissions in the role. The default value is `"BASIC"`, which does not return the `permissions`.

## Attributes Reference

The following attributes are exported:

* `roles` - A list of all retrieved custom roles roles. Structure is [defined below](#nested_roles).

<a name="nested_roles"></a>The `roles` block supports:

* `deleted` - The current deleted state of the role.

* `description` - A human-readable description for the role.

* `id` - an identifier for the resource with the format `organizations/{{org_id}}/roles/{{role_id}}`.

* `name` - The name of the role in the format `organizations/{{org_id}}/roles/{{role_id}}`. Like `id`, this field can be used as a reference in other resources such as IAM role bindings.

* `permissions` - The names of the permissions this role grants when bound in an IAM policy.

* `role_id` - The camel case role id used for this role.

* `stage` - The current launch stage of the role. List of possible stages is [here](https://cloud.google.com/iam/reference/rest/v1/organizations.roles#Role.RoleLaunchStage).

* `title` - A human-readable title for the role.
Loading