forked from hashicorp/terraform
/
resource_key.go
100 lines (82 loc) · 2.12 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
package triton
import (
"errors"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/joyent/triton-go"
)
func resourceKey() *schema.Resource {
return &schema.Resource{
Create: resourceKeyCreate,
Exists: resourceKeyExists,
Read: resourceKeyRead,
Delete: resourceKeyDelete,
Timeouts: fastResourceTimeout,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Description: "Name of the key (generated from the key comment if not set)",
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"key": {
Description: "Content of public key from disk in OpenSSH format",
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*triton.Client)
if keyName := d.Get("name").(string); keyName == "" {
parts := strings.SplitN(d.Get("key").(string), " ", 3)
if len(parts) == 3 {
d.Set("name", parts[2])
} else {
return errors.New("No key name specified, and key material has no comment")
}
}
_, err := client.Keys().CreateKey(&triton.CreateKeyInput{
Name: d.Get("name").(string),
Key: d.Get("key").(string),
})
if err != nil {
return err
}
d.SetId(d.Get("name").(string))
return resourceKeyRead(d, meta)
}
func resourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) {
client := meta.(*triton.Client)
_, err := client.Keys().GetKey(&triton.GetKeyInput{
KeyName: d.Id(),
})
if err != nil {
return false, err
}
return true, nil
}
func resourceKeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*triton.Client)
key, err := client.Keys().GetKey(&triton.GetKeyInput{
KeyName: d.Id(),
})
if err != nil {
return err
}
d.Set("name", key.Name)
d.Set("key", key.Key)
return nil
}
func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*triton.Client)
return client.Keys().DeleteKey(&triton.DeleteKeyInput{
KeyName: d.Id(),
})
}