This repository has been archived by the owner on Jul 20, 2020. It is now read-only.
forked from digitalocean/terraform-provider-digitalocean
/
datasource_digitalocean_ssh_key.go
102 lines (83 loc) · 2.16 KB
/
datasource_digitalocean_ssh_key.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package digitalocean
import (
"context"
"fmt"
"strconv"
"github.com/digitalocean/godo"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceDigitalOceanSSHKey() *schema.Resource {
return &schema.Resource{
Read: dataSourceDigitalOceanSSHKeyRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "name of the ssh key",
ValidateFunc: validation.NoZeroValues,
},
// computed attributes
"public_key": {
Type: schema.TypeString,
Computed: true,
Description: "public key part of the ssh key",
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: "fingerprint of the ssh key",
},
},
}
}
func dataSourceDigitalOceanSSHKeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*CombinedConfig).godoClient()
name := d.Get("name").(string)
opts := &godo.ListOptions{
Page: 1,
PerPage: 200,
}
keyList := []godo.Key{}
for {
keys, resp, err := client.Keys.List(context.Background(), opts)
if err != nil {
return fmt.Errorf("Error retrieving ssh keys: %s", err)
}
for _, key := range keys {
keyList = append(keyList, key)
}
if resp.Links == nil || resp.Links.IsLastPage() {
break
}
page, err := resp.Links.CurrentPage()
if err != nil {
return fmt.Errorf("Error retrieving ssh keys: %s", err)
}
opts.Page = page + 1
}
key, err := findKeyByName(keyList, name)
if err != nil {
return err
}
d.SetId(strconv.Itoa(key.ID))
d.Set("name", key.Name)
d.Set("public_key", key.PublicKey)
d.Set("fingerprint", key.Fingerprint)
return nil
}
func findKeyByName(keys []godo.Key, name string) (*godo.Key, error) {
results := make([]godo.Key, 0)
for _, v := range keys {
if v.Name == name {
results = append(results, v)
}
}
if len(results) == 1 {
return &results[0], nil
}
if len(results) == 0 {
return nil, fmt.Errorf("no ssh key found with name %s", name)
}
return nil, fmt.Errorf("too many ssh keys found with name %s (found %d, expected 1)", name, len(results))
}