github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/chef/resource_data_bag_item.go (about) 1 package chef 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "github.com/hashicorp/terraform/helper/schema" 8 9 chefc "github.com/go-chef/chef" 10 ) 11 12 func resourceChefDataBagItem() *schema.Resource { 13 return &schema.Resource{ 14 Create: CreateDataBagItem, 15 Read: ReadDataBagItem, 16 Delete: DeleteDataBagItem, 17 18 Schema: map[string]*schema.Schema{ 19 "data_bag_name": &schema.Schema{ 20 Type: schema.TypeString, 21 Required: true, 22 ForceNew: true, 23 }, 24 "content_json": &schema.Schema{ 25 Type: schema.TypeString, 26 Required: true, 27 ForceNew: true, 28 StateFunc: jsonStateFunc, 29 }, 30 "id": &schema.Schema{ 31 Type: schema.TypeString, 32 Computed: true, 33 }, 34 }, 35 } 36 } 37 38 func CreateDataBagItem(d *schema.ResourceData, meta interface{}) error { 39 client := meta.(*chefc.Client) 40 41 dataBagName := d.Get("data_bag_name").(string) 42 itemId, itemContent, err := prepareDataBagItemContent(d.Get("content_json").(string)) 43 if err != nil { 44 return err 45 } 46 47 err = client.DataBags.CreateItem(dataBagName, itemContent) 48 if err != nil { 49 return err 50 } 51 52 d.SetId(itemId) 53 d.Set("id", itemId) 54 return nil 55 } 56 57 func ReadDataBagItem(d *schema.ResourceData, meta interface{}) error { 58 client := meta.(*chefc.Client) 59 60 // The Chef API provides no API to read a data bag's metadata, 61 // but we can try to read its items and use that as a proxy for 62 // whether it still exists. 63 64 itemId := d.Id() 65 dataBagName := d.Get("data_bag_name").(string) 66 67 value, err := client.DataBags.GetItem(dataBagName, itemId) 68 if err != nil { 69 if errRes, ok := err.(*chefc.ErrorResponse); ok { 70 if errRes.Response.StatusCode == 404 { 71 d.SetId("") 72 return nil 73 } 74 } else { 75 return err 76 } 77 } 78 79 jsonContent, err := json.Marshal(value) 80 if err != nil { 81 return err 82 } 83 84 d.Set("content_json", string(jsonContent)) 85 86 return nil 87 } 88 89 func DeleteDataBagItem(d *schema.ResourceData, meta interface{}) error { 90 client := meta.(*chefc.Client) 91 92 itemId := d.Id() 93 dataBagName := d.Get("data_bag_name").(string) 94 95 err := client.DataBags.DeleteItem(dataBagName, itemId) 96 if err == nil { 97 d.SetId("") 98 d.Set("id", "") 99 } 100 return err 101 } 102 103 func prepareDataBagItemContent(contentJson string) (string, interface{}, error) { 104 var value map[string]interface{} 105 err := json.Unmarshal([]byte(contentJson), &value) 106 if err != nil { 107 return "", nil, err 108 } 109 110 var itemId string 111 if itemIdI, ok := value["id"]; ok { 112 itemId, _ = itemIdI.(string) 113 } 114 115 if itemId == "" { 116 return "", nil, fmt.Errorf("content_json must have id attribute, set to a string") 117 } 118 119 return itemId, value, nil 120 }