github.com/andresvia/terraform@v0.6.15-0.20160412045437-d51c75946785/builtin/providers/aws/resource_aws_lambda_function.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "log" 7 "time" 8 9 "github.com/aws/aws-sdk-go/aws" 10 "github.com/aws/aws-sdk-go/aws/awserr" 11 "github.com/aws/aws-sdk-go/service/lambda" 12 "github.com/mitchellh/go-homedir" 13 14 "errors" 15 16 "github.com/hashicorp/terraform/helper/resource" 17 "github.com/hashicorp/terraform/helper/schema" 18 ) 19 20 func resourceAwsLambdaFunction() *schema.Resource { 21 return &schema.Resource{ 22 Create: resourceAwsLambdaFunctionCreate, 23 Read: resourceAwsLambdaFunctionRead, 24 Update: resourceAwsLambdaFunctionUpdate, 25 Delete: resourceAwsLambdaFunctionDelete, 26 27 Schema: map[string]*schema.Schema{ 28 "filename": &schema.Schema{ 29 Type: schema.TypeString, 30 Optional: true, 31 ConflictsWith: []string{"s3_bucket", "s3_key", "s3_object_version"}, 32 }, 33 "s3_bucket": &schema.Schema{ 34 Type: schema.TypeString, 35 Optional: true, 36 ConflictsWith: []string{"filename"}, 37 }, 38 "s3_key": &schema.Schema{ 39 Type: schema.TypeString, 40 Optional: true, 41 ConflictsWith: []string{"filename"}, 42 }, 43 "s3_object_version": &schema.Schema{ 44 Type: schema.TypeString, 45 Optional: true, 46 ConflictsWith: []string{"filename"}, 47 }, 48 "description": &schema.Schema{ 49 Type: schema.TypeString, 50 Optional: true, 51 }, 52 "function_name": &schema.Schema{ 53 Type: schema.TypeString, 54 Required: true, 55 ForceNew: true, 56 }, 57 "handler": &schema.Schema{ 58 Type: schema.TypeString, 59 Required: true, 60 }, 61 "memory_size": &schema.Schema{ 62 Type: schema.TypeInt, 63 Optional: true, 64 Default: 128, 65 }, 66 "role": &schema.Schema{ 67 Type: schema.TypeString, 68 Required: true, 69 }, 70 "runtime": &schema.Schema{ 71 Type: schema.TypeString, 72 Optional: true, 73 ForceNew: true, 74 Default: "nodejs", 75 }, 76 "timeout": &schema.Schema{ 77 Type: schema.TypeInt, 78 Optional: true, 79 Default: 3, 80 }, 81 "vpc_config": &schema.Schema{ 82 Type: schema.TypeList, 83 Optional: true, 84 ForceNew: true, 85 Elem: &schema.Resource{ 86 Schema: map[string]*schema.Schema{ 87 "subnet_ids": &schema.Schema{ 88 Type: schema.TypeSet, 89 Required: true, 90 ForceNew: true, 91 Elem: &schema.Schema{Type: schema.TypeString}, 92 Set: schema.HashString, 93 }, 94 "security_group_ids": &schema.Schema{ 95 Type: schema.TypeSet, 96 Required: true, 97 ForceNew: true, 98 Elem: &schema.Schema{Type: schema.TypeString}, 99 Set: schema.HashString, 100 }, 101 }, 102 }, 103 }, 104 "arn": &schema.Schema{ 105 Type: schema.TypeString, 106 Computed: true, 107 }, 108 "last_modified": &schema.Schema{ 109 Type: schema.TypeString, 110 Computed: true, 111 }, 112 "source_code_hash": &schema.Schema{ 113 Type: schema.TypeString, 114 Optional: true, 115 Computed: true, 116 }, 117 }, 118 } 119 } 120 121 // resourceAwsLambdaFunction maps to: 122 // CreateFunction in the API / SDK 123 func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error { 124 conn := meta.(*AWSClient).lambdaconn 125 126 functionName := d.Get("function_name").(string) 127 iamRole := d.Get("role").(string) 128 129 log.Printf("[DEBUG] Creating Lambda Function %s with role %s", functionName, iamRole) 130 131 var functionCode *lambda.FunctionCode 132 if v, ok := d.GetOk("filename"); ok { 133 file, err := loadFileContent(v.(string)) 134 if err != nil { 135 return fmt.Errorf("Unable to load %q: %s", v.(string), err) 136 } 137 functionCode = &lambda.FunctionCode{ 138 ZipFile: file, 139 } 140 } else { 141 s3Bucket, bucketOk := d.GetOk("s3_bucket") 142 s3Key, keyOk := d.GetOk("s3_key") 143 s3ObjectVersion, versionOk := d.GetOk("s3_object_version") 144 if !bucketOk || !keyOk { 145 return errors.New("s3_bucket and s3_key must all be set while using S3 code source") 146 } 147 functionCode = &lambda.FunctionCode{ 148 S3Bucket: aws.String(s3Bucket.(string)), 149 S3Key: aws.String(s3Key.(string)), 150 } 151 if versionOk { 152 functionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string)) 153 } 154 } 155 156 params := &lambda.CreateFunctionInput{ 157 Code: functionCode, 158 Description: aws.String(d.Get("description").(string)), 159 FunctionName: aws.String(functionName), 160 Handler: aws.String(d.Get("handler").(string)), 161 MemorySize: aws.Int64(int64(d.Get("memory_size").(int))), 162 Role: aws.String(iamRole), 163 Runtime: aws.String(d.Get("runtime").(string)), 164 Timeout: aws.Int64(int64(d.Get("timeout").(int))), 165 } 166 167 if v, ok := d.GetOk("vpc_config"); ok { 168 config, err := validateVPCConfig(v) 169 if err != nil { 170 return err 171 } 172 173 var subnetIds []*string 174 for _, id := range config["subnet_ids"].(*schema.Set).List() { 175 subnetIds = append(subnetIds, aws.String(id.(string))) 176 } 177 178 var securityGroupIds []*string 179 for _, id := range config["security_group_ids"].(*schema.Set).List() { 180 securityGroupIds = append(securityGroupIds, aws.String(id.(string))) 181 } 182 183 params.VpcConfig = &lambda.VpcConfig{ 184 SubnetIds: subnetIds, 185 SecurityGroupIds: securityGroupIds, 186 } 187 } 188 189 // IAM profiles can take ~10 seconds to propagate in AWS: 190 // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console 191 // Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda. 192 err := resource.Retry(1*time.Minute, func() *resource.RetryError { 193 _, err := conn.CreateFunction(params) 194 if err != nil { 195 log.Printf("[ERROR] Received %q, retrying CreateFunction", err) 196 if awserr, ok := err.(awserr.Error); ok { 197 if awserr.Code() == "InvalidParameterValueException" { 198 log.Printf("[DEBUG] InvalidParameterValueException creating Lambda Function: %s", awserr) 199 return resource.RetryableError(awserr) 200 } 201 } 202 log.Printf("[DEBUG] Error creating Lambda Function: %s", err) 203 return resource.NonRetryableError(err) 204 } 205 return nil 206 }) 207 if err != nil { 208 return fmt.Errorf("Error creating Lambda function: %s", err) 209 } 210 211 d.SetId(d.Get("function_name").(string)) 212 213 return resourceAwsLambdaFunctionRead(d, meta) 214 } 215 216 // resourceAwsLambdaFunctionRead maps to: 217 // GetFunction in the API / SDK 218 func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) error { 219 conn := meta.(*AWSClient).lambdaconn 220 221 log.Printf("[DEBUG] Fetching Lambda Function: %s", d.Id()) 222 223 params := &lambda.GetFunctionInput{ 224 FunctionName: aws.String(d.Get("function_name").(string)), 225 } 226 227 getFunctionOutput, err := conn.GetFunction(params) 228 if err != nil { 229 if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ResourceNotFoundException" { 230 d.SetId("") 231 return nil 232 } 233 return err 234 } 235 236 // getFunctionOutput.Code.Location is a pre-signed URL pointing at the zip 237 // file that we uploaded when we created the resource. You can use it to 238 // download the code from AWS. The other part is 239 // getFunctionOutput.Configuration which holds metadata. 240 241 function := getFunctionOutput.Configuration 242 // TODO error checking / handling on the Set() calls. 243 d.Set("arn", function.FunctionArn) 244 d.Set("description", function.Description) 245 d.Set("handler", function.Handler) 246 d.Set("memory_size", function.MemorySize) 247 d.Set("last_modified", function.LastModified) 248 d.Set("role", function.Role) 249 d.Set("runtime", function.Runtime) 250 d.Set("timeout", function.Timeout) 251 if config := flattenLambdaVpcConfigResponse(function.VpcConfig); len(config) > 0 { 252 d.Set("vpc_config", config) 253 } 254 d.Set("source_code_hash", function.CodeSha256) 255 256 return nil 257 } 258 259 // resourceAwsLambdaFunction maps to: 260 // DeleteFunction in the API / SDK 261 func resourceAwsLambdaFunctionDelete(d *schema.ResourceData, meta interface{}) error { 262 conn := meta.(*AWSClient).lambdaconn 263 264 log.Printf("[INFO] Deleting Lambda Function: %s", d.Id()) 265 266 params := &lambda.DeleteFunctionInput{ 267 FunctionName: aws.String(d.Get("function_name").(string)), 268 } 269 270 _, err := conn.DeleteFunction(params) 271 if err != nil { 272 return fmt.Errorf("Error deleting Lambda Function: %s", err) 273 } 274 275 d.SetId("") 276 277 return nil 278 } 279 280 // resourceAwsLambdaFunctionUpdate maps to: 281 // UpdateFunctionCode in the API / SDK 282 func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) error { 283 conn := meta.(*AWSClient).lambdaconn 284 285 d.Partial(true) 286 287 codeReq := &lambda.UpdateFunctionCodeInput{ 288 FunctionName: aws.String(d.Id()), 289 } 290 291 codeUpdate := false 292 if v, ok := d.GetOk("filename"); ok && d.HasChange("source_code_hash") { 293 file, err := loadFileContent(v.(string)) 294 if err != nil { 295 return fmt.Errorf("Unable to load %q: %s", v.(string), err) 296 } 297 codeReq.ZipFile = file 298 codeUpdate = true 299 } 300 if d.HasChange("s3_bucket") || d.HasChange("s3_key") || d.HasChange("s3_object_version") { 301 codeReq.S3Bucket = aws.String(d.Get("s3_bucket").(string)) 302 codeReq.S3Key = aws.String(d.Get("s3_key").(string)) 303 codeReq.S3ObjectVersion = aws.String(d.Get("s3_object_version").(string)) 304 codeUpdate = true 305 } 306 307 log.Printf("[DEBUG] Send Update Lambda Function Code request: %#v", codeReq) 308 if codeUpdate { 309 _, err := conn.UpdateFunctionCode(codeReq) 310 if err != nil { 311 return fmt.Errorf("Error modifying Lambda Function Code %s: %s", d.Id(), err) 312 } 313 314 d.SetPartial("filename") 315 d.SetPartial("source_code_hash") 316 d.SetPartial("s3_bucket") 317 d.SetPartial("s3_key") 318 d.SetPartial("s3_object_version") 319 } 320 321 configReq := &lambda.UpdateFunctionConfigurationInput{ 322 FunctionName: aws.String(d.Id()), 323 } 324 325 configUpdate := false 326 if d.HasChange("description") { 327 configReq.Description = aws.String(d.Get("description").(string)) 328 configUpdate = true 329 } 330 if d.HasChange("handler") { 331 configReq.Handler = aws.String(d.Get("handler").(string)) 332 configUpdate = true 333 } 334 if d.HasChange("memory_size") { 335 configReq.MemorySize = aws.Int64(int64(d.Get("memory_size").(int))) 336 configUpdate = true 337 } 338 if d.HasChange("role") { 339 configReq.Role = aws.String(d.Get("role").(string)) 340 configUpdate = true 341 } 342 if d.HasChange("timeout") { 343 configReq.Timeout = aws.Int64(int64(d.Get("timeout").(int))) 344 configUpdate = true 345 } 346 347 log.Printf("[DEBUG] Send Update Lambda Function Configuration request: %#v", configReq) 348 if configUpdate { 349 _, err := conn.UpdateFunctionConfiguration(configReq) 350 if err != nil { 351 return fmt.Errorf("Error modifying Lambda Function Configuration %s: %s", d.Id(), err) 352 } 353 d.SetPartial("description") 354 d.SetPartial("handler") 355 d.SetPartial("memory_size") 356 d.SetPartial("role") 357 d.SetPartial("timeout") 358 } 359 d.Partial(false) 360 361 return resourceAwsLambdaFunctionRead(d, meta) 362 } 363 364 // loadFileContent returns contents of a file in a given path 365 func loadFileContent(v string) ([]byte, error) { 366 filename, err := homedir.Expand(v) 367 if err != nil { 368 return nil, err 369 } 370 fileContent, err := ioutil.ReadFile(filename) 371 if err != nil { 372 return nil, err 373 } 374 return fileContent, nil 375 } 376 377 func validateVPCConfig(v interface{}) (map[string]interface{}, error) { 378 configs := v.([]interface{}) 379 if len(configs) > 1 { 380 return nil, errors.New("Only a single vpc_config block is expected") 381 } 382 383 config, ok := configs[0].(map[string]interface{}) 384 385 if !ok { 386 return nil, errors.New("vpc_config is <nil>") 387 } 388 389 if config["subnet_ids"].(*schema.Set).Len() == 0 { 390 return nil, errors.New("vpc_config.subnet_ids cannot be empty") 391 } 392 393 if config["security_group_ids"].(*schema.Set).Len() == 0 { 394 return nil, errors.New("vpc_config.security_group_ids cannot be empty") 395 } 396 397 return config, nil 398 }