github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/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/triton-go" 9 ) 10 11 func resourceKey() *schema.Resource { 12 return &schema.Resource{ 13 Create: resourceKeyCreate, 14 Exists: resourceKeyExists, 15 Read: resourceKeyRead, 16 Delete: resourceKeyDelete, 17 Timeouts: fastResourceTimeout, 18 Importer: &schema.ResourceImporter{ 19 State: schema.ImportStatePassthrough, 20 }, 21 22 Schema: map[string]*schema.Schema{ 23 "name": { 24 Description: "Name of the key (generated from the key comment if not set)", 25 Type: schema.TypeString, 26 Optional: true, 27 Computed: true, 28 ForceNew: true, 29 }, 30 "key": { 31 Description: "Content of public key from disk in OpenSSH format", 32 Type: schema.TypeString, 33 Required: true, 34 ForceNew: true, 35 }, 36 }, 37 } 38 } 39 40 func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error { 41 client := meta.(*triton.Client) 42 43 if keyName := d.Get("name").(string); keyName == "" { 44 parts := strings.SplitN(d.Get("key").(string), " ", 3) 45 if len(parts) == 3 { 46 d.Set("name", parts[2]) 47 } else { 48 return errors.New("No key name specified, and key material has no comment") 49 } 50 } 51 52 _, err := client.Keys().CreateKey(&triton.CreateKeyInput{ 53 Name: d.Get("name").(string), 54 Key: d.Get("key").(string), 55 }) 56 if err != nil { 57 return err 58 } 59 60 d.SetId(d.Get("name").(string)) 61 62 return resourceKeyRead(d, meta) 63 } 64 65 func resourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) { 66 client := meta.(*triton.Client) 67 68 _, err := client.Keys().GetKey(&triton.GetKeyInput{ 69 KeyName: d.Id(), 70 }) 71 if err != nil { 72 return false, err 73 } 74 75 return true, nil 76 } 77 78 func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { 79 client := meta.(*triton.Client) 80 81 key, err := client.Keys().GetKey(&triton.GetKeyInput{ 82 KeyName: d.Id(), 83 }) 84 if err != nil { 85 return err 86 } 87 88 d.Set("name", key.Name) 89 d.Set("key", key.Key) 90 91 return nil 92 } 93 94 func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error { 95 client := meta.(*triton.Client) 96 97 return client.Keys().DeleteKey(&triton.DeleteKeyInput{ 98 KeyName: d.Id(), 99 }) 100 }