forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 2
/
resource_key.go
110 lines (89 loc) · 2.26 KB
/
resource_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
package triton
import (
"errors"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/joyent/gosdc/cloudapi"
)
var (
// ErrNoKeyComment will be returned when the key name cannot be generated from
// the key comment and is not otherwise specified.
ErrNoKeyComment = errors.New("no key comment found to use as a name (and none specified)")
)
func resourceKey() *schema.Resource {
return &schema.Resource{
Create: resourceKeyCreate,
Exists: resourceKeyExists,
Read: resourceKeyRead,
Delete: resourceKeyDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Description: "name of this key (will be generated from the key comment, if not set and comment present)",
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"key": &schema.Schema{
Description: "content of public key from disk",
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudapi.Client)
if d.Get("name").(string) == "" {
parts := strings.SplitN(d.Get("key").(string), " ", 3)
if len(parts) == 3 {
d.Set("name", parts[2])
} else {
return ErrNoKeyComment
}
}
_, err := client.CreateKey(cloudapi.CreateKeyOpts{
Name: d.Get("name").(string),
Key: d.Get("key").(string),
})
if err != nil {
return err
}
err = resourceKeyRead(d, meta)
if err != nil {
return err
}
return nil
}
func resourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) {
client := meta.(*cloudapi.Client)
keys, err := client.ListKeys()
if err != nil {
return false, err
}
for _, key := range keys {
if key.Name == d.Id() {
return true, nil
}
}
return false, nil
}
func resourceKeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudapi.Client)
key, err := client.GetKey(d.Get("name").(string))
if err != nil {
return err
}
d.SetId(key.Name)
d.Set("name", key.Name)
d.Set("key", key.Key)
return nil
}
func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudapi.Client)
if err := client.DeleteKey(d.Get("name").(string)); err != nil {
return err
}
return nil
}