Skip to content

Commit

Permalink
Add tagging support to the 'aws_lambda_function' resource. (#13873)
Browse files Browse the repository at this point in the history
  • Loading branch information
ewbankkit authored and stack72 committed Apr 23, 2017
1 parent 9aaf220 commit ff9af4c
Show file tree
Hide file tree
Showing 6 changed files with 319 additions and 0 deletions.
13 changes: 13 additions & 0 deletions builtin/providers/aws/resource_aws_lambda_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ func resourceAwsLambdaFunction() *schema.Resource {
Optional: true,
ValidateFunc: validateArn,
},

"tags": tagsSchema(),
},
}
}
Expand Down Expand Up @@ -291,6 +293,10 @@ func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) e
params.KMSKeyArn = aws.String(v.(string))
}

if v, exists := d.GetOk("tags"); exists {
params.Tags = tagsFromMapGeneric(v.(map[string]interface{}))
}

// IAM profiles can take ~10 seconds to propagate in AWS:
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.
Expand Down Expand Up @@ -353,6 +359,7 @@ func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) err
d.Set("runtime", function.Runtime)
d.Set("timeout", function.Timeout)
d.Set("kms_key_arn", function.KMSKeyArn)
d.Set("tags", tagsToMapGeneric(getFunctionOutput.Tags))

config := flattenLambdaVpcConfigResponse(function.VpcConfig)
log.Printf("[INFO] Setting Lambda %s VPC config %#v from API", d.Id(), config)
Expand Down Expand Up @@ -448,6 +455,12 @@ func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) e

d.Partial(true)

arn := d.Get("arn").(string)
if tagErr := setTagsLambda(conn, d, arn); tagErr != nil {
return tagErr
}
d.SetPartial("tags")

if d.HasChange("filename") || d.HasChange("source_code_hash") || d.HasChange("s3_bucket") || d.HasChange("s3_key") || d.HasChange("s3_object_version") {
codeReq := &lambda.UpdateFunctionCodeInput{
FunctionName: aws.String(d.Id()),
Expand Down
113 changes: 113 additions & 0 deletions builtin/providers/aws/resource_aws_lambda_function_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,74 @@ func TestAccAWSLambdaFunction_runtimeValidation_java8(t *testing.T) {
})
}

func TestAccAWSLambdaFunction_tags(t *testing.T) {
var conf lambda.GetFunctionOutput

rSt := acctest.RandString(5)
rName := fmt.Sprintf("tf_test_%s", rSt)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLambdaFunctionDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSLambdaConfigBasic(rName, rSt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaFunctionExists("aws_lambda_function.lambda_function_test", rName, &conf),
testAccCheckAwsLambdaFunctionName(&conf, rName),
testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+rName),
resource.TestCheckNoResourceAttr("aws_lambda_function.lambda_function_test", "tags"),
),
},
{
Config: testAccAWSLambdaConfigTags(rName, rSt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaFunctionExists("aws_lambda_function.lambda_function_test", rName, &conf),
testAccCheckAwsLambdaFunctionName(&conf, rName),
testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+rName),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.%", "2"),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.Key1", "Value One"),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.Description", "Very interesting"),
),
},
{
Config: testAccAWSLambdaConfigTagsModified(rName, rSt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaFunctionExists("aws_lambda_function.lambda_function_test", rName, &conf),
testAccCheckAwsLambdaFunctionName(&conf, rName),
testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+rName),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.%", "3"),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.Key1", "Value One Changed"),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.Key2", "Value Two"),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "tags.Key3", "Value Three"),
),
},
},
})
}

func TestAccAWSLambdaFunction_runtimeValidation_python36(t *testing.T) {
var conf lambda.GetFunctionOutput
rSt := acctest.RandString(5)
rName := fmt.Sprintf("tf_test_%s", rSt)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLambdaFunctionDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSLambdaConfigPython36Runtime(rName, rSt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaFunctionExists("aws_lambda_function.lambda_function_test", rName, &conf),
resource.TestCheckResourceAttr("aws_lambda_function.lambda_function_test", "runtime", lambda.RuntimePython36),
),
},
},
})
}

func testAccCheckLambdaFunctionDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).lambdaconn

Expand Down Expand Up @@ -1106,6 +1174,51 @@ resource "aws_lambda_function" "lambda_function_test" {
`, rName)
}

func testAccAWSLambdaConfigTags(rName, rSt string) string {
return fmt.Sprintf(baseAccAWSLambdaConfig(rSt)+`
resource "aws_lambda_function" "lambda_function_test" {
filename = "test-fixtures/lambdatest.zip"
function_name = "%s"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
runtime = "nodejs4.3"
tags {
Key1 = "Value One"
Description = "Very interesting"
}
}
`, rName)
}

func testAccAWSLambdaConfigTagsModified(rName, rSt string) string {
return fmt.Sprintf(baseAccAWSLambdaConfig(rSt)+`
resource "aws_lambda_function" "lambda_function_test" {
filename = "test-fixtures/lambdatest.zip"
function_name = "%s"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
runtime = "nodejs4.3"
tags {
Key1 = "Value One Changed"
Key2 = "Value Two"
Key3 = "Value Three"
}
}
`, rName)
}

func testAccAWSLambdaConfigPython36Runtime(rName, rSt string) string {
return fmt.Sprintf(baseAccAWSLambdaConfig(rSt)+`
resource "aws_lambda_function" "lambda_function_test" {
filename = "test-fixtures/lambdatest.zip"
function_name = "%s"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
runtime = "python3.6"
}
`, rName)
}

const testAccAWSLambdaFunctionConfig_local_tpl = `
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda_%d"
Expand Down
69 changes: 69 additions & 0 deletions builtin/providers/aws/tagsGeneric.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package aws

import (
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
)

// diffTags takes our tags locally and the ones remotely and returns
// the set of tags that must be created, and the set of tags that must
// be destroyed.
func diffTagsGeneric(oldTags, newTags map[string]interface{}) (map[string]*string, map[string]*string) {
// First, we're creating everything we have
create := make(map[string]*string)
for k, v := range newTags {
create[k] = aws.String(v.(string))
}

// Build the map of what to remove
remove := make(map[string]*string)
for k, v := range oldTags {
old, ok := create[k]
if !ok || old != aws.String(v.(string)) {
// Delete it!
remove[k] = aws.String(v.(string))
}
}

return create, remove
}

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapGeneric(m map[string]interface{}) map[string]*string {
result := make(map[string]*string)
for k, v := range m {
if !tagIgnoredGeneric(k) {
result[k] = aws.String(v.(string))
}
}

return result
}

// tagsToMap turns the tags into a map.
func tagsToMapGeneric(ts map[string]*string) map[string]string {
result := make(map[string]string)
for k, v := range ts {
if !tagIgnoredGeneric(k) {
result[k] = aws.StringValue(v)
}
}

return result
}

// compare a tag against a list of strings and checks if it should
// be ignored or not
func tagIgnoredGeneric(k string) bool {
filter := []string{"^aws:*"}
for _, v := range filter {
log.Printf("[DEBUG] Matching %v with %v\n", v, k)
if r, _ := regexp.MatchString(v, k); r == true {
log.Printf("[DEBUG] Found AWS specific tag %s, ignoring.\n", k)
return true
}
}
return false
}
73 changes: 73 additions & 0 deletions builtin/providers/aws/tagsGeneric_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package aws

import (
"reflect"
"testing"

"github.com/aws/aws-sdk-go/aws"
)

// go test -v -run="TestDiffGenericTags"
func TestDiffGenericTags(t *testing.T) {
cases := []struct {
Old, New map[string]interface{}
Create, Remove map[string]string
}{
// Basic add/remove
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"bar": "baz",
},
Create: map[string]string{
"bar": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},

// Modify
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"foo": "baz",
},
Create: map[string]string{
"foo": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},
}

for i, tc := range cases {
c, r := diffTagsGeneric(tc.Old, tc.New)
cm := tagsToMapGeneric(c)
rm := tagsToMapGeneric(r)
if !reflect.DeepEqual(cm, tc.Create) {
t.Fatalf("%d: bad create: %#v", i, cm)
}
if !reflect.DeepEqual(rm, tc.Remove) {
t.Fatalf("%d: bad remove: %#v", i, rm)
}
}
}

// go test -v -run="TestIgnoringTagsGeneric"
func TestIgnoringTagsGeneric(t *testing.T) {
ignoredTags := map[string]*string{
"aws:cloudformation:logical-id": aws.String("foo"),
"aws:foo:bar": aws.String("baz"),
}
for k, v := range ignoredTags {
if !tagIgnoredGeneric(k) {
t.Fatalf("Tag %v with value %v not ignored, but should be!", k, *v)
}
}
}
50 changes: 50 additions & 0 deletions builtin/providers/aws/tagsLambda.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package aws

import (
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/hashicorp/terraform/helper/schema"
)

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTagsLambda(conn *lambda.Lambda, d *schema.ResourceData, arn string) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTagsGeneric(o, n)

// Set tags
if len(remove) > 0 {
log.Printf("[DEBUG] Removing tags: %#v", remove)
keys := make([]*string, 0, len(remove))
for k := range remove {
keys = append(keys, aws.String(k))
}

_, err := conn.UntagResource(&lambda.UntagResourceInput{
Resource: aws.String(arn),
TagKeys: keys,
})
if err != nil {
return err
}
}
if len(create) > 0 {
log.Printf("[DEBUG] Creating tags: %#v", create)

_, err := conn.TagResource(&lambda.TagResourceInput{
Resource: aws.String(arn),
Tags: create,
})
if err != nil {
return err
}
}
}

return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ large files efficiently.
* `environment` - (Optional) The Lambda environment's configuration settings. Fields documented below.
* `kms_key_arn` - (Optional) The ARN for the KMS encryption key.
* `source_code_hash` - (Optional) Used to trigger updates. Must be set to a base64-encoded SHA256 hash of the package file specified with either `filename` or `s3_key`. The usual way to set this is `${base64sha256(file("file.zip"))}`, where "file.zip" is the local filename of the lambda function source archive.
* `tags` - (Optional) A mapping of tags to assign to the object.

**dead\_letter\_config** is a child block with a single argument:

Expand Down

0 comments on commit ff9af4c

Please sign in to comment.