forked from hashicorp/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_dynamodb_table_item.go
295 lines (248 loc) · 7.46 KB
/
resource_aws_dynamodb_table_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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package aws
import (
"fmt"
"log"
"reflect"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsDynamoDbTableItem() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDynamoDbTableItemCreate,
Read: resourceAwsDynamoDbTableItemRead,
Update: resourceAwsDynamoDbTableItemUpdate,
Delete: resourceAwsDynamoDbTableItemDelete,
Schema: map[string]*schema.Schema{
"table_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"hash_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"range_key": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"item": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateDynamoDbTableItem,
},
},
}
}
func validateDynamoDbTableItem(v interface{}, k string) (ws []string, errors []error) {
_, err := expandDynamoDbTableItemAttributes(v.(string))
if err != nil {
errors = append(errors, fmt.Errorf("Invalid format of %q: %s", k, err))
}
return
}
func resourceAwsDynamoDbTableItemCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
tableName := d.Get("table_name").(string)
hashKey := d.Get("hash_key").(string)
item := d.Get("item").(string)
attributes, err := expandDynamoDbTableItemAttributes(item)
if err != nil {
return err
}
log.Printf("[DEBUG] DynamoDB item create: %s", tableName)
_, err = conn.PutItem(&dynamodb.PutItemInput{
Item: attributes,
// Explode if item exists. We didn't create it.
Expected: map[string]*dynamodb.ExpectedAttributeValue{
hashKey: {
Exists: aws.Bool(false),
},
},
TableName: aws.String(tableName),
})
if err != nil {
return err
}
rangeKey := d.Get("range_key").(string)
id := buildDynamoDbTableItemId(tableName, hashKey, rangeKey, attributes)
d.SetId(id)
return resourceAwsDynamoDbTableItemRead(d, meta)
}
func resourceAwsDynamoDbTableItemUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Updating DynamoDB table %s", d.Id())
conn := meta.(*AWSClient).dynamodbconn
if d.HasChange("item") {
tableName := d.Get("table_name").(string)
hashKey := d.Get("hash_key").(string)
rangeKey := d.Get("range_key").(string)
oldItem, newItem := d.GetChange("item")
attributes, err := expandDynamoDbTableItemAttributes(newItem.(string))
if err != nil {
return err
}
newQueryKey := buildDynamoDbTableItemQueryKey(attributes, hashKey, rangeKey)
updates := map[string]*dynamodb.AttributeValueUpdate{}
for key, value := range attributes {
// Hash keys are not updatable, so we'll basically create
// a new record and delete the old one below
if key == hashKey {
continue
}
updates[key] = &dynamodb.AttributeValueUpdate{
Action: aws.String(dynamodb.AttributeActionPut),
Value: value,
}
}
_, err = conn.UpdateItem(&dynamodb.UpdateItemInput{
AttributeUpdates: updates,
TableName: aws.String(tableName),
Key: newQueryKey,
})
if err != nil {
return err
}
oItem := oldItem.(string)
oldAttributes, err := expandDynamoDbTableItemAttributes(oItem)
if err != nil {
return err
}
// New record is created via UpdateItem in case we're changing hash key
// so we need to get rid of the old one
oldQueryKey := buildDynamoDbTableItemQueryKey(oldAttributes, hashKey, rangeKey)
if !reflect.DeepEqual(oldQueryKey, newQueryKey) {
log.Printf("[DEBUG] Deleting old record: %#v", oldQueryKey)
_, err := conn.DeleteItem(&dynamodb.DeleteItemInput{
Key: oldQueryKey,
TableName: aws.String(tableName),
})
if err != nil {
return err
}
}
id := buildDynamoDbTableItemId(tableName, hashKey, rangeKey, attributes)
d.SetId(id)
}
return resourceAwsDynamoDbTableItemRead(d, meta)
}
func resourceAwsDynamoDbTableItemRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
log.Printf("[DEBUG] Loading data for DynamoDB table item '%s'", d.Id())
tableName := d.Get("table_name").(string)
hashKey := d.Get("hash_key").(string)
rangeKey := d.Get("range_key").(string)
attributes, err := expandDynamoDbTableItemAttributes(d.Get("item").(string))
if err != nil {
return err
}
result, err := conn.GetItem(&dynamodb.GetItemInput{
TableName: aws.String(tableName),
ConsistentRead: aws.Bool(true),
Key: buildDynamoDbTableItemQueryKey(attributes, hashKey, rangeKey),
ProjectionExpression: buildDynamoDbProjectionExpression(attributes),
ExpressionAttributeNames: buildDynamoDbExpressionAttributeNames(attributes),
})
if err != nil {
if isAWSErr(err, dynamodb.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] Dynamodb Table Item (%s) not found, error code (404)", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving DynamoDB table item: %s", err)
}
if result.Item == nil {
log.Printf("[WARN] Dynamodb Table Item (%s) not found", d.Id())
d.SetId("")
return nil
}
// The record exists, now test if it differs from what is desired
if !reflect.DeepEqual(result.Item, attributes) {
itemAttrs, err := flattenDynamoDbTableItemAttributes(result.Item)
if err != nil {
return err
}
d.Set("item", itemAttrs)
id := buildDynamoDbTableItemId(tableName, hashKey, rangeKey, result.Item)
d.SetId(id)
}
return nil
}
func resourceAwsDynamoDbTableItemDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
attributes, err := expandDynamoDbTableItemAttributes(d.Get("item").(string))
if err != nil {
return err
}
hashKey := d.Get("hash_key").(string)
rangeKey := d.Get("range_key").(string)
queryKey := buildDynamoDbTableItemQueryKey(attributes, hashKey, rangeKey)
_, err = conn.DeleteItem(&dynamodb.DeleteItemInput{
Key: queryKey,
TableName: aws.String(d.Get("table_name").(string)),
})
return err
}
// Helpers
func buildDynamoDbExpressionAttributeNames(attrs map[string]*dynamodb.AttributeValue) map[string]*string {
names := map[string]*string{}
for key, _ := range attrs {
names["#a_"+key] = aws.String(key)
}
return names
}
func buildDynamoDbProjectionExpression(attrs map[string]*dynamodb.AttributeValue) *string {
keys := []string{}
for key, _ := range attrs {
keys = append(keys, key)
}
return aws.String("#a_" + strings.Join(keys, ", #a_"))
}
func buildDynamoDbTableItemId(tableName string, hashKey string, rangeKey string, attrs map[string]*dynamodb.AttributeValue) string {
hashVal := attrs[hashKey]
id := []string{
tableName,
hashKey,
base64Encode(hashVal.B),
}
if hashVal.S != nil {
id = append(id, *hashVal.S)
} else {
id = append(id, "")
}
if hashVal.N != nil {
id = append(id, *hashVal.N)
} else {
id = append(id, "")
}
if rangeKey != "" {
rangeVal := attrs[rangeKey]
id = append(id,
rangeKey,
base64Encode(rangeVal.B),
)
if rangeVal.S != nil {
id = append(id, *rangeVal.S)
} else {
id = append(id, "")
}
if rangeVal.N != nil {
id = append(id, *rangeVal.N)
} else {
id = append(id, "")
}
}
return strings.Join(id, "|")
}
func buildDynamoDbTableItemQueryKey(attrs map[string]*dynamodb.AttributeValue, hashKey string, rangeKey string) map[string]*dynamodb.AttributeValue {
queryKey := map[string]*dynamodb.AttributeValue{
hashKey: attrs[hashKey],
}
if rangeKey != "" {
queryKey[rangeKey] = attrs[rangeKey]
}
return queryKey
}