Skip to content

Commit

Permalink
add role resource
Browse files Browse the repository at this point in the history
  • Loading branch information
zippolyte committed Nov 17, 2020
1 parent fe619a6 commit 1dec8cd
Show file tree
Hide file tree
Showing 3 changed files with 235 additions and 0 deletions.
1 change: 1 addition & 0 deletions datadog/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func Provider() terraform.ResourceProvider {
"datadog_logs_pipeline_order": resourceDatadogLogsPipelineOrder(),
"datadog_metric_metadata": resourceDatadogMetricMetadata(),
"datadog_monitor": resourceDatadogMonitor(),
"datadog_role": resourceDatadogRole(),
"datadog_screenboard": resourceDatadogScreenboard(),
"datadog_service_level_objective": resourceDatadogServiceLevelObjective(),
"datadog_synthetics_test": resourceDatadogSyntheticsTest(),
Expand Down
193 changes: 193 additions & 0 deletions datadog/resource_datadog_role.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package datadog

import (
"github.com/DataDog/datadog-api-client-go/api/v2/datadog"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceDatadogRole() *schema.Resource {
return &schema.Resource{
Exists: resourceDatadogRoleExists,
Create: resourceDatadogRoleCreate,
Read: resourceDatadogRoleRead,
Update: resourceDatadogRoleUpdate,
Delete: resourceDatadogRoleDelete,
Importer: &schema.ResourceImporter{
State: resourceDatadogRoleImport,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the role.",
},
"permissions": {
Type: schema.TypeSet,
Optional: true,
Description: "List of permission IDs to give to this role.",
Elem: &schema.Schema{Type: schema.TypeString},
},
"user_count": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of users that have this role.",
},
},
}
}

func resourceDatadogRoleExists(d *schema.ResourceData, meta interface{}) (bool, error) {
client := meta.(*ProviderConfiguration).DatadogClientV2
auth := meta.(*ProviderConfiguration).AuthV2
_, httpresp, err := client.RolesApi.GetRole(auth, d.Id()).Execute()
if err != nil {
if httpresp.StatusCode == 404 {
return false, nil
}
return false, translateClientError(err, "error checking if role exists")
}
return true, nil
}

func resourceDatadogRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfiguration).DatadogClientV2
auth := meta.(*ProviderConfiguration).AuthV2

roleReq := buildRoleCreateRequest(d)
resp, _, err := client.RolesApi.CreateRole(auth).Body(roleReq).Execute()
if err != nil {
return translateClientError(err, "error creating role")
}
roleData := resp.GetData()
d.SetId(roleData.GetId())

return resourceDatadogRoleRead(d, meta)
}

func resourceDatadogRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfiguration).DatadogClientV2
auth := meta.(*ProviderConfiguration).AuthV2
resp, _, err := client.RolesApi.GetRole(auth, d.Id()).Execute()
if err != nil {
return translateClientError(err, "error getting role")
}
roleData := resp.GetData()
roleAttrs := roleData.GetAttributes()
d.Set("user_count", roleAttrs.GetUserCount())
d.Set("name", roleAttrs.GetName())

roleRelations := roleData.GetRelationships()
rolePerms := roleRelations.GetPermissions()
rolePermsData := rolePerms.GetData()
perms := make([]string, len(rolePermsData))
for i, perm := range rolePermsData {
perms[i] = perm.GetId()
}
d.Set("permissions", perms)

return nil
}

func resourceDatadogRoleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfiguration).DatadogClientV2
auth := meta.(*ProviderConfiguration).AuthV2

if d.HasChange("name") {
roleReq := buildRoleUpdateRequest(d)
_, _, err := client.RolesApi.UpdateRole(auth, d.Id()).Body(roleReq).Execute()
if err != nil {
return translateClientError(err, "error updating role")
}
}
if d.HasChange("permissions") {
oldPermsI, newPermsI := d.GetChange("permissions")
oldPerms := oldPermsI.(*schema.Set)
newPerms := newPermsI.(*schema.Set)
permsToRemove := oldPerms.Difference(newPerms)
permsToAdd := newPerms.Difference(oldPerms)
for _, permI := range permsToRemove.List() {
permRelation := datadog.NewRelationshipToPermissionWithDefaults()
permRelationData := datadog.NewRelationshipToPermissionDataWithDefaults()
permRelationData.SetId(permI.(string))
permRelation.SetData(*permRelationData)
_, _, err := client.RolesApi.RemovePermissionFromRole(auth, d.Id()).Body(*permRelation).Execute()
if err != nil {
return translateClientError(err, "error removing permission from role")
}
}
for _, permI := range permsToAdd.List() {
permRelation := datadog.NewRelationshipToPermissionWithDefaults()
permRelationData := datadog.NewRelationshipToPermissionDataWithDefaults()
permRelationData.SetId(permI.(string))
permRelation.SetData(*permRelationData)
_, _, err := client.RolesApi.AddPermissionToRole(auth, d.Id()).Body(*permRelation).Execute()
if err != nil {
return translateClientError(err, "error adding permission to role")
}
}
}

return resourceDatadogRoleRead(d, meta)
}

func resourceDatadogRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfiguration).DatadogClientV2
auth := meta.(*ProviderConfiguration).AuthV2

_, err := client.RolesApi.DeleteRole(auth, d.Id()).Execute()
if err != nil {
return translateClientError(err, "error deleting role")
}

return nil
}

func resourceDatadogRoleImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
if err := resourceDatadogRoleRead(d, meta); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}

func buildRoleCreateRequest(d *schema.ResourceData) datadog.RoleCreateRequest {
roleCreateRequest := datadog.NewRoleCreateRequestWithDefaults()
roleCreateData := datadog.NewRoleCreateDataWithDefaults()
roleCreateAttrs := datadog.NewRoleCreateAttributesWithDefaults()
roleCreateRelations := datadog.NewRoleRelationshipsWithDefaults()

// Set attributes
roleCreateAttrs.SetName(d.Get("name").(string))
roleCreateData.SetAttributes(*roleCreateAttrs)

// Set permission relationships
if permsI, ok := d.GetOk("permissions"); ok {
perms := permsI.([]string)
rolePermRelations := datadog.NewRelationshipToPermissionsWithDefaults()
rolePermRelationsData := make([]datadog.RelationshipToPermissionData, len(perms))
for i, perm := range perms {
roleRelationshipToPerm := datadog.NewRelationshipToPermissionDataWithDefaults()
roleRelationshipToPerm.SetId(perm)
rolePermRelationsData[i] = *roleRelationshipToPerm
}
rolePermRelations.SetData(rolePermRelationsData)
roleCreateRelations.SetPermissions(*rolePermRelations)
}
roleCreateData.SetRelationships(*roleCreateRelations)

roleCreateRequest.SetData(*roleCreateData)
return *roleCreateRequest
}

func buildRoleUpdateRequest(d *schema.ResourceData) datadog.RoleUpdateRequest {
roleUpdateRequest := datadog.NewRoleUpdateRequestWithDefaults()
roleUpdateData := datadog.NewRoleUpdateDataWithDefaults()
roleUpdateAttributes := datadog.NewRoleUpdateAttributesWithDefaults()

roleUpdateAttributes.SetName(d.Get("name").(string))

roleUpdateData.SetId(d.Id())
roleUpdateData.SetAttributes(*roleUpdateAttributes)

roleUpdateRequest.SetData(*roleUpdateData)
return *roleUpdateRequest
}
41 changes: 41 additions & 0 deletions docs/resources/role.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
page_title: "datadog_role"
---

# datadog_role Resource

Provides a Datadog role resource. This can be used to create and manage Datadog roles.

## Example Usage

```hcl
# Create a new Datadog role
resource "datadog_role" "foo" {
name = "foo"
permissions = [
"${data.datadog_permissions.example_permission_1.id}",
"${data.datadog_permissions.example_permission_2.id}"
]
}
```

## Argument Reference

The following arguments are supported:

- `name`: (Required) The name of the role to create.
- `permissions`: (Optional) A list of permission IDs to grant to the role.

## Attributes Reference

The following attributes are exported:

- `user_count`: The number of users that have this role.

## Import

Roles can be imported using their ID, e.g.

```
$ terraform import datadog_role.example_role 000000-0000-0000-0000-000000000000
```

0 comments on commit 1dec8cd

Please sign in to comment.