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

feat: add role resource #7

Merged
merged 2 commits into from
Jul 2, 2020
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
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func New() terraform.ResourceProvider {
"watchtower_group": resourceGroup(),
"watchtower_host_catalog": resourceHostCatalog(),
"watchtower_project": resourceProject(),
"watchtower_role": resourceRole(),
"watchtower_user": resourceUser(),
},
}
Expand Down
172 changes: 172 additions & 0 deletions internal/provider/resource_role.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package provider

import (
"fmt"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/watchtower/api/roles"
"github.com/hashicorp/watchtower/api/scopes"
)

const (
roleNameKey = "name"
roleDescriptionKey = "description"
)

func resourceRole() *schema.Resource {
return &schema.Resource{
Create: resourceRoleCreate,
Read: resourceRoleRead,
Update: resourceRoleUpdate,
Delete: resourceRoleDelete,
Schema: map[string]*schema.Schema{
roleNameKey: {
Type: schema.TypeString,
Optional: true,
},
roleDescriptionKey: {
Type: schema.TypeString,
Optional: true,
},
},
}

}

// convertRoleToResourceData creates a ResourceData type from a Role
func convertRoleToResourceData(u *roles.Role, d *schema.ResourceData) error {
if u.Name != nil {
if err := d.Set(roleNameKey, u.Name); err != nil {
return err
}
}

if u.Description != nil {
if err := d.Set(roleDescriptionKey, u.Description); err != nil {
return err
}
}

d.SetId(u.Id)

return nil
}

// convertResourceDataToRole returns a localy built Role using the values provided in the ResourceData.
func convertResourceDataToRole(d *schema.ResourceData) *roles.Role {
u := &roles.Role{}
if descVal, ok := d.GetOk(roleDescriptionKey); ok {
desc := descVal.(string)
u.Description = &desc
}
if nameVal, ok := d.GetOk(roleNameKey); ok {
name := nameVal.(string)
u.Name = &name
}

if d.Id() != "" {
u.Id = d.Id()
}

return u
}

func resourceRoleCreate(d *schema.ResourceData, meta interface{}) error {
md := meta.(*metaData)
client := md.client
ctx := md.ctx

o := &scopes.Organization{
Client: client,
}

u := convertResourceDataToRole(d)

u, apiErr, err := o.CreateRole(ctx, u)
if err != nil {
return fmt.Errorf("error calling new role: %s", err.Error())
}
if apiErr != nil {
return fmt.Errorf("error creating role: %s", *apiErr.Message)
}

d.SetId(u.Id)

return nil
}

func resourceRoleRead(d *schema.ResourceData, meta interface{}) error {
md := meta.(*metaData)
client := md.client
ctx := md.ctx

o := &scopes.Organization{
Client: client,
}

u := convertResourceDataToRole(d)

u, apiErr, err := o.ReadRole(ctx, u)
if err != nil {
return fmt.Errorf("error reading role: %s", err.Error())
}
if apiErr != nil {
return fmt.Errorf("error reading role: %s", *apiErr.Message)
}

return convertRoleToResourceData(u, d)
}

func resourceRoleUpdate(d *schema.ResourceData, meta interface{}) error {
md := meta.(*metaData)
client := md.client
ctx := md.ctx

o := &scopes.Organization{
Client: client,
}

u := convertResourceDataToRole(d)

if d.HasChange(roleNameKey) {
n := d.Get(roleNameKey).(string)
u.Name = &n
}

if d.HasChange(roleDescriptionKey) {
d := d.Get(roleDescriptionKey).(string)
u.Description = &d
}

u, apiErr, err := o.UpdateRole(ctx, u)
if err != nil {
return err
}
if apiErr != nil {
return fmt.Errorf("error updating role: %s\n Invalid request fields: %v\n", *apiErr.Message, apiErr.Details.RequestFields)
}

return convertRoleToResourceData(u, d)
}

func resourceRoleDelete(d *schema.ResourceData, meta interface{}) error {
md := meta.(*metaData)
client := md.client
ctx := md.ctx

o := &scopes.Organization{
Client: client,
}

u := convertResourceDataToRole(d)

_, apiErr, err := o.DeleteRole(ctx, u)
if err != nil {
return fmt.Errorf("error deleting role: %s", err.Error())
}
if apiErr != nil {
return fmt.Errorf("error deleting role: %s", *apiErr.Message)
}

return nil
}
170 changes: 170 additions & 0 deletions internal/provider/resource_role_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package provider

import (
"errors"
"fmt"
"net/http"
"strings"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/hashicorp/watchtower/api/roles"
"github.com/hashicorp/watchtower/api/scopes"
"github.com/hashicorp/watchtower/testing/controller"
)

const (
fooRoleDescription = "bar"
fooRoleDescriptionUpdate = "foo bar"
)

var (
fooRole = fmt.Sprintf(`
resource "watchtower_role" "foo" {
name = "test"
description = "%s"
}`, fooRoleDescription)

fooRoleUpdate = fmt.Sprintf(`
resource "watchtower_role" "foo" {
name = "test"
description = "%s"
}`, fooRoleDescriptionUpdate)
)

func TestAccRole(t *testing.T) {
tc := controller.NewTestController(t, controller.WithDefaultOrgId("o_0000000000"))
defer tc.Shutdown()
url := tc.ApiAddrs()[0]

resource.Test(t, resource.TestCase{
Providers: testProviders,
CheckDestroy: testAccCheckRoleResourceDestroy(t),
Steps: []resource.TestStep{
{
// test create
Config: testConfig(url, fooRole),
Check: resource.ComposeTestCheckFunc(
testAccCheckRoleResourceExists("watchtower_role.foo"),
resource.TestCheckResourceAttr("watchtower_role.foo", roleDescriptionKey, fooRoleDescription),
resource.TestCheckResourceAttr("watchtower_role.foo", roleNameKey, "test"),
),
},
{
// test update
Config: testConfig(url, fooRoleUpdate),
Check: resource.ComposeTestCheckFunc(
testAccCheckRoleResourceExists("watchtower_role.foo"),
resource.TestCheckResourceAttr("watchtower_role.foo", roleDescriptionKey, fooRoleDescriptionUpdate),
),
},
{
// test destroy
Config: testConfig(url),
Check: resource.ComposeTestCheckFunc(
testAccCheckRoleDestroyed("watchtower_role.foo"),
),
},
},
})
}

// testAccCheckRoleDestroyed checks the terraform state for the host
// catalog and returns an error if found.
//
// TODO(malnick) This method falls short of checking the Watchtower API for
// the resource if the resource is not found in state. This is due to us not
// having the host catalog ID, but it doesn't guarantee that the resource was
// successfully removed.
//
// It does check Watchtower if the resource is found in state to point out any
// misalignment between what is in state and the actual configuration.
func testAccCheckRoleDestroyed(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name]
if !ok {
// If it's not in state, it's destroyed in TF but not guaranteed to be destroyed
// in Watchtower. Need to find a way to get the host catalog ID here so we can
// form a lookup to the WT API to check this.
return nil
}
errs := []string{}
errs = append(errs, fmt.Sprintf("Found role resource in state: %s", name))

id := rs.Primary.ID
if id == "" {
return fmt.Errorf("No ID is set")
}

md := testProvider.Meta().(*metaData)

u := roles.Role{Id: id}

o := &scopes.Organization{
Client: md.client,
}
if _, apiErr, _ := o.ReadRole(md.ctx, &u); apiErr == nil || *apiErr.Status != http.StatusNotFound {
errs = append(errs, fmt.Sprintf("Role not destroyed %q: %v", id, apiErr))
}

return errors.New(strings.Join(errs, ","))
}
}

func testAccCheckRoleResourceExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}

id := rs.Primary.ID
if id == "" {
return fmt.Errorf("No ID is set")
}

md := testProvider.Meta().(*metaData)

u := roles.Role{Id: id}

o := &scopes.Organization{
Client: md.client,
}
if _, _, err := o.ReadRole(md.ctx, &u); err != nil {
return fmt.Errorf("Got an error when reading role %q: %v", id, err)
}

return nil
}
}

func testAccCheckRoleResourceDestroy(t *testing.T) resource.TestCheckFunc {
return func(s *terraform.State) error {
md := testProvider.Meta().(*metaData)
client := md.client

for _, rs := range s.RootModule().Resources {
switch rs.Type {
case "watchtower_role":

id := rs.Primary.ID

u := roles.Role{Id: id}

o := &scopes.Organization{
Client: client,
}

_, apiErr, _ := o.ReadRole(md.ctx, &u)
if apiErr == nil || *apiErr.Status != http.StatusNotFound {
return fmt.Errorf("Didn't get a 404 when reading destroyed role %q: %v", id, apiErr)
}

default:
t.Logf("Got unknown resource type %q", rs.Type)
}
}
return nil
}
}
26 changes: 26 additions & 0 deletions website/docs/r/resource_role.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
layout: "watchtower"
page_title: "Watchtower: role_resource"
sidebar_current: "docs-watchtower-role-resource"
description: |-
Role resource for the Watchtower Terraform provider.
---

# role_resource
The role resource allows you to configure a Watchtower role.

## Example Usage

```hcl
resource "watchtower_role" "example" {
name = "My role"
description = "My first role!"
}
```

## Argument Reference

The following arguments are optional:
* `name` - The role name. Defaults to the resource name.
* `description` - The role description.