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(iam): add iam api key resource #1343

Merged
merged 15 commits into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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 scaleway/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func addBetaResources(provider *schema.Provider) {
}
betaResources := map[string]*schema.Resource{
"scaleway_iam_application": resourceScalewayIamApplication(),
"scaleway_iam_api_key": resourceScalewayIamAPIKey(),
}
betaDataSources := map[string]*schema.Resource{
"scaleway_iam_application": dataSourceScalewayIamApplication(),
Expand Down
173 changes: 173 additions & 0 deletions scaleway/resource_iam_api_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package scaleway

import (
"context"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
iam "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)

func resourceScalewayIamAPIKey() *schema.Resource {
return &schema.Resource{
CreateContext: resourceScalewayIamAPIKeyCreate,
ReadContext: resourceScalewayIamAPIKeyRead,
UpdateContext: resourceScalewayIamAPIKeyUpdate,
DeleteContext: resourceScalewayIamAPIKeyDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaVersion: 0,
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
Description: "The description of the iam api key",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the creation of the iam api key",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the last update of the iam api key",
},
"expires_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the expiration of the iam api key",
},
"access_key": {
Type: schema.TypeString,
Computed: true,
Description: "The access key of the iam api key",
},
"secret_key": {
Type: schema.TypeString,
Computed: true,
Description: "The secret Key of the iam api key",
},
"application_id": {
Type: schema.TypeString,
Optional: true,
Description: "ID of the application attached to the api key",
ConflictsWith: []string{"user_id"},
ValidateFunc: validationUUID(),
},
"user_id": {
Type: schema.TypeString,
Optional: true,
Description: "ID of the user attached to the api key",
ConflictsWith: []string{"application_id"},
ValidateFunc: validationUUID(),
},
"editable": {
Type: schema.TypeBool,
Computed: true,
Description: "Whether or not the iam api key is editable",
},
"creation_ip": {
Type: schema.TypeString,
Computed: true,
Description: "The IP Address of the device which created the API key",
},
"default_project_id": projectIDSchema(),
},
}
}

func resourceScalewayIamAPIKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
iamAPI := iamAPI(meta)
res, err := iamAPI.CreateAPIKey(&iam.CreateAPIKeyRequest{
ApplicationID: expandStringPtr(d.Get("application_id")),
UserID: expandStringPtr(d.Get("user_id")),
ExpiresAt: expandTimePtr(d.Get("expires_at")),
DefaultProjectID: expandStringPtr(d.Get("project_id")),
Description: d.Get("description").(string),
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}

d.SetId(res.AccessKey)

return resourceScalewayIamAPIKeyRead(ctx, d, meta)
}

func resourceScalewayIamAPIKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
api := iamAPI(meta)
res, err := api.GetAPIKey(&iam.GetAPIKeyRequest{
AccessKey: d.Id(),
}, scw.WithContext(ctx))
if err != nil {
if is404Error(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
_ = d.Set("description", res.Description)
_ = d.Set("created_at", flattenTime(res.CreatedAt))
_ = d.Set("updated_at", flattenTime(res.UpdatedAt))
_ = d.Set("expires_at", flattenTime(res.ExpiresAt))
_ = d.Set("access_key", res.AccessKey)
_ = d.Set("secret_key", res.SecretKey)

if res.ApplicationID != nil {
_ = d.Set("application_id", res.ApplicationID)
}
if res.UserID != nil {
_ = d.Set("user_id", res.UserID)
}

_ = d.Set("editable", res.Editable)
_ = d.Set("creation_ip", res.CreationIP)
_ = d.Set("default_project_id", res.DefaultProjectID)

return nil
}

func resourceScalewayIamAPIKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
api := iamAPI(meta)

req := &iam.UpdateAPIKeyRequest{
AccessKey: d.Id(),
}

hasChanged := false

if d.HasChange("description") {
req.Description = expandStringPtr(d.Get("description"))
hasChanged = true
}

if d.HasChange("default_project_id") {
req.DefaultProjectID = expandStringPtr(d.Get("default_project_id"))
hasChanged = true
}

if hasChanged {
_, err := api.UpdateAPIKey(req, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
}

return resourceScalewayIamAPIKeyRead(ctx, d, meta)
}

func resourceScalewayIamAPIKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
api := iamAPI(meta)

err := api.DeleteAPIKey(&iam.DeleteAPIKeyRequest{
AccessKey: d.Id(),
}, scw.WithContext(ctx))
if err != nil && !is404Error(err) {
return diag.FromErr(err)
}

return nil
}
184 changes: 184 additions & 0 deletions scaleway/resource_iam_api_key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package scaleway

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
iam "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)

func init() {
if !terraformBetaEnabled {
return
}
resource.AddTestSweepers("scaleway_iam_api_key", &resource.Sweeper{
Name: "scaleway_iam_api_key",
F: testSweepIamAPIKey,
})
}

func testSweepIamAPIKey(_ string) error {
return sweep(func(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)

l.Debugf("sweeper: destroying the api keys")

listAPIKeys, err := api.ListAPIKeys(&iam.ListAPIKeysRequest{})
if err != nil {
return fmt.Errorf("failed to list api keys: %w", err)
}
for _, app := range listAPIKeys.APIKeys {
err = api.DeleteAPIKey(&iam.DeleteAPIKeyRequest{
AccessKey: app.AccessKey,
})
if err != nil {
return fmt.Errorf("failed to delete api key: %w", err)
}
}
return nil
})
}

func TestAccScalewayIamApiKey_Basic(t *testing.T) {
SkipBetaTest(t)
tt := NewTestTools(t)
defer tt.Cleanup()
resource.ParallelTest(t, resource.TestCase{
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayIamAPIKeyDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_iam_application" "main" {
name = "tf_tests_app_basic"
}

resource "scaleway_iam_api_key" "main" {
application_id = scaleway_iam_application.main.id
description = "a description"
}
`,
Check: resource.ComposeTestCheckFunc(
testAccCheckScalewayIamAPIKeyExists(tt, "scaleway_iam_api_key.main"),
resource.TestCheckResourceAttrPair("scaleway_iam_api_key.main", "application_id", "scaleway_iam_application.main", "id"),
resource.TestCheckResourceAttr("scaleway_iam_api_key.main", "description", "a description"),
),
},
{
Config: `
resource "scaleway_iam_application" "main" {
name = "tf_tests_app_basic"
}

resource "scaleway_iam_api_key" "main" {
application_id = scaleway_iam_application.main.id
description = "another description"
}
`,
Check: resource.ComposeTestCheckFunc(
testAccCheckScalewayIamApplicationExists(tt, "scaleway_iam_application.main"),
resource.TestCheckResourceAttrPair("scaleway_iam_api_key.main", "application_id", "scaleway_iam_application.main", "id"),
resource.TestCheckResourceAttr("scaleway_iam_api_key.main", "description", "another description"),
),
},
},
})
}

func TestAccScalewayIamApiKey_NoUpdate(t *testing.T) {
SkipBetaTest(t)
tt := NewTestTools(t)
defer tt.Cleanup()

resource.ParallelTest(t, resource.TestCase{
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayIamAPIKeyDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_iam_application" "main" {
name = "tf_tests_app_noupdate"
}

resource "scaleway_iam_api_key" "main" {
application_id = scaleway_iam_application.main.id
description = "no update"
}
`,
Check: resource.ComposeTestCheckFunc(
testAccCheckScalewayIamAPIKeyExists(tt, "scaleway_iam_api_key.main"),
resource.TestCheckResourceAttrPair("scaleway_iam_api_key.main", "application_id", "scaleway_iam_application.main", "id"),
resource.TestCheckResourceAttr("scaleway_iam_api_key.main", "description", "no update"),
),
},
{
Config: `
resource "scaleway_iam_application" "main" {
name = "tf_tests_app_noupdate"
}

resource "scaleway_iam_api_key" "main" {
application_id = scaleway_iam_application.main.id
description = "no update"
}
`,
Check: resource.ComposeTestCheckFunc(
testAccCheckScalewayIamAPIKeyExists(tt, "scaleway_iam_api_key.main"),
resource.TestCheckResourceAttrPair("scaleway_iam_api_key.main", "application_id", "scaleway_iam_application.main", "id"),
resource.TestCheckResourceAttr("scaleway_iam_api_key.main", "description", "no update"),
),
},
},
})
}

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

iamAPI := iamAPI(tt.Meta)

_, err := iamAPI.GetAPIKey(&iam.GetAPIKeyRequest{
AccessKey: rs.Primary.ID,
})
if err != nil {
return fmt.Errorf("could not find api key: %w", err)
}

return nil
}
}

func testAccCheckScalewayIamAPIKeyDestroy(tt *TestTools) resource.TestCheckFunc {
return func(s *terraform.State) error {
for _, rs := range s.RootModule().Resources {
if rs.Type != "scaleway_iam_api_key" {
continue
}

iamAPI := iamAPI(tt.Meta)

_, err := iamAPI.GetAPIKey(&iam.GetAPIKeyRequest{
AccessKey: rs.Primary.ID,
})

// If no error resource still exist
if err == nil {
return fmt.Errorf("resource %s(%s) still exist", rs.Type, rs.Primary.ID)
}

// Unexpected api error we return it
if !is404Error(err) {
return err
}
}

return nil
}
}
Loading