github.com/sixgill/terraform@v0.9.0-beta2.0.20170316214032-033f6226ae50/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 const awsMutexLambdaKey = `aws_lambda_function` 21 22 func resourceAwsLambdaFunction() *schema.Resource { 23 return &schema.Resource{ 24 Create: resourceAwsLambdaFunctionCreate, 25 Read: resourceAwsLambdaFunctionRead, 26 Update: resourceAwsLambdaFunctionUpdate, 27 Delete: resourceAwsLambdaFunctionDelete, 28 29 Importer: &schema.ResourceImporter{ 30 State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { 31 d.Set("function_name", d.Id()) 32 return []*schema.ResourceData{d}, nil 33 }, 34 }, 35 36 Schema: map[string]*schema.Schema{ 37 "filename": { 38 Type: schema.TypeString, 39 Optional: true, 40 ConflictsWith: []string{"s3_bucket", "s3_key", "s3_object_version"}, 41 }, 42 "s3_bucket": { 43 Type: schema.TypeString, 44 Optional: true, 45 ConflictsWith: []string{"filename"}, 46 }, 47 "s3_key": { 48 Type: schema.TypeString, 49 Optional: true, 50 ConflictsWith: []string{"filename"}, 51 }, 52 "s3_object_version": { 53 Type: schema.TypeString, 54 Optional: true, 55 ConflictsWith: []string{"filename"}, 56 }, 57 "description": { 58 Type: schema.TypeString, 59 Optional: true, 60 }, 61 "dead_letter_config": { 62 Type: schema.TypeList, 63 Optional: true, 64 ForceNew: true, 65 MinItems: 0, 66 MaxItems: 1, 67 Elem: &schema.Resource{ 68 Schema: map[string]*schema.Schema{ 69 "target_arn": { 70 Type: schema.TypeString, 71 Required: true, 72 ValidateFunc: validateArn, 73 }, 74 }, 75 }, 76 }, 77 "function_name": { 78 Type: schema.TypeString, 79 Required: true, 80 ForceNew: true, 81 }, 82 "handler": { 83 Type: schema.TypeString, 84 Required: true, 85 }, 86 "memory_size": { 87 Type: schema.TypeInt, 88 Optional: true, 89 Default: 128, 90 }, 91 "role": { 92 Type: schema.TypeString, 93 Required: true, 94 }, 95 "runtime": { 96 Type: schema.TypeString, 97 Required: true, 98 ValidateFunc: validateRuntime, 99 }, 100 "timeout": { 101 Type: schema.TypeInt, 102 Optional: true, 103 Default: 3, 104 }, 105 "publish": { 106 Type: schema.TypeBool, 107 Optional: true, 108 Default: false, 109 }, 110 "version": { 111 Type: schema.TypeString, 112 Computed: true, 113 }, 114 "vpc_config": { 115 Type: schema.TypeList, 116 Optional: true, 117 ForceNew: true, 118 Elem: &schema.Resource{ 119 Schema: map[string]*schema.Schema{ 120 "subnet_ids": { 121 Type: schema.TypeSet, 122 Required: true, 123 ForceNew: true, 124 Elem: &schema.Schema{Type: schema.TypeString}, 125 Set: schema.HashString, 126 }, 127 "security_group_ids": { 128 Type: schema.TypeSet, 129 Required: true, 130 ForceNew: true, 131 Elem: &schema.Schema{Type: schema.TypeString}, 132 Set: schema.HashString, 133 }, 134 "vpc_id": { 135 Type: schema.TypeString, 136 Computed: true, 137 }, 138 }, 139 }, 140 }, 141 "arn": { 142 Type: schema.TypeString, 143 Computed: true, 144 }, 145 "qualified_arn": { 146 Type: schema.TypeString, 147 Computed: true, 148 }, 149 "last_modified": { 150 Type: schema.TypeString, 151 Computed: true, 152 }, 153 "source_code_hash": { 154 Type: schema.TypeString, 155 Optional: true, 156 Computed: true, 157 }, 158 "environment": { 159 Type: schema.TypeList, 160 Optional: true, 161 MaxItems: 1, 162 Elem: &schema.Resource{ 163 Schema: map[string]*schema.Schema{ 164 "variables": { 165 Type: schema.TypeMap, 166 Optional: true, 167 Elem: schema.TypeString, 168 }, 169 }, 170 }, 171 }, 172 173 "kms_key_arn": { 174 Type: schema.TypeString, 175 Optional: true, 176 ValidateFunc: validateArn, 177 }, 178 }, 179 } 180 } 181 182 // resourceAwsLambdaFunction maps to: 183 // CreateFunction in the API / SDK 184 func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error { 185 conn := meta.(*AWSClient).lambdaconn 186 187 functionName := d.Get("function_name").(string) 188 iamRole := d.Get("role").(string) 189 190 log.Printf("[DEBUG] Creating Lambda Function %s with role %s", functionName, iamRole) 191 192 filename, hasFilename := d.GetOk("filename") 193 s3Bucket, bucketOk := d.GetOk("s3_bucket") 194 s3Key, keyOk := d.GetOk("s3_key") 195 s3ObjectVersion, versionOk := d.GetOk("s3_object_version") 196 197 if !hasFilename && !bucketOk && !keyOk && !versionOk { 198 return errors.New("filename or s3_* attributes must be set") 199 } 200 201 var functionCode *lambda.FunctionCode 202 if hasFilename { 203 // Grab an exclusive lock so that we're only reading one function into 204 // memory at a time. 205 // See https://github.com/hashicorp/terraform/issues/9364 206 awsMutexKV.Lock(awsMutexLambdaKey) 207 defer awsMutexKV.Unlock(awsMutexLambdaKey) 208 file, err := loadFileContent(filename.(string)) 209 if err != nil { 210 return fmt.Errorf("Unable to load %q: %s", filename.(string), err) 211 } 212 functionCode = &lambda.FunctionCode{ 213 ZipFile: file, 214 } 215 } else { 216 if !bucketOk || !keyOk { 217 return errors.New("s3_bucket and s3_key must all be set while using S3 code source") 218 } 219 functionCode = &lambda.FunctionCode{ 220 S3Bucket: aws.String(s3Bucket.(string)), 221 S3Key: aws.String(s3Key.(string)), 222 } 223 if versionOk { 224 functionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string)) 225 } 226 } 227 228 params := &lambda.CreateFunctionInput{ 229 Code: functionCode, 230 Description: aws.String(d.Get("description").(string)), 231 FunctionName: aws.String(functionName), 232 Handler: aws.String(d.Get("handler").(string)), 233 MemorySize: aws.Int64(int64(d.Get("memory_size").(int))), 234 Role: aws.String(iamRole), 235 Runtime: aws.String(d.Get("runtime").(string)), 236 Timeout: aws.Int64(int64(d.Get("timeout").(int))), 237 Publish: aws.Bool(d.Get("publish").(bool)), 238 } 239 240 if v, ok := d.GetOk("dead_letter_config"); ok { 241 dlcMaps := v.([]interface{}) 242 if len(dlcMaps) == 1 { // Schema guarantees either 0 or 1 243 dlcMap := dlcMaps[0].(map[string]interface{}) 244 params.DeadLetterConfig = &lambda.DeadLetterConfig{ 245 TargetArn: aws.String(dlcMap["target_arn"].(string)), 246 } 247 } 248 } 249 250 if v, ok := d.GetOk("vpc_config"); ok { 251 config, err := validateVPCConfig(v) 252 if err != nil { 253 return err 254 } 255 256 if config != nil { 257 var subnetIds []*string 258 for _, id := range config["subnet_ids"].(*schema.Set).List() { 259 subnetIds = append(subnetIds, aws.String(id.(string))) 260 } 261 262 var securityGroupIds []*string 263 for _, id := range config["security_group_ids"].(*schema.Set).List() { 264 securityGroupIds = append(securityGroupIds, aws.String(id.(string))) 265 } 266 267 params.VpcConfig = &lambda.VpcConfig{ 268 SubnetIds: subnetIds, 269 SecurityGroupIds: securityGroupIds, 270 } 271 } 272 } 273 274 if v, ok := d.GetOk("environment"); ok { 275 environments := v.([]interface{}) 276 environment, ok := environments[0].(map[string]interface{}) 277 if !ok { 278 return errors.New("At least one field is expected inside environment") 279 } 280 281 if environmentVariables, ok := environment["variables"]; ok { 282 variables := readEnvironmentVariables(environmentVariables.(map[string]interface{})) 283 284 params.Environment = &lambda.Environment{ 285 Variables: aws.StringMap(variables), 286 } 287 } 288 } 289 290 if v, ok := d.GetOk("kms_key_arn"); ok { 291 params.KMSKeyArn = aws.String(v.(string)) 292 } 293 294 // IAM profiles can take ~10 seconds to propagate in AWS: 295 // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console 296 // Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda. 297 err := resource.Retry(10*time.Minute, func() *resource.RetryError { 298 _, err := conn.CreateFunction(params) 299 if err != nil { 300 log.Printf("[ERROR] Received %q, retrying CreateFunction", err) 301 if awserr, ok := err.(awserr.Error); ok { 302 if awserr.Code() == "InvalidParameterValueException" { 303 log.Printf("[DEBUG] InvalidParameterValueException creating Lambda Function: %s", awserr) 304 return resource.RetryableError(awserr) 305 } 306 } 307 log.Printf("[DEBUG] Error creating Lambda Function: %s", err) 308 return resource.NonRetryableError(err) 309 } 310 return nil 311 }) 312 if err != nil { 313 return fmt.Errorf("Error creating Lambda function: %s", err) 314 } 315 316 d.SetId(d.Get("function_name").(string)) 317 318 return resourceAwsLambdaFunctionRead(d, meta) 319 } 320 321 // resourceAwsLambdaFunctionRead maps to: 322 // GetFunction in the API / SDK 323 func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) error { 324 conn := meta.(*AWSClient).lambdaconn 325 326 log.Printf("[DEBUG] Fetching Lambda Function: %s", d.Id()) 327 328 params := &lambda.GetFunctionInput{ 329 FunctionName: aws.String(d.Get("function_name").(string)), 330 } 331 332 getFunctionOutput, err := conn.GetFunction(params) 333 if err != nil { 334 if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ResourceNotFoundException" && !d.IsNewResource() { 335 d.SetId("") 336 return nil 337 } 338 return err 339 } 340 341 // getFunctionOutput.Code.Location is a pre-signed URL pointing at the zip 342 // file that we uploaded when we created the resource. You can use it to 343 // download the code from AWS. The other part is 344 // getFunctionOutput.Configuration which holds metadata. 345 346 function := getFunctionOutput.Configuration 347 // TODO error checking / handling on the Set() calls. 348 d.Set("arn", function.FunctionArn) 349 d.Set("description", function.Description) 350 d.Set("handler", function.Handler) 351 d.Set("memory_size", function.MemorySize) 352 d.Set("last_modified", function.LastModified) 353 d.Set("role", function.Role) 354 d.Set("runtime", function.Runtime) 355 d.Set("timeout", function.Timeout) 356 d.Set("kms_key_arn", function.KMSKeyArn) 357 358 config := flattenLambdaVpcConfigResponse(function.VpcConfig) 359 log.Printf("[INFO] Setting Lambda %s VPC config %#v from API", d.Id(), config) 360 vpcSetErr := d.Set("vpc_config", config) 361 if vpcSetErr != nil { 362 return fmt.Errorf("Failed setting vpc_config: %s", vpcSetErr) 363 } 364 365 d.Set("source_code_hash", function.CodeSha256) 366 367 if err := d.Set("environment", flattenLambdaEnvironment(function.Environment)); err != nil { 368 log.Printf("[ERR] Error setting environment for Lambda Function (%s): %s", d.Id(), err) 369 } 370 371 if function.DeadLetterConfig != nil && function.DeadLetterConfig.TargetArn != nil { 372 d.Set("dead_letter_config", []interface{}{ 373 map[string]interface{}{ 374 "target_arn": *function.DeadLetterConfig.TargetArn, 375 }, 376 }) 377 } else { 378 d.Set("dead_letter_config", []interface{}{}) 379 } 380 381 // List is sorted from oldest to latest 382 // so this may get costly over time :'( 383 var lastVersion, lastQualifiedArn string 384 err = listVersionsByFunctionPages(conn, &lambda.ListVersionsByFunctionInput{ 385 FunctionName: function.FunctionName, 386 MaxItems: aws.Int64(10000), 387 }, func(p *lambda.ListVersionsByFunctionOutput, lastPage bool) bool { 388 if lastPage { 389 last := p.Versions[len(p.Versions)-1] 390 lastVersion = *last.Version 391 lastQualifiedArn = *last.FunctionArn 392 return false 393 } 394 return true 395 }) 396 if err != nil { 397 return err 398 } 399 400 d.Set("version", lastVersion) 401 d.Set("qualified_arn", lastQualifiedArn) 402 403 return nil 404 } 405 406 func listVersionsByFunctionPages(c *lambda.Lambda, input *lambda.ListVersionsByFunctionInput, 407 fn func(p *lambda.ListVersionsByFunctionOutput, lastPage bool) bool) error { 408 for { 409 page, err := c.ListVersionsByFunction(input) 410 if err != nil { 411 return err 412 } 413 lastPage := page.NextMarker == nil 414 415 shouldContinue := fn(page, lastPage) 416 if !shouldContinue || lastPage { 417 break 418 } 419 input.Marker = page.NextMarker 420 } 421 return nil 422 } 423 424 // resourceAwsLambdaFunction maps to: 425 // DeleteFunction in the API / SDK 426 func resourceAwsLambdaFunctionDelete(d *schema.ResourceData, meta interface{}) error { 427 conn := meta.(*AWSClient).lambdaconn 428 429 log.Printf("[INFO] Deleting Lambda Function: %s", d.Id()) 430 431 params := &lambda.DeleteFunctionInput{ 432 FunctionName: aws.String(d.Get("function_name").(string)), 433 } 434 435 _, err := conn.DeleteFunction(params) 436 if err != nil { 437 return fmt.Errorf("Error deleting Lambda Function: %s", err) 438 } 439 440 d.SetId("") 441 442 return nil 443 } 444 445 // resourceAwsLambdaFunctionUpdate maps to: 446 // UpdateFunctionCode in the API / SDK 447 func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) error { 448 conn := meta.(*AWSClient).lambdaconn 449 450 d.Partial(true) 451 452 if d.HasChange("filename") || d.HasChange("source_code_hash") || d.HasChange("s3_bucket") || d.HasChange("s3_key") || d.HasChange("s3_object_version") { 453 codeReq := &lambda.UpdateFunctionCodeInput{ 454 FunctionName: aws.String(d.Id()), 455 Publish: aws.Bool(d.Get("publish").(bool)), 456 } 457 458 if v, ok := d.GetOk("filename"); ok { 459 // Grab an exclusive lock so that we're only reading one function into 460 // memory at a time. 461 // See https://github.com/hashicorp/terraform/issues/9364 462 awsMutexKV.Lock(awsMutexLambdaKey) 463 defer awsMutexKV.Unlock(awsMutexLambdaKey) 464 file, err := loadFileContent(v.(string)) 465 if err != nil { 466 return fmt.Errorf("Unable to load %q: %s", v.(string), err) 467 } 468 codeReq.ZipFile = file 469 } else { 470 s3Bucket, _ := d.GetOk("s3_bucket") 471 s3Key, _ := d.GetOk("s3_key") 472 s3ObjectVersion, versionOk := d.GetOk("s3_object_version") 473 474 codeReq.S3Bucket = aws.String(s3Bucket.(string)) 475 codeReq.S3Key = aws.String(s3Key.(string)) 476 if versionOk { 477 codeReq.S3ObjectVersion = aws.String(s3ObjectVersion.(string)) 478 } 479 } 480 481 log.Printf("[DEBUG] Send Update Lambda Function Code request: %#v", codeReq) 482 483 _, err := conn.UpdateFunctionCode(codeReq) 484 if err != nil { 485 return fmt.Errorf("Error modifying Lambda Function Code %s: %s", d.Id(), err) 486 } 487 488 d.SetPartial("filename") 489 d.SetPartial("source_code_hash") 490 d.SetPartial("s3_bucket") 491 d.SetPartial("s3_key") 492 d.SetPartial("s3_object_version") 493 } 494 495 configReq := &lambda.UpdateFunctionConfigurationInput{ 496 FunctionName: aws.String(d.Id()), 497 } 498 499 configUpdate := false 500 if d.HasChange("description") { 501 configReq.Description = aws.String(d.Get("description").(string)) 502 configUpdate = true 503 } 504 if d.HasChange("handler") { 505 configReq.Handler = aws.String(d.Get("handler").(string)) 506 configUpdate = true 507 } 508 if d.HasChange("memory_size") { 509 configReq.MemorySize = aws.Int64(int64(d.Get("memory_size").(int))) 510 configUpdate = true 511 } 512 if d.HasChange("role") { 513 configReq.Role = aws.String(d.Get("role").(string)) 514 configUpdate = true 515 } 516 if d.HasChange("timeout") { 517 configReq.Timeout = aws.Int64(int64(d.Get("timeout").(int))) 518 configUpdate = true 519 } 520 if d.HasChange("kms_key_arn") { 521 configReq.KMSKeyArn = aws.String(d.Get("kms_key_arn").(string)) 522 configUpdate = true 523 } 524 if d.HasChange("dead_letter_config") { 525 dlcMaps := d.Get("dead_letter_config").([]interface{}) 526 if len(dlcMaps) == 1 { // Schema guarantees either 0 or 1 527 dlcMap := dlcMaps[0].(map[string]interface{}) 528 configReq.DeadLetterConfig = &lambda.DeadLetterConfig{ 529 TargetArn: aws.String(dlcMap["target_arn"].(string)), 530 } 531 configUpdate = true 532 } 533 } 534 if d.HasChange("runtime") { 535 configReq.Runtime = aws.String(d.Get("runtime").(string)) 536 configUpdate = true 537 } 538 if d.HasChange("environment") { 539 if v, ok := d.GetOk("environment"); ok { 540 environments := v.([]interface{}) 541 environment, ok := environments[0].(map[string]interface{}) 542 if !ok { 543 return errors.New("At least one field is expected inside environment") 544 } 545 546 if environmentVariables, ok := environment["variables"]; ok { 547 variables := readEnvironmentVariables(environmentVariables.(map[string]interface{})) 548 549 configReq.Environment = &lambda.Environment{ 550 Variables: aws.StringMap(variables), 551 } 552 configUpdate = true 553 } 554 } else { 555 configReq.Environment = &lambda.Environment{ 556 Variables: aws.StringMap(map[string]string{}), 557 } 558 configUpdate = true 559 } 560 } 561 562 if configUpdate { 563 log.Printf("[DEBUG] Send Update Lambda Function Configuration request: %#v", configReq) 564 _, err := conn.UpdateFunctionConfiguration(configReq) 565 if err != nil { 566 return fmt.Errorf("Error modifying Lambda Function Configuration %s: %s", d.Id(), err) 567 } 568 d.SetPartial("description") 569 d.SetPartial("handler") 570 d.SetPartial("memory_size") 571 d.SetPartial("role") 572 d.SetPartial("timeout") 573 } 574 d.Partial(false) 575 576 return resourceAwsLambdaFunctionRead(d, meta) 577 } 578 579 // loadFileContent returns contents of a file in a given path 580 func loadFileContent(v string) ([]byte, error) { 581 filename, err := homedir.Expand(v) 582 if err != nil { 583 return nil, err 584 } 585 fileContent, err := ioutil.ReadFile(filename) 586 if err != nil { 587 return nil, err 588 } 589 return fileContent, nil 590 } 591 592 func readEnvironmentVariables(ev map[string]interface{}) map[string]string { 593 variables := make(map[string]string) 594 for k, v := range ev { 595 variables[k] = v.(string) 596 } 597 598 return variables 599 } 600 601 func validateVPCConfig(v interface{}) (map[string]interface{}, error) { 602 configs := v.([]interface{}) 603 if len(configs) > 1 { 604 return nil, errors.New("Only a single vpc_config block is expected") 605 } 606 607 config, ok := configs[0].(map[string]interface{}) 608 609 if !ok { 610 return nil, errors.New("vpc_config is <nil>") 611 } 612 613 // if subnet_ids and security_group_ids are both empty then the VPC is optional 614 if config["subnet_ids"].(*schema.Set).Len() == 0 && config["security_group_ids"].(*schema.Set).Len() == 0 { 615 return nil, nil 616 } 617 618 if config["subnet_ids"].(*schema.Set).Len() == 0 { 619 return nil, errors.New("vpc_config.subnet_ids cannot be empty") 620 } 621 622 if config["security_group_ids"].(*schema.Set).Len() == 0 { 623 return nil, errors.New("vpc_config.security_group_ids cannot be empty") 624 } 625 626 return config, nil 627 } 628 629 func validateRuntime(v interface{}, k string) (ws []string, errors []error) { 630 runtime := v.(string) 631 632 if runtime == lambda.RuntimeNodejs { 633 errors = append(errors, fmt.Errorf( 634 "%s has reached end of life since October 2016 and has been deprecated in favor of %s.", 635 runtime, lambda.RuntimeNodejs43)) 636 } 637 return 638 }