forked from aliyun/terraform-provider-alicloud
/
resource_alicloud_fc_function.go
296 lines (262 loc) · 8.07 KB
/
resource_alicloud_fc_function.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
package alicloud
import (
"fmt"
"time"
"strings"
"github.com/aliyun/fc-go-sdk"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAlicloudFCFunction() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCFunctionCreate,
Read: resourceAlicloudFCFunctionRead,
Update: resourceAlicloudFCFunctionUpdate,
Delete: resourceAlicloudFCFunctionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validateStringLengthInRange(1, 128),
},
"name_prefix": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// uuid is 26 characters, limit the prefix to 229.
value := v.(string)
if len(value) > 122 {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than 102 characters, name is limited to 128", k))
}
return
},
},
"oss_bucket": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"filename"},
},
"oss_key": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"filename"},
},
"filename": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"oss_bucket", "oss_key"},
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"handler": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"memory_size": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 128,
ValidateFunc: validateIntegerInRange(128, 3072),
},
"runtime": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
"last_modified": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudFCFunctionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*AliyunClient)
conn, err := client.Fcconn()
if err != nil {
return err
}
serviceName := d.Get("service").(string)
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
input := &fc.CreateFunctionInput{
ServiceName: StringPointer(serviceName),
}
object := fc.FunctionCreateObject{
FunctionName: StringPointer(name),
Description: StringPointer(d.Get("description").(string)),
Runtime: StringPointer(d.Get("runtime").(string)),
Handler: StringPointer(d.Get("handler").(string)),
Timeout: Int32Pointer(int32(d.Get("timeout").(int))),
MemorySize: Int32Pointer(int32(d.Get("memory_size").(int))),
}
code, err := getFunctionCode(d)
if err != nil {
return err
}
object.Code = code
input.FunctionCreateObject = object
var function *fc.CreateFunctionOutput
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
out, err := conn.CreateFunction(input)
if err != nil {
if IsExceptedErrors(err, []string{AccessDenied}) {
return resource.RetryableError(fmt.Errorf("Error creating function compute service got an error: %#v", err))
}
return resource.NonRetryableError(fmt.Errorf("Error creating function compute service got an error: %#v", err))
}
function = out
return nil
}); err != nil {
return err
}
if function == nil {
return fmt.Errorf("Creating function compute function got a empty response: %#v.", function)
}
d.SetId(fmt.Sprintf("%s%s%s", serviceName, COLON_SEPARATED, *function.FunctionName))
return resourceAlicloudFCFunctionRead(d, meta)
}
func resourceAlicloudFCFunctionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*AliyunClient)
split := strings.Split(d.Id(), COLON_SEPARATED)
if len(split) < 2 {
return fmt.Errorf("Invalid resource ID %s. Please check it and try again.", d.Id())
}
function, err := client.DescribeFcFunction(split[0], split[1])
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return fmt.Errorf("DescribeFCFunction %s got an error: %#v", d.Id(), err)
}
d.Set("service", split[0])
d.Set("name", function.FunctionName)
d.Set("description", function.Description)
d.Set("handler", function.Handler)
d.Set("memory_size", function.MemorySize)
d.Set("runtime", function.Runtime)
d.Set("timeout", function.Timeout)
d.Set("last_modified", function.LastModifiedTime)
return nil
}
func resourceAlicloudFCFunctionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*AliyunClient)
conn, err := client.Fcconn()
if err != nil {
return err
}
d.Partial(true)
updateInput := &fc.UpdateFunctionInput{}
update := false
if d.HasChange("filename") || d.HasChange("oss_bucket") || d.HasChange("oss_key") {
update = true
d.SetPartial("filename")
d.SetPartial("oss_bucket")
d.SetPartial("oss_key")
}
if d.HasChange("description") {
updateInput.Description = StringPointer(d.Get("description").(string))
d.SetPartial("description")
}
if d.HasChange("handler") {
updateInput.Handler = StringPointer(d.Get("handler").(string))
d.SetPartial("handler")
}
if d.HasChange("memory_size") {
updateInput.MemorySize = Int32Pointer(int32(d.Get("memory_size").(int)))
d.SetPartial("memory_size")
}
if d.HasChange("timeout") {
updateInput.Timeout = Int32Pointer(int32(d.Get("timeout").(int)))
d.SetPartial("timeout")
}
if d.HasChange("runtime") {
updateInput.Runtime = StringPointer(d.Get("runtime").(string))
d.SetPartial("runtime")
}
if updateInput != nil || update {
split := strings.Split(d.Id(), COLON_SEPARATED)
updateInput.ServiceName = StringPointer(split[0])
updateInput.FunctionName = StringPointer(split[1])
code, err := getFunctionCode(d)
if err != nil {
return err
}
updateInput.Code = code
if _, err := conn.UpdateFunction(updateInput); err != nil {
return fmt.Errorf("UpdateFunction %s got an error: %#v.", d.Id(), err)
}
}
d.Partial(false)
return resourceAlicloudFCFunctionRead(d, meta)
}
func resourceAlicloudFCFunctionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*AliyunClient)
conn, err := client.Fcconn()
if err != nil {
return err
}
split := strings.Split(d.Id(), COLON_SEPARATED)
return resource.Retry(5*time.Minute, func() *resource.RetryError {
if _, err := conn.DeleteFunction(&fc.DeleteFunctionInput{
ServiceName: StringPointer(split[0]),
FunctionName: StringPointer(split[1]),
}); err != nil {
if IsExceptedErrors(err, []string{ServiceNotFound, FunctionNotFound}) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Deleting function got an error: %#v.", err))
}
if _, err := client.DescribeFcFunction(split[0], split[1]); err != nil {
if NotFoundError(err) {
return nil
}
return resource.RetryableError(fmt.Errorf("While deleting function, getting function %s got an error: %#v.", d.Id(), err))
}
return nil
})
}
func getFunctionCode(d *schema.ResourceData) (*fc.Code, error) {
code := fc.NewCode()
if filename, ok := d.GetOk("filename"); ok && filename.(string) != "" {
file, err := loadFileContent(filename.(string))
if err != nil {
return code, fmt.Errorf("Unable to load %q: %s", filename.(string), err)
}
code.WithZipFile(file)
} else {
bucket, bucketOk := d.GetOk("oss_bucket")
key, keyOk := d.GetOk("oss_key")
if !bucketOk || !keyOk {
return code, fmt.Errorf("'oss_bucket' and 'oss_key' must all be set while using OSS code source.")
}
code.WithOSSBucketName(bucket.(string)).WithOSSObjectName(key.(string))
}
return code, nil
}