github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/openstack/resource_openstack_compute_keypair_v2.go (about) 1 package openstack 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs" 8 "github.com/hashicorp/terraform/helper/schema" 9 ) 10 11 func resourceComputeKeypairV2() *schema.Resource { 12 return &schema.Resource{ 13 Create: resourceComputeKeypairV2Create, 14 Read: resourceComputeKeypairV2Read, 15 Delete: resourceComputeKeypairV2Delete, 16 Importer: &schema.ResourceImporter{ 17 State: schema.ImportStatePassthrough, 18 }, 19 20 Schema: map[string]*schema.Schema{ 21 "region": &schema.Schema{ 22 Type: schema.TypeString, 23 Required: true, 24 ForceNew: true, 25 DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), 26 }, 27 "name": &schema.Schema{ 28 Type: schema.TypeString, 29 Required: true, 30 ForceNew: true, 31 }, 32 "public_key": &schema.Schema{ 33 Type: schema.TypeString, 34 Optional: true, 35 ForceNew: true, 36 }, 37 "value_specs": &schema.Schema{ 38 Type: schema.TypeMap, 39 Optional: true, 40 ForceNew: true, 41 }, 42 }, 43 } 44 } 45 46 func resourceComputeKeypairV2Create(d *schema.ResourceData, meta interface{}) error { 47 config := meta.(*Config) 48 computeClient, err := config.computeV2Client(GetRegion(d)) 49 if err != nil { 50 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 51 } 52 53 createOpts := KeyPairCreateOpts{ 54 keypairs.CreateOpts{ 55 Name: d.Get("name").(string), 56 PublicKey: d.Get("public_key").(string), 57 }, 58 MapValueSpecs(d), 59 } 60 61 log.Printf("[DEBUG] Create Options: %#v", createOpts) 62 kp, err := keypairs.Create(computeClient, createOpts).Extract() 63 if err != nil { 64 return fmt.Errorf("Error creating OpenStack keypair: %s", err) 65 } 66 67 d.SetId(kp.Name) 68 69 return resourceComputeKeypairV2Read(d, meta) 70 } 71 72 func resourceComputeKeypairV2Read(d *schema.ResourceData, meta interface{}) error { 73 config := meta.(*Config) 74 computeClient, err := config.computeV2Client(GetRegion(d)) 75 if err != nil { 76 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 77 } 78 79 kp, err := keypairs.Get(computeClient, d.Id()).Extract() 80 if err != nil { 81 return CheckDeleted(d, err, "keypair") 82 } 83 84 d.Set("name", kp.Name) 85 d.Set("public_key", kp.PublicKey) 86 d.Set("region", GetRegion(d)) 87 88 return nil 89 } 90 91 func resourceComputeKeypairV2Delete(d *schema.ResourceData, meta interface{}) error { 92 config := meta.(*Config) 93 computeClient, err := config.computeV2Client(GetRegion(d)) 94 if err != nil { 95 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 96 } 97 98 err = keypairs.Delete(computeClient, d.Id()).ExtractErr() 99 if err != nil { 100 return fmt.Errorf("Error deleting OpenStack keypair: %s", err) 101 } 102 d.SetId("") 103 return nil 104 }