github.com/danrjohnson/terraform@v0.7.0-rc2.0.20160627135212-d0fc1fa086ff/builtin/providers/triton/resource_key.go (about) 1 package triton 2 3 import ( 4 "errors" 5 "strings" 6 7 "github.com/hashicorp/terraform/helper/schema" 8 "github.com/joyent/gosdc/cloudapi" 9 ) 10 11 var ( 12 // ErrNoKeyComment will be returned when the key name cannot be generated from 13 // the key comment and is not otherwise specified. 14 ErrNoKeyComment = errors.New("no key comment found to use as a name (and none specified)") 15 ) 16 17 func resourceKey() *schema.Resource { 18 return &schema.Resource{ 19 Create: resourceKeyCreate, 20 Exists: resourceKeyExists, 21 Read: resourceKeyRead, 22 Delete: resourceKeyDelete, 23 Importer: &schema.ResourceImporter{ 24 State: resourceKeyImporter, 25 }, 26 27 Schema: map[string]*schema.Schema{ 28 "name": &schema.Schema{ 29 Description: "name of this key (will be generated from the key comment, if not set and comment present)", 30 Type: schema.TypeString, 31 Optional: true, 32 Computed: true, 33 ForceNew: true, 34 }, 35 "key": &schema.Schema{ 36 Description: "content of public key from disk", 37 Type: schema.TypeString, 38 Required: true, 39 ForceNew: true, 40 }, 41 }, 42 } 43 } 44 45 func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error { 46 client := meta.(*cloudapi.Client) 47 48 if d.Get("name").(string) == "" { 49 parts := strings.SplitN(d.Get("key").(string), " ", 3) 50 if len(parts) == 3 { 51 d.Set("name", parts[2]) 52 } else { 53 return ErrNoKeyComment 54 } 55 } 56 57 _, err := client.CreateKey(cloudapi.CreateKeyOpts{ 58 Name: d.Get("name").(string), 59 Key: d.Get("key").(string), 60 }) 61 if err != nil { 62 return err 63 } 64 65 err = resourceKeyRead(d, meta) 66 if err != nil { 67 return err 68 } 69 70 return nil 71 } 72 73 func resourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) { 74 client := meta.(*cloudapi.Client) 75 76 keys, err := client.ListKeys() 77 if err != nil { 78 return false, err 79 } 80 81 for _, key := range keys { 82 if key.Name == d.Id() { 83 return true, nil 84 } 85 } 86 87 return false, nil 88 } 89 90 func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { 91 client := meta.(*cloudapi.Client) 92 93 key, err := client.GetKey(d.Id()) 94 if err != nil { 95 return err 96 } 97 98 d.SetId(key.Name) 99 d.Set("name", key.Name) 100 d.Set("key", key.Key) 101 102 return nil 103 } 104 105 func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error { 106 client := meta.(*cloudapi.Client) 107 108 if err := client.DeleteKey(d.Get("name").(string)); err != nil { 109 return err 110 } 111 112 return nil 113 } 114 115 func resourceKeyImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { 116 return []*schema.ResourceData{d}, nil 117 }