-
Notifications
You must be signed in to change notification settings - Fork 134
/
resource_tc_cos_bucket_object.go
317 lines (281 loc) · 9.63 KB
/
resource_tc_cos_bucket_object.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package cos
import (
"bytes"
"context"
"fmt"
"io"
"log"
"os"
"strings"
tccommon "github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/common"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/mitchellh/go-homedir"
)
func ResourceTencentCloudCosBucketObject() *schema.Resource {
return &schema.Resource{
Create: resourceTencentCloudCosBucketObjectCreate,
Read: resourceTencentCloudCosBucketObjectRead,
Update: resourceTencentCloudCosBucketObjectUpdate,
Delete: resourceTencentCloudCosBucketObjectDelete,
Schema: map[string]*schema.Schema{
"bucket": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of a bucket to use. Bucket format should be [custom name]-[appid], for example `mycos-1258798060`.",
},
"key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the object once it is in the bucket.",
},
"source": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"content"},
Description: "The path to the source file being uploaded to the bucket.",
},
"content": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"source"},
Description: "Literal string value to use as the object content, which will be uploaded as UTF-8-encoded text.",
},
"acl": {
Type: schema.TypeString,
Optional: true,
Default: s3.ObjectCannedACLPrivate,
ValidateFunc: tccommon.ValidateAllowedStringValue([]string{
s3.ObjectCannedACLPrivate,
s3.ObjectCannedACLPublicRead,
s3.ObjectCannedACLPublicReadWrite,
}),
Description: "The canned ACL to apply. Available values include `private`, `public-read`, and `public-read-write`. Defaults to `private`.",
},
"cache_control": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Specifies caching behavior along the request/reply chain. For further details, RFC2616 can be referred.",
},
"content_disposition": {
Type: schema.TypeString,
Optional: true,
Description: "Specifies presentational information for the object.",
},
"content_encoding": {
Type: schema.TypeString,
Optional: true,
Description: "Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field.",
},
"tags": {
Type: schema.TypeMap,
Optional: true,
Description: "Tag of the object.",
},
"content_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "A standard MIME type describing the format of the object data.",
},
"storage_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Object storage type, Available values include `STANDARD_IA`, `MAZ_STANDARD_IA`, `INTELLIGENT_TIERING`, `MAZ_INTELLIGENT_TIERING`, `ARCHIVE`, `DEEP_ARCHIVE`. For more information, please refer to: https://cloud.tencent.com/document/product/436/33417.",
},
"etag": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The ETag generated for the object (an MD5 sum of the object content).",
},
},
}
}
func resourceTencentCloudCosBucketObjectCreate(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cos_bucket_object.create")()
logId := tccommon.GetLogId(tccommon.ContextNil)
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
var body io.ReadSeeker
if v, ok := d.GetOk("source"); ok {
source := v.(string)
path, err := homedir.Expand(source)
if err != nil {
return fmt.Errorf("cos object source (%s) homedir expand error: %s", source, err.Error())
}
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("cos object source (%s) open error: %s", source, err.Error())
}
body = file
defer func() {
err := file.Close()
if err != nil {
log.Printf("closing cos object source (%s) error: %s", path, err.Error())
}
}()
} else if v, ok := d.GetOk("content"); ok {
content := v.(string)
body = bytes.NewReader([]byte(content))
} else {
return fmt.Errorf("must specify \"source\" or \"content\" field")
}
request := &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: body,
}
if v, ok := d.GetOk("acl"); ok {
request.ACL = aws.String(v.(string))
}
if v, ok := d.GetOk("cache_control"); ok {
request.CacheControl = aws.String(v.(string))
}
if v, ok := d.GetOk("content_disposition"); ok {
request.ContentDisposition = aws.String(v.(string))
}
if v, ok := d.GetOk("content_encoding"); ok {
request.ContentEncoding = aws.String(v.(string))
}
if v, ok := d.GetOk("content_type"); ok {
request.ContentType = aws.String(v.(string))
}
if v, ok := d.GetOk("storage_class"); ok {
request.StorageClass = aws.String(v.(string))
}
response, err := meta.(tccommon.ProviderMeta).GetAPIV3Conn().UseCosClient().PutObject(request)
if err != nil {
return fmt.Errorf("putting object (%s) in cos bucket (%s) error: %s", key, bucket, err.Error())
}
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n",
logId, "put object", request.String(), response.String())
if v, ok := d.GetOk("tags"); ok {
ctx := context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
service := CosService{
client: meta.(tccommon.ProviderMeta).GetAPIV3Conn(),
}
tags := make(map[string]string)
for key, val := range v.(map[string]interface{}) {
tags[key] = val.(string)
}
if err := service.SetObjectTags(ctx, bucket, key, tags); err != nil {
log.Printf("[WARN] set object tags error, skip processing")
}
}
d.SetId(bucket + key)
return resourceTencentCloudCosBucketObjectRead(d, meta)
}
func resourceTencentCloudCosBucketObjectRead(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cos_bucket_object.read")()
logId := tccommon.GetLogId(tccommon.ContextNil)
ctx := context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
cosService := CosService{
client: meta.(tccommon.ProviderMeta).GetAPIV3Conn(),
}
response, err := cosService.HeadObject(ctx, bucket, key)
if err != nil {
if awsError, ok := err.(awserr.RequestFailure); ok && awsError.StatusCode() == 404 {
log.Printf("[WARN]%s object (%s) in bucket (%s) not found, error code (404)", logId, key, bucket)
d.SetId("")
return nil
}
return err
}
_ = d.Set("cache_control", response.CacheControl)
_ = d.Set("content_disposition", response.ContentDisposition)
_ = d.Set("content_encoding", response.ContentEncoding)
_ = d.Set("content_type", response.ContentType)
_ = d.Set("etag", strings.Trim(*response.ETag, `"`))
_ = d.Set("storage_class", s3.StorageClassStandard)
if response.StorageClass != nil {
_ = d.Set("storage_class", response.StorageClass)
}
_, aclResponse, aclErr := meta.(tccommon.ProviderMeta).GetAPIV3Conn().UseTencentCosClient(bucket).Object.GetACL(ctx, key)
if aclErr != nil {
return fmt.Errorf("cos [GetACL] error: %s, bucket: %s, object: %s", aclErr.Error(), bucket, key)
}
if aclResponse.StatusCode == 404 {
log.Printf("[WARN] [GetACL] returns %d, %s", 404, err)
return nil
}
_ = d.Set("acl", aclResponse.Header.Get("x-cos-acl"))
var tags map[string]string
tags, err = cosService.GetObjectTags(ctx, bucket, key)
if err != nil {
if awsError, ok := err.(awserr.RequestFailure); ok && awsError.StatusCode() == 404 {
log.Printf("[WARN]%s tags in object (%s) of bucket (%s) not found, error code (404)", logId, key, bucket)
d.SetId("")
return nil
}
return err
}
_ = d.Set("tags", tags)
return nil
}
func resourceTencentCloudCosBucketObjectUpdate(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cos_bucket_object.update")()
logId := tccommon.GetLogId(tccommon.ContextNil)
ctx := context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
fields := []string{
"cache_control",
"content_disposition",
"content_encoding",
"content_type",
"source",
"content",
"storage_class",
"etag",
}
for _, key := range fields {
if d.HasChange(key) {
return resourceTencentCloudCosBucketObjectCreate(d, meta)
}
}
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
cosService := CosService{
client: meta.(tccommon.ProviderMeta).GetAPIV3Conn(),
}
if d.HasChange("acl") {
acl := d.Get("acl").(string)
err := cosService.PutObjectAcl(ctx, bucket, key, acl)
if err != nil {
return err
}
}
if d.HasChange("tags") {
v := d.Get("tags").(map[string]interface{})
tags := make(map[string]string)
for key, val := range v {
tags[key] = val.(string)
}
if err := cosService.SetObjectTags(ctx, bucket, key, tags); err != nil {
return err
}
}
return nil
}
func resourceTencentCloudCosBucketObjectDelete(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cos_bucket_object.delete")()
logId := tccommon.GetLogId(tccommon.ContextNil)
ctx := context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
cosService := CosService{
client: meta.(tccommon.ProviderMeta).GetAPIV3Conn(),
}
err := cosService.DeleteObject(ctx, bucket, key)
if err != nil {
return err
}
return nil
}