github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/ns1/resource_apikey.go (about) 1 package ns1 2 3 import ( 4 "github.com/hashicorp/terraform/helper/schema" 5 6 ns1 "gopkg.in/ns1/ns1-go.v2/rest" 7 "gopkg.in/ns1/ns1-go.v2/rest/model/account" 8 ) 9 10 func apikeyResource() *schema.Resource { 11 s := map[string]*schema.Schema{ 12 "id": &schema.Schema{ 13 Type: schema.TypeString, 14 Computed: true, 15 }, 16 "name": &schema.Schema{ 17 Type: schema.TypeString, 18 Required: true, 19 }, 20 "key": &schema.Schema{ 21 Type: schema.TypeString, 22 Computed: true, 23 }, 24 "teams": &schema.Schema{ 25 Type: schema.TypeList, 26 Optional: true, 27 Elem: &schema.Schema{Type: schema.TypeString}, 28 }, 29 } 30 s = addPermsSchema(s) 31 return &schema.Resource{ 32 Schema: s, 33 Create: ApikeyCreate, 34 Read: ApikeyRead, 35 Update: ApikeyUpdate, 36 Delete: ApikeyDelete, 37 } 38 } 39 40 func apikeyToResourceData(d *schema.ResourceData, k *account.APIKey) error { 41 d.SetId(k.ID) 42 d.Set("name", k.Name) 43 d.Set("key", k.Key) 44 d.Set("teams", k.TeamIDs) 45 permissionsToResourceData(d, k.Permissions) 46 return nil 47 } 48 49 func resourceDataToApikey(k *account.APIKey, d *schema.ResourceData) error { 50 k.ID = d.Id() 51 k.Name = d.Get("name").(string) 52 if v, ok := d.GetOk("teams"); ok { 53 teamsRaw := v.([]interface{}) 54 k.TeamIDs = make([]string, len(teamsRaw)) 55 for i, team := range teamsRaw { 56 k.TeamIDs[i] = team.(string) 57 } 58 } else { 59 k.TeamIDs = make([]string, 0) 60 } 61 k.Permissions = resourceDataToPermissions(d) 62 return nil 63 } 64 65 // ApikeyCreate creates ns1 API key 66 func ApikeyCreate(d *schema.ResourceData, meta interface{}) error { 67 client := meta.(*ns1.Client) 68 k := account.APIKey{} 69 if err := resourceDataToApikey(&k, d); err != nil { 70 return err 71 } 72 if _, err := client.APIKeys.Create(&k); err != nil { 73 return err 74 } 75 return apikeyToResourceData(d, &k) 76 } 77 78 // ApikeyRead reads API key from ns1 79 func ApikeyRead(d *schema.ResourceData, meta interface{}) error { 80 client := meta.(*ns1.Client) 81 k, _, err := client.APIKeys.Get(d.Id()) 82 if err != nil { 83 return err 84 } 85 return apikeyToResourceData(d, k) 86 } 87 88 //ApikeyDelete deletes the given ns1 api key 89 func ApikeyDelete(d *schema.ResourceData, meta interface{}) error { 90 client := meta.(*ns1.Client) 91 _, err := client.APIKeys.Delete(d.Id()) 92 d.SetId("") 93 return err 94 } 95 96 //ApikeyUpdate updates the given api key in ns1 97 func ApikeyUpdate(d *schema.ResourceData, meta interface{}) error { 98 client := meta.(*ns1.Client) 99 k := account.APIKey{ 100 ID: d.Id(), 101 } 102 if err := resourceDataToApikey(&k, d); err != nil { 103 return err 104 } 105 if _, err := client.APIKeys.Update(&k); err != nil { 106 return err 107 } 108 return apikeyToResourceData(d, &k) 109 }