/
ssh_key_data_source.go
77 lines (63 loc) · 2.04 KB
/
ssh_key_data_source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package iam
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"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/datasource"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/types"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/verify"
)
func DataSourceSSHKey() *schema.Resource {
// Generate datasource schema from resource
dsSchema := datasource.SchemaFromResourceSchema(ResourceSSKKey().Schema)
datasource.AddOptionalFieldsToSchema(dsSchema, "name", "project_id")
dsSchema["name"].ConflictsWith = []string{"ssh_key_id"}
dsSchema["ssh_key_id"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The ID of the SSH key",
ValidateFunc: verify.IsUUID(),
}
return &schema.Resource{
ReadContext: DataSourceIamSSHKeyRead,
Schema: dsSchema,
}
}
func DataSourceIamSSHKeyRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
iamAPI := NewAPI(m)
sshKeyID, sshKeyIDExists := d.GetOk("ssh_key_id")
if !sshKeyIDExists {
sshKeyName := d.Get("name").(string)
res, err := iamAPI.ListSSHKeys(&iam.ListSSHKeysRequest{
Name: types.ExpandStringPtr(sshKeyName),
ProjectID: types.ExpandStringPtr(d.Get("project_id")),
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
foundKey, err := datasource.FindExact(
res.SSHKeys,
func(s *iam.SSHKey) bool { return s.Name == sshKeyName },
sshKeyName,
)
if err != nil {
return diag.FromErr(err)
}
sshKeyID = foundKey.ID
}
d.SetId(sshKeyID.(string))
err := d.Set("ssh_key_id", sshKeyID)
if err != nil {
return diag.FromErr(err)
}
diags := resourceIamSSHKeyRead(ctx, d, m)
if diags != nil {
return append(diags, diag.Errorf("failed to read iam ssh key state")...)
}
if d.Id() == "" {
return diag.Errorf("iam ssh key (%s) not found", sshKeyID)
}
return nil
}