Skip to content

Commit

Permalink
refactor: project sshkeys using equinix-sdk-go (#562)
Browse files Browse the repository at this point in the history
#402

Co-authored-by: codinja1188 <3358152+vasubabu@users.noreply.github.com>
Co-authored-by: Charles Treatman <ctreatman@equinix.com>
  • Loading branch information
3 people authored Feb 13, 2024
1 parent feb1325 commit 27ee859
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 85 deletions.
11 changes: 6 additions & 5 deletions internal/acceptance/ssh_key_helpers.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package acceptance

import (
"context"
"fmt"

"github.com/equinix/equinix-sdk-go/services/metalv1"
"github.com/equinix/terraform-provider-equinix/internal/config"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/packethost/packngo"
)

func TestAccCheckMetalSSHKeyExists(n string, key *packngo.SSHKey) resource.TestCheckFunc {
func TestAccCheckMetalSSHKeyExists(n string, key *metalv1.SSHKey) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
Expand All @@ -19,13 +20,13 @@ func TestAccCheckMetalSSHKeyExists(n string, key *packngo.SSHKey) resource.TestC
return fmt.Errorf("No Record ID is set")
}

client := TestAccProvider.Meta().(*config.Config).Metal
client := TestAccProvider.Meta().(*config.Config).Metalgo

foundKey, _, err := client.SSHKeys.Get(rs.Primary.ID, nil)
foundKey, _, err := client.SSHKeysApi.FindSSHKeyById(context.Background(), rs.Primary.ID).Execute()
if err != nil {
return err
}
if foundKey.ID != rs.Primary.ID {
if foundKey.GetId() != rs.Primary.ID {
return fmt.Errorf("SSh Key not found: %v - %v", rs.Primary.ID, foundKey)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ func (c *Config) AddFwModuleToMetalUserAgent(ctx context.Context, meta tfsdk.Con
c.Metal.UserAgent = generateFwModuleUserAgentString(ctx, meta, c.metalUserAgent)
}

func (c *Config) AddFwModuleToMetaGolUserAgent(ctx context.Context, meta tfsdk.Config) {
func (c *Config) AddFwModuleToMetalGoUserAgent(ctx context.Context, meta tfsdk.Config) {
c.Metalgo.GetConfig().UserAgent = generateFwModuleUserAgentString(ctx, meta, c.metalGoUserAgent)
}

Expand Down
20 changes: 8 additions & 12 deletions internal/resources/metal/project_ssh_key/datasource.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package project_ssh_key

import (
"github.com/equinix/equinix-sdk-go/services/metalv1"
equinix_errors "github.com/equinix/terraform-provider-equinix/internal/errors"
"github.com/equinix/terraform-provider-equinix/internal/framework"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/packethost/packngo"

"context"
"fmt"
Expand All @@ -30,8 +30,8 @@ func (r *DataSource) Read(
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) {
r.Meta.AddFwModuleToMetalUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metal
r.Meta.AddFwModuleToMetalGoUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metalgo

// Retrieve values from plan
var data DataSourceModel
Expand All @@ -46,16 +46,11 @@ func (r *DataSource) Read(
projectID := data.ProjectID.ValueString()

var (
key packngo.SSHKey
searchOpts *packngo.SearchOptions
key metalv1.SSHKey
)

if search != "" {
searchOpts = &packngo.SearchOptions{Search: search}
}

// Use API client to list SSH keys
keys, _, err := client.Projects.ListSSHKeys(projectID, searchOpts)
keysList, _, err := client.SSHKeysApi.FindProjectSSHKeys(context.Background(), projectID).Query(search).Execute()
if err != nil {
err = equinix_errors.FriendlyError(err)
resp.Diagnostics.AddError(
Expand All @@ -65,6 +60,7 @@ func (r *DataSource) Read(
return
}

keys := keysList.GetSshKeys()
for i := range keys {
// use the first match for searches
if search != "" {
Expand All @@ -73,13 +69,13 @@ func (r *DataSource) Read(
}

// otherwise find the matching ID
if keys[i].ID == id {
if keys[i].GetId() == id {
key = keys[i]
break
}
}

if key.ID == "" {
if key.GetId() == "" {
// Not Found
resp.Diagnostics.AddError(
"Error listing project ssh keys",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func TestAccDataSourceMetalProjectSSHKey_upgradeFromVersion(t *testing.T) {
{
ExternalProviders: map[string]resource.ExternalProvider{
"equinix": {
VersionConstraint: "1.24.0", // latest version with resource defined on SDKv2
VersionConstraint: "1.27.0", // latest version with resource defined on SDKv2
Source: "equinix/equinix",
},
},
Expand Down
38 changes: 21 additions & 17 deletions internal/resources/metal/project_ssh_key/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package project_ssh_key
import (
"path"

"github.com/equinix/equinix-sdk-go/services/metalv1"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/packethost/packngo"
)

type ResourceModel struct {
Expand All @@ -19,14 +19,16 @@ type ResourceModel struct {
ProjectID types.String `tfsdk:"project_id"`
}

func (m *ResourceModel) parse(key *packngo.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.ID)
m.Name = types.StringValue(key.Label)
m.PublicKey = types.StringValue(key.Key)
m.Fingerprint = types.StringValue(key.FingerPrint)
m.Created = types.StringValue(key.Created)
m.Updated = types.StringValue(key.Updated)
m.OwnerID = types.StringValue(path.Base(key.Owner.Href))
func (m *ResourceModel) parse(key *metalv1.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.GetId())
m.Name = types.StringValue(key.GetLabel())
m.PublicKey = types.StringValue(key.GetKey())
m.Fingerprint = types.StringValue(key.GetFingerprint())
m.Created = types.StringValue(key.CreatedAt.GoString())
m.Updated = types.StringValue(key.UpdatedAt.GoString())

ownerID := key.AdditionalProperties["owner"].(map[string]interface{})
m.OwnerID = types.StringValue(path.Base(ownerID["href"].(string)))
m.ProjectID = m.OwnerID
return nil
}
Expand All @@ -46,14 +48,16 @@ type DataSourceModel struct {
ProjectID types.String `tfsdk:"project_id"`
}

func (m *DataSourceModel) parse(key *packngo.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.ID)
m.Name = types.StringValue(key.Label)
m.PublicKey = types.StringValue(key.Key)
m.Fingerprint = types.StringValue(key.FingerPrint)
m.Created = types.StringValue(key.Created)
m.Updated = types.StringValue(key.Updated)
m.OwnerID = types.StringValue(path.Base(key.Owner.Href))
func (m *DataSourceModel) parse(key *metalv1.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.GetId())
m.Name = types.StringValue(key.GetLabel())
m.PublicKey = types.StringValue(key.GetKey())
m.Fingerprint = types.StringValue(key.GetFingerprint())
m.Created = types.StringValue(key.CreatedAt.GoString())
m.Updated = types.StringValue(key.UpdatedAt.GoString())

ownerID := key.AdditionalProperties["owner"].(map[string]interface{})
m.OwnerID = types.StringValue(path.Base(ownerID["href"].(string)))
m.ProjectID = m.OwnerID
return nil
}
39 changes: 20 additions & 19 deletions internal/resources/metal/project_ssh_key/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"context"
"fmt"

"github.com/equinix/equinix-sdk-go/services/metalv1"
equinix_errors "github.com/equinix/terraform-provider-equinix/internal/errors"
"github.com/equinix/terraform-provider-equinix/internal/framework"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/packethost/packngo"
)

func NewResource() resource.Resource {
Expand All @@ -31,8 +31,8 @@ func (r *Resource) Create(
resp *resource.CreateResponse,
) {

r.Meta.AddFwModuleToMetalUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metal
r.Meta.AddFwModuleToMetalGoUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metalgo

// Retrieve values from plan
var plan ResourceModel
Expand All @@ -42,14 +42,15 @@ func (r *Resource) Create(
}

// Generate API request body from plan
createRequest := &packngo.SSHKeyCreateRequest{
Label: plan.Name.ValueString(),
Key: plan.PublicKey.ValueString(),
ProjectID: plan.ProjectID.ValueString(),
createRequest := &metalv1.SSHKeyCreateInput{
Label: plan.Name.ValueStringPointer(),
Key: plan.PublicKey.ValueStringPointer(),
}

projectId := plan.ProjectID.ValueString()

// Create API resource
key, _, err := client.SSHKeys.Create(createRequest)
key, _, err := client.SSHKeysApi.CreateProjectSSHKey(context.Background(), projectId).SSHKeyCreateInput(*createRequest).Execute()
if err != nil {
resp.Diagnostics.AddError(
"Failed to create Project SSH Key",
Expand All @@ -73,8 +74,8 @@ func (r *Resource) Read(
req resource.ReadRequest,
resp *resource.ReadResponse,
) {
r.Meta.AddFwModuleToMetalUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metal
r.Meta.AddFwModuleToMetalGoUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metalgo

// Retrieve values from state
var state ResourceModel
Expand All @@ -87,7 +88,7 @@ func (r *Resource) Read(
id := state.ID.ValueString()

// Use API client to get the current state of the resource
key, _, err := client.SSHKeys.Get(id, nil)
key, _, err := client.SSHKeysApi.FindSSHKeyById(context.Background(), id).Include(nil).Execute()
if err != nil {
err = equinix_errors.FriendlyError(err)

Expand Down Expand Up @@ -122,8 +123,8 @@ func (r *Resource) Update(
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) {
r.Meta.AddFwModuleToMetalUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metal
r.Meta.AddFwModuleToMetalGoUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metalgo

// Retrieve values from plan
var state, plan ResourceModel
Expand All @@ -136,7 +137,7 @@ func (r *Resource) Update(
// Extract the ID of the resource from the state
id := plan.ID.ValueString()

updateRequest := &packngo.SSHKeyUpdateRequest{}
updateRequest := &metalv1.SSHKeyInput{}
if !state.Name.Equal(plan.Name) {
updateRequest.Label = plan.Name.ValueStringPointer()
}
Expand All @@ -145,7 +146,7 @@ func (r *Resource) Update(
}

// Update the resource
key, _, err := client.SSHKeys.Update(plan.ID.ValueString(), updateRequest)
key, _, err := client.SSHKeysApi.UpdateSSHKey(context.Background(), id).SSHKeyInput(*updateRequest).Execute()
if err != nil {
err = equinix_errors.FriendlyError(err)
resp.Diagnostics.AddError(
Expand All @@ -170,8 +171,8 @@ func (r *Resource) Delete(
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) {
r.Meta.AddFwModuleToMetalUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metal
r.Meta.AddFwModuleToMetalGoUserAgent(ctx, req.ProviderMeta)
client := r.Meta.Metalgo

// Retrieve values from plan
var state ResourceModel
Expand All @@ -184,8 +185,8 @@ func (r *Resource) Delete(
id := state.ID.ValueString()

// Use API client to delete the resource
deleteResp, err := client.SSHKeys.Delete(id)
if equinix_errors.IgnoreResponseErrors(equinix_errors.HttpForbidden, equinix_errors.HttpNotFound)(deleteResp, err) != nil {
deleteResp, err := client.SSHKeysApi.DeleteSSHKey(context.Background(), id).Execute()
if equinix_errors.IgnoreHttpResponseErrors(equinix_errors.HttpForbidden, equinix_errors.HttpNotFound)(deleteResp, err) != nil {
err = equinix_errors.FriendlyError(err)
resp.Diagnostics.AddError(
fmt.Sprintf("Failed to delete Project SSHKey %s", id),
Expand Down
6 changes: 3 additions & 3 deletions internal/resources/metal/project_ssh_key/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import (

"github.com/equinix/terraform-provider-equinix/internal/config"

"github.com/equinix/equinix-sdk-go/services/metalv1"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/packethost/packngo"
)

func testAccMetalProjectSSHKeyConfig_basic(name, publicSshKey string) string {
Expand Down Expand Up @@ -50,7 +50,7 @@ resource "equinix_metal_device" "test" {

func TestAccMetalProjectSSHKey_basic(t *testing.T) {
rs := acctest.RandString(10)
var key packngo.SSHKey
var key metalv1.SSHKey
publicKeyMaterial, _, err := acctest.RandSSHKeyPair("")
if err != nil {
t.Fatalf("Cannot generate test SSH key pair: %s", err)
Expand Down Expand Up @@ -102,7 +102,7 @@ func testAccMetalProjectSSHKeyCheckDestroyed(s *terraform.State) error {
// TODO (ocobles): once migrated, this test may be removed
func TestAccMetalProjectSSHKey_upgradeFromVersion(t *testing.T) {
rs := acctest.RandString(10)
var key packngo.SSHKey
var key metalv1.SSHKey
publicKeyMaterial, _, err := acctest.RandSSHKeyPair("")
if err != nil {
t.Fatalf("Cannot generate test SSH key pair: %s", err)
Expand Down
20 changes: 11 additions & 9 deletions internal/resources/metal/ssh_key/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package ssh_key
import (
"path"

"github.com/equinix/equinix-sdk-go/services/metalv1"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/packethost/packngo"
)

type ResourceModel struct {
Expand All @@ -18,13 +18,15 @@ type ResourceModel struct {
OwnerID types.String `tfsdk:"owner_id"`
}

func (m *ResourceModel) parse(key *packngo.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.ID)
m.Name = types.StringValue(key.Label)
m.PublicKey = types.StringValue(key.Key)
m.Fingerprint = types.StringValue(key.FingerPrint)
m.Created = types.StringValue(key.Created)
m.Updated = types.StringValue(key.Updated)
m.OwnerID = types.StringValue(path.Base(key.Owner.Href))
func (m *ResourceModel) parse(key *metalv1.SSHKey) diag.Diagnostics {
m.ID = types.StringValue(key.GetId())
m.Name = types.StringValue(key.GetLabel())
m.PublicKey = types.StringValue(key.GetKey())
m.Fingerprint = types.StringValue(key.GetFingerprint())
m.Created = types.StringValue(key.CreatedAt.GoString())
m.Updated = types.StringValue(key.UpdatedAt.GoString())
ownerID := key.AdditionalProperties["owner"].(map[string]interface{})
m.OwnerID = types.StringValue(path.Base(ownerID["href"].(string)))

return nil
}
Loading

0 comments on commit 27ee859

Please sign in to comment.