/
resource_ibm_compute_ssh_key.go
240 lines (202 loc) · 6.13 KB
/
resource_ibm_compute_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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package ibm
import (
"crypto/md5"
"encoding/base64"
"fmt"
"log"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/softlayer/softlayer-go/datatypes"
"github.com/softlayer/softlayer-go/filter"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/sl"
)
func resourceIBMComputeSSHKey() *schema.Resource {
return &schema.Resource{
Create: resourceIBMComputeSSHKeyCreate,
Read: resourceIBMComputeSSHKeyRead,
Update: resourceIBMComputeSSHKeyUpdate,
Delete: resourceIBMComputeSSHKeyDelete,
Exists: resourceIBMComputeSSHKeyExists,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"label": {
Type: schema.TypeString,
Required: true,
Description: "SSH Key label",
},
"public_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.TrimSpace(old) == strings.TrimSpace(new)
},
Description: "Plublic Key info",
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: "SSH key fingerprint",
},
"notes": {
Type: schema.TypeString,
Optional: true,
Default: nil,
Description: "Additional notes",
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: "List of tags for the resource",
},
},
}
}
func resourceIBMComputeSSHKeyCreate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetSecuritySshKeyService(sess)
// First check if the key exists by fingerprint
// If so, set the Id (and fingerprint), but update notes and label (if any)
key := d.Get("public_key").(string)
label := d.Get("label").(string)
fingerprint, err := computeSSHKeyFingerprint(key)
if err != nil {
return err
}
keys, err := services.GetAccountService(sess).
Filter(filter.Path("sshKeys.fingerprint").Eq(fingerprint).Build()).
GetSshKeys()
if err == nil && len(keys) > 0 {
slKey := keys[0]
id := *slKey.Id
slKey.Id = nil
d.SetId(fmt.Sprintf("%d", id))
d.Set("fingerprint", fingerprint)
editKey := false
notes := d.Get("notes").(string)
if notes != "" && (slKey.Notes == nil || notes != *slKey.Notes) {
slKey.Notes = sl.String(notes)
editKey = true
} else if slKey.Notes != nil {
d.Set("notes", *slKey.Notes)
}
if label != *slKey.Label {
slKey.Label = sl.String(label)
editKey = true
}
if editKey {
_, err = service.Id(id).EditObject(&slKey)
return err
}
return nil
} // End of "Import"
// Build up our creation options
opts := datatypes.Security_Ssh_Key{
Label: sl.String(label),
Key: sl.String(key),
}
if notes, ok := d.GetOk("notes"); ok {
opts.Notes = sl.String(notes.(string))
}
res, err := service.CreateObject(&opts)
if err != nil {
return fmt.Errorf("Error creating SSH Key: %s", err)
}
d.SetId(strconv.Itoa(*res.Id))
log.Printf("[INFO] SSH Key: %d", *res.Id)
return resourceIBMComputeSSHKeyRead(d, meta)
}
func resourceIBMComputeSSHKeyRead(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetSecuritySshKeyService(sess)
keyID, _ := strconv.Atoi(d.Id())
key, err := service.Id(keyID).GetObject()
if err != nil {
// If the key is somehow already destroyed, mark as
// succesfully gone
if err, ok := err.(sl.Error); ok && err.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving SSH key: %s", err)
}
d.Set("label", key.Label)
d.Set("public_key", key.Key)
d.Set("fingerprint", key.Fingerprint)
d.Set("notes", key.Notes)
return nil
}
func resourceIBMComputeSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetSecuritySshKeyService(sess)
keyID, _ := strconv.Atoi(d.Id())
key, err := service.Id(keyID).GetObject()
if err != nil {
return fmt.Errorf("Error retrieving SSH key: %s", err)
}
if d.HasChange("label") {
key.Label = sl.String(d.Get("label").(string))
}
if d.HasChange("notes") {
key.Notes = sl.String(d.Get("notes").(string))
}
_, err = service.Id(keyID).EditObject(&key)
if err != nil {
return fmt.Errorf("Error editing SSH key: %s", err)
}
return resourceIBMComputeSSHKeyRead(d, meta)
}
func resourceIBMComputeSSHKeyDelete(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetSecuritySshKeyService(sess)
id, err := strconv.Atoi(d.Id())
if err != nil {
return fmt.Errorf("Error deleting SSH Key: %s", err)
}
log.Printf("[INFO] Deleting SSH key: %d", id)
_, err = service.Id(id).DeleteObject()
if err != nil {
return fmt.Errorf("Error deleting SSH key: %s", err)
}
d.SetId("")
return nil
}
func resourceIBMComputeSSHKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetSecuritySshKeyService(sess)
keyID, err := strconv.Atoi(d.Id())
if err != nil {
return false, fmt.Errorf("Not a valid ID, must be an integer: %s", err)
}
result, err := service.Id(keyID).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.StatusCode == 404 {
return false, nil
}
}
return false, fmt.Errorf("Error communicating with the API: %s", err)
}
return result.Id != nil && *result.Id == keyID, nil
}
func computeSSHKeyFingerprint(key string) (fingerprint string, err error) {
parts := strings.Fields(key)
if len(parts) < 2 {
return "", fmt.Errorf("Invalid public key specified :%s\nPlease check the value of public_key", key)
}
k, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return "", fmt.Errorf("Error decoding the public key: %s\nPlease check the value of public_key", err)
}
fp := md5.Sum([]byte(k))
prints := make([]string, len(fp))
for i, b := range fp {
prints[i] = fmt.Sprintf("%02x", b)
}
fingerprint = strings.Join(prints, ":")
return
}