Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Data Source: aws_lambda_invocation #4222

Merged
merged 7 commits into from
May 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions aws/data_source_aws_lambda_invocation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package aws

import (
"crypto/md5"
"encoding/json"
"fmt"
"log"

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

func dataSourceAwsLambdaInvocation() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsLambdaInvocationRead,

Schema: map[string]*schema.Schema{
"function_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"qualifier": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "$LATEST",
},

"input": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateJsonString,
},

"result": {
Type: schema.TypeString,
Computed: true,
},

"result_map": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}

func dataSourceAwsLambdaInvocationRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).lambdaconn

functionName := d.Get("function_name").(string)
qualifier := d.Get("qualifier").(string)
input := []byte(d.Get("input").(string))

res, err := conn.Invoke(&lambda.InvokeInput{
FunctionName: aws.String(functionName),
InvocationType: aws.String(lambda.InvocationTypeRequestResponse),
Payload: input,
Qualifier: aws.String(qualifier),
})

if err != nil {
return err
}

if res.FunctionError != nil {
return fmt.Errorf("Lambda function (%s) returned error: (%s)", functionName, string(res.Payload))
}

if err = d.Set("result", string(res.Payload)); err != nil {
return err
}

var result map[string]interface{}

if err = json.Unmarshal(res.Payload, &result); err != nil {
return err
}

if err = d.Set("result_map", result); err != nil {
log.Printf("[WARN] Cannot use the result invocation as a string map: %s", err)
}

d.SetId(fmt.Sprintf("%s_%s_%x", functionName, qualifier, md5.Sum(input)))

return nil
}
215 changes: 215 additions & 0 deletions aws/data_source_aws_lambda_invocation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
package aws

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func testAccCheckLambdaInvocationResult(name, expectedResult string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}

if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}

result, ok := rs.Primary.Attributes["result"]

if !ok {
return fmt.Errorf("No result is set")
}

if !suppressEquivalentJsonDiffs("", result, expectedResult, nil) {
return fmt.Errorf("%s: Attribute 'result' expected %s, got %s", name, expectedResult, result)
}

return nil
}
}

func TestAccDataSourceAwsLambdaInvocation_basic(t *testing.T) {
testData := "value3"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsLambdaInvocation_basic_config("tf-test-lambda-role", "tf-test-lambda-invocation", testData),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.%", "3"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key1", "value1"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key2", "value2"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key3", testData),
testAccCheckLambdaInvocationResult("data.aws_lambda_invocation.invocation_test", `{"key1":"value1","key2":"value2","key3":"`+testData+`"}`),
),
},
},
})
}

func TestAccDataSourceAwsLambdaInvocation_qualifier(t *testing.T) {
testData := "value3"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsLambdaInvocation_qualifier_config("tf-test-lambda-role-qualifier", "tf-test-lambda-invocation-qualifier", testData),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.%", "3"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key1", "value1"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key2", "value2"),
resource.TestCheckResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map.key3", testData),
),
},
},
})
}

func TestAccDataSourceAwsLambdaInvocation_complex(t *testing.T) {
testData := "value3"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsLambdaInvocation_complex_config("tf-test-lambda-role-complex", "tf-test-lambda-invocation-complex", testData),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckNoResourceAttr("data.aws_lambda_invocation.invocation_test", "result_map"),
testAccCheckLambdaInvocationResult("data.aws_lambda_invocation.invocation_test", `{"key1":{"subkey1":"subvalue1"},"key2":{"subkey2":"subvalue2","subkey3":{"a": "b"}},"key3":"`+testData+`"}`),
),
},
},
})
}

func testAccDataSourceAwsLambdaInvocation_base_config(roleName string) string {
return fmt.Sprintf(`
data "aws_iam_policy_document" "lambda_assume_role_policy" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]

principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}

resource "aws_iam_role" "lambda_role" {
name = "%s"
assume_role_policy = "${data.aws_iam_policy_document.lambda_assume_role_policy.json}"
}

resource "aws_iam_role_policy_attachment" "lambda_role_policy" {
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
role = "${aws_iam_role.lambda_role.name}"
}
`, roleName)
}

func testAccDataSourceAwsLambdaInvocation_basic_config(roleName, lambdaName, testData string) string {
return fmt.Sprintf(testAccDataSourceAwsLambdaInvocation_base_config(roleName)+`
resource "aws_lambda_function" "lambda" {
depends_on = ["aws_iam_role_policy_attachment.lambda_role_policy"]

filename = "test-fixtures/lambda_invocation.zip"
function_name = "%s"
role = "${aws_iam_role.lambda_role.arn}"
handler = "lambda_invocation.handler"
runtime = "nodejs8.10"

environment {
variables = {
TEST_DATA = "%s"
}
}
}

data "aws_lambda_invocation" "invocation_test" {
function_name = "${aws_lambda_function.lambda.function_name}"

input = <<JSON
{
"key1": "value1",
"key2": "value2"
}
JSON
}
`, lambdaName, testData)
}

func testAccDataSourceAwsLambdaInvocation_qualifier_config(roleName, lambdaName, testData string) string {
return fmt.Sprintf(testAccDataSourceAwsLambdaInvocation_base_config(roleName)+`
resource "aws_lambda_function" "lambda" {
depends_on = ["aws_iam_role_policy_attachment.lambda_role_policy"]

filename = "test-fixtures/lambda_invocation.zip"
function_name = "%s"
role = "${aws_iam_role.lambda_role.arn}"
handler = "lambda_invocation.handler"
runtime = "nodejs8.10"
publish = true

environment {
variables = {
TEST_DATA = "%s"
}
}
}

data "aws_lambda_invocation" "invocation_test" {
function_name = "${aws_lambda_function.lambda.function_name}"
qualifier = "${aws_lambda_function.lambda.version}"

input = <<JSON
{
"key1": "value1",
"key2": "value2"
}
JSON
}
`, lambdaName, testData)
}

func testAccDataSourceAwsLambdaInvocation_complex_config(roleName, lambdaName, testData string) string {
return fmt.Sprintf(testAccDataSourceAwsLambdaInvocation_base_config(roleName)+`
resource "aws_lambda_function" "lambda" {
depends_on = ["aws_iam_role_policy_attachment.lambda_role_policy"]

filename = "test-fixtures/lambda_invocation.zip"
function_name = "%s"
role = "${aws_iam_role.lambda_role.arn}"
handler = "lambda_invocation.handler"
runtime = "nodejs8.10"
publish = true

environment {
variables = {
TEST_DATA = "%s"
}
}
}

data "aws_lambda_invocation" "invocation_test" {
function_name = "${aws_lambda_function.lambda.function_name}"

input = <<JSON
{
"key1": {"subkey1": "subvalue1"},
"key2": {"subkey2": "subvalue2", "subkey3": {"a": "b"}}
}
JSON
}
`, lambdaName, testData)
}
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ func Provider() terraform.ResourceProvider {
"aws_kms_key": dataSourceAwsKmsKey(),
"aws_kms_secret": dataSourceAwsKmsSecret(),
"aws_lambda_function": dataSourceAwsLambdaFunction(),
"aws_lambda_invocation": dataSourceAwsLambdaInvocation(),
"aws_mq_broker": dataSourceAwsMqBroker(),
"aws_nat_gateway": dataSourceAwsNatGateway(),
"aws_network_interface": dataSourceAwsNetworkInterface(),
Expand Down
6 changes: 6 additions & 0 deletions aws/test-fixtures/lambda_invocation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
exports.handler = async (event) => {
if (process.env.TEST_DATA) {
event.key3 = process.env.TEST_DATA;
}
return event;
}
Binary file added aws/test-fixtures/lambda_invocation.zip
Binary file not shown.
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@
<li<%= sidebar_current("docs-aws-datasource-kms-secret") %>>
<a href="/docs/providers/aws/d/kms_secret.html">aws_kms_secret</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-lambda-invocation") %>>
<a href="/docs/providers/aws/d/lambda_invocation.html">aws_lambda_invocation</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-nat-gateway") %>>
<a href="/docs/providers/aws/d/nat_gateway.html">aws_nat_gateway</a>
</li>
Expand Down
49 changes: 49 additions & 0 deletions website/docs/d/lambda_invocation.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
layout: "aws"
page_title: "AWS: aws_lambda_invocation"
sidebar_current: "docs-aws-datasource-lambda-invocation"
description: |-
Invoke AWS Lambda Function as data source
---

# Data Source: aws_lambda_invocation

Use this data source to invoke custom lambda functions as data source.
The lambda function is invoked with [RequestResponse](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax)
invocation type.

## Example Usage

```hcl
data "aws_lambda_invocation" "example" {
function_name = "${aws_lambda_function.lambda_function_test.function_name}"

input = <<JSON
{
"key1": "value1",
"key2": "value2"
}
JSON

}

output "result_entry" {
value = "${data.aws_lambda_invocation.result_map["key1"]}"
}

output "result" {
value = "${data.aws_lambda_invocation.result}"
}
```

## Argument Reference

* `function_name` - (Required) The name of the lambda function.
* `input` - (Required) A string in JSON format that is passed as payload to the lambda function.
* `qualifier` - (Optional) The qualifier (a.k.a version) of the lambda function. Defaults
to `$LATEST`.

## Attributes Reference

* `result` - A result of the lambda function invocation.
* `result_map` - This field is set only if result is a map of primitive types.