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