/
resource_compute_keypair.go
102 lines (82 loc) · 2.49 KB
/
resource_compute_keypair.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 main
import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs"
)
func resourceComputeKeypair() *schema.Resource {
return &schema.Resource{
Create: resourceComputeKeypairCreate,
Read: resourceComputeKeypairRead,
Delete: resourceComputeKeypairDelete,
Exists: resourceComputeKeypairExists,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"public_key": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceComputeKeypairCreate(d *schema.ResourceData, meta interface{}) error {
computeClient, err := meta.(*Config).computeClient()
if err != nil {
return fmt.Errorf("Error creating ConoHa compute client: %s", err)
}
createOpts := keypairs.CreateOpts{
Name: d.Get("name").(string),
PublicKey: d.Get("public_key").(string),
}
keypair, err := keypairs.Create(computeClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating ConoHa keypair: %s", err)
}
d.SetId(keypair.Name)
return resourceComputeKeypairRead(d, meta)
}
func resourceComputeKeypairRead(d *schema.ResourceData, meta interface{}) error {
computeClient, err := meta.(*Config).computeClient()
if err != nil {
return fmt.Errorf("Error creating ConoHa compute client: %s", err)
}
keypair, err := keypairs.Get(computeClient, d.Id()).Extract()
if err != nil {
return err
}
d.Set("name", keypair.Name)
d.Set("public_key", keypair.PublicKey)
return nil
}
func resourceComputeKeypairDelete(d *schema.ResourceData, meta interface{}) error {
computeClient, err := meta.(*Config).computeClient()
if err != nil {
return fmt.Errorf("Error creating ConoHa compute client: %s", err)
}
err = keypairs.Delete(computeClient, d.Id()).ExtractErr()
if err != nil {
return fmt.Errorf("Error deleting ConoHa keypair: %s", err)
}
d.SetId("")
return nil
}
func resourceComputeKeypairExists(d *schema.ResourceData, meta interface{}) (bool, error) {
computeClient, err := meta.(*Config).computeClient()
if err != nil {
return false, fmt.Errorf("Error creating ConoHa compute client: %s", err)
}
_, err = keypairs.Get(computeClient, d.Id()).Extract()
if err != nil {
if code, ok := err.(*gophercloud.UnexpectedResponseCodeError); ok && code.Actual == 404 {
return false, nil
}
return false, err
}
return true, nil
}