New resource (AWS provider) - aws_lambda_event_source_mapping

This commit is contained in:
Chris Marchesi 2015-11-27 15:23:45 -08:00
parent 9e1fca790a
commit 85627630bd
4 changed files with 498 additions and 0 deletions

View File

@ -223,6 +223,7 @@ func Provider() terraform.ResourceProvider {
"aws_kinesis_firehose_delivery_stream": resourceAwsKinesisFirehoseDeliveryStream(), "aws_kinesis_firehose_delivery_stream": resourceAwsKinesisFirehoseDeliveryStream(),
"aws_kinesis_stream": resourceAwsKinesisStream(), "aws_kinesis_stream": resourceAwsKinesisStream(),
"aws_lambda_function": resourceAwsLambdaFunction(), "aws_lambda_function": resourceAwsLambdaFunction(),
"aws_lambda_event_source_mapping": resourceAwsLambdaEventSourceMapping(),
"aws_launch_configuration": resourceAwsLaunchConfiguration(), "aws_launch_configuration": resourceAwsLaunchConfiguration(),
"aws_lb_cookie_stickiness_policy": resourceAwsLBCookieStickinessPolicy(), "aws_lb_cookie_stickiness_policy": resourceAwsLBCookieStickinessPolicy(),
"aws_main_route_table_association": resourceAwsMainRouteTableAssociation(), "aws_main_route_table_association": resourceAwsMainRouteTableAssociation(),

View File

@ -0,0 +1,171 @@
package aws
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsLambdaEventSourceMapping() *schema.Resource {
return &schema.Resource{
Create: resourceAwsLambdaEventSourceMappingCreate,
Read: resourceAwsLambdaEventSourceMappingRead,
Update: resourceAwsLambdaEventSourceMappingUpdate,
Delete: resourceAwsLambdaEventSourceMappingDelete,
Schema: map[string]*schema.Schema{
"event_source_arn": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"function_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"starting_position": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"batch_size": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 100,
},
"enabled": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"function_arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"last_modified": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"last_processing_result": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"state_transition_reason": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"uuid": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
// resourceAwsLambdaEventSourceMappingCreate maps to:
// CreateEventSourceMapping in the API / SDK
func resourceAwsLambdaEventSourceMappingCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).lambdaconn
functionName := d.Get("function_name").(string)
eventSourceArn := d.Get("event_source_arn").(string)
log.Printf("[DEBUG] Creating Lambda event source mapping: source %s to function %s", eventSourceArn, functionName)
params := &lambda.CreateEventSourceMappingInput{
EventSourceArn: aws.String(eventSourceArn),
FunctionName: aws.String(functionName),
StartingPosition: aws.String(d.Get("starting_position").(string)),
BatchSize: aws.Int64(int64(d.Get("batch_size").(int))),
Enabled: aws.Bool(d.Get("enabled").(bool)),
}
eventSourceMappingConfiguration, err := conn.CreateEventSourceMapping(params)
if err != nil {
return fmt.Errorf("Error creating Lambda event source mapping: %s", err)
}
d.Set("uuid", eventSourceMappingConfiguration.UUID)
d.SetId(*eventSourceMappingConfiguration.UUID)
return resourceAwsLambdaEventSourceMappingRead(d, meta)
}
// resourceAwsLambdaEventSourceMappingRead maps to:
// GetEventSourceMapping in the API / SDK
func resourceAwsLambdaEventSourceMappingRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).lambdaconn
log.Printf("[DEBUG] Fetching Lambda event source mapping: %s", d.Id())
params := &lambda.GetEventSourceMappingInput{
UUID: aws.String(d.Id()),
}
eventSourceMappingConfiguration, err := conn.GetEventSourceMapping(params)
if err != nil {
return err
}
d.Set("batch_size", eventSourceMappingConfiguration.BatchSize)
d.Set("event_source_arn", eventSourceMappingConfiguration.EventSourceArn)
d.Set("function_arn", eventSourceMappingConfiguration.FunctionArn)
d.Set("last_modified", eventSourceMappingConfiguration.LastModified)
d.Set("last_processing_result", eventSourceMappingConfiguration.LastProcessingResult)
d.Set("state", eventSourceMappingConfiguration.State)
d.Set("state_transition_reason", eventSourceMappingConfiguration.StateTransitionReason)
d.Set("uuid", eventSourceMappingConfiguration.UUID)
return nil
}
// resourceAwsLambdaEventSourceMappingDelete maps to:
// DeleteEventSourceMapping in the API / SDK
func resourceAwsLambdaEventSourceMappingDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).lambdaconn
log.Printf("[INFO] Deleting Lambda event source mapping: %s", d.Id())
params := &lambda.DeleteEventSourceMappingInput{
UUID: aws.String(d.Id()),
}
_, err := conn.DeleteEventSourceMapping(params)
if err != nil {
return fmt.Errorf("Error deleting Lambda event source mapping: %s", err)
}
d.SetId("")
return nil
}
// resourceAwsLambdaEventSourceMappingUpdate maps to:
// UpdateEventSourceMapping in the API / SDK
func resourceAwsLambdaEventSourceMappingUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).lambdaconn
log.Printf("[DEBUG] Updating Lambda event source mapping: %s", d.Id())
params := &lambda.UpdateEventSourceMappingInput{
UUID: aws.String(d.Id()),
BatchSize: aws.Int64(int64(d.Get("batch_size").(int))),
FunctionName: aws.String(d.Get("function_name").(string)),
Enabled: aws.Bool(d.Get("enabled").(bool)),
}
_, err := conn.UpdateEventSourceMapping(params)
if err != nil {
return fmt.Errorf("Error updating Lambda event source mapping: %s", err)
}
return resourceAwsLambdaEventSourceMappingRead(d, meta)
}

View File

@ -0,0 +1,279 @@
package aws
import (
"fmt"
"regexp"
"strconv"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSLambdaEventSourceMapping_basic(t *testing.T) {
var conf lambda.EventSourceMappingConfiguration
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLambdaEventSourceMappingDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSLambdaEventSourceMappingConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaEventSourceMappingExists("aws_lambda_event_source_mapping.lambda_event_source_mapping_test", &conf),
testAccCheckAWSLambdaEventSourceMappingAttributes(&conf),
),
},
resource.TestStep{
Config: testAccAWSLambdaEventSourceMappingConfigUpdate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsLambdaEventSourceMappingExists("aws_lambda_event_source_mapping.lambda_event_source_mapping_test", &conf),
resource.TestCheckResourceAttr("aws_lambda_event_source_mapping.lambda_event_source_mapping_test",
"batch_size",
strconv.Itoa(200)),
resource.TestCheckResourceAttr("aws_lambda_event_source_mapping.lambda_event_source_mapping_test",
"enabled",
strconv.FormatBool(false)),
resource.TestMatchResourceAttr(
"aws_lambda_event_source_mapping.lambda_event_source_mapping_test",
"function_arn",
regexp.MustCompile("example_lambda_name_update$"),
),
),
},
},
})
}
func testAccCheckLambdaEventSourceMappingDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).lambdaconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_lambda_event_source_mapping" {
continue
}
_, err := conn.GetEventSourceMapping(&lambda.GetEventSourceMappingInput{
UUID: aws.String(rs.Primary.ID),
})
if err == nil {
return fmt.Errorf("Lambda event source mapping was not deleted")
}
}
return nil
}
func testAccCheckAwsLambdaEventSourceMappingExists(n string, mapping *lambda.EventSourceMappingConfiguration) resource.TestCheckFunc {
// Wait for IAM role
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Lambda event source mapping not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("Lambda event source mapping ID not set")
}
conn := testAccProvider.Meta().(*AWSClient).lambdaconn
params := &lambda.GetEventSourceMappingInput{
UUID: aws.String(rs.Primary.ID),
}
getSourceMappingConfiguration, err := conn.GetEventSourceMapping(params)
if err != nil {
return err
}
*mapping = *getSourceMappingConfiguration
return nil
}
}
func testAccCheckAWSLambdaEventSourceMappingAttributes(mapping *lambda.EventSourceMappingConfiguration) resource.TestCheckFunc {
return func(s *terraform.State) error {
uuid := *mapping.UUID
if uuid == "" {
return fmt.Errorf("Could not read Lambda event source mapping's UUID")
}
return nil
}
}
const testAccAWSLambdaEventSourceMappingConfig = `
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_policy" "policy_for_role" {
name = "policy_for_role"
path = "/"
description = "IAM policy for for Lamda event mapping testing"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:GetRecords",
"kinesis:GetShardIterator",
"kinesis:DescribeStream"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"kinesis:ListStreams"
],
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
name = "policy_attachment_for_role"
roles = ["${aws_iam_role.iam_for_lambda.name}"]
policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}
resource "aws_kinesis_stream" "kinesis_stream_test" {
name = "kinesis_stream_test"
shard_count = 1
}
resource "aws_lambda_function" "lambda_function_test_create" {
filename = "test-fixtures/lambdatest.zip"
function_name = "example_lambda_name_create"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
}
resource "aws_lambda_function" "lambda_function_test_update" {
filename = "test-fixtures/lambdatest.zip"
function_name = "example_lambda_name_update"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
}
resource "aws_lambda_event_source_mapping" "lambda_event_source_mapping_test" {
batch_size = 100
event_source_arn = "${aws_kinesis_stream.kinesis_stream_test.arn}"
enabled = true
depends_on = ["aws_iam_policy_attachment.policy_attachment_for_role"]
function_name = "${aws_lambda_function.lambda_function_test_create.arn}"
starting_position = "TRIM_HORIZON"
}
`
const testAccAWSLambdaEventSourceMappingConfigUpdate = `
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_policy" "policy_for_role" {
name = "policy_for_role"
path = "/"
description = "IAM policy for for Lamda event mapping testing"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:GetRecords",
"kinesis:GetShardIterator",
"kinesis:DescribeStream"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"kinesis:ListStreams"
],
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
name = "policy_attachment_for_role"
roles = ["${aws_iam_role.iam_for_lambda.name}"]
policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}
resource "aws_kinesis_stream" "kinesis_stream_test" {
name = "kinesis_stream_test"
shard_count = 1
}
resource "aws_lambda_function" "lambda_function_test_create" {
filename = "test-fixtures/lambdatest.zip"
function_name = "example_lambda_name_create"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
}
resource "aws_lambda_function" "lambda_function_test_update" {
filename = "test-fixtures/lambdatest.zip"
function_name = "example_lambda_name_update"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
}
resource "aws_lambda_event_source_mapping" "lambda_event_source_mapping_test" {
batch_size = 200
event_source_arn = "${aws_kinesis_stream.kinesis_stream_test.arn}"
enabled = false
depends_on = ["aws_iam_policy_attachment.policy_attachment_for_role"]
function_name = "${aws_lambda_function.lambda_function_test_update.arn}"
starting_position = "TRIM_HORIZON"
}
`

View File

@ -0,0 +1,47 @@
---
layout: "aws"
page_title: "AWS: aws_lambda_event_source_mapping"
sidebar_current: "docs-aws-resource-aws-lambda-event-source-mapping"
description: |-
Provides a Lambda event source mapping. This allows Lambda functions to get events from Kinesis and DynamoDB.
---
# aws\_lambda\_event\_source\_mapping
Provides a Lambda event source mapping. This allows Lambda functions to get events from Kinesis and DynamoDB.
For information about Lambda and how to use it, see [What is AWS Lambda?][1]
For information about event source mappings, see [CreateEventSourceMapping][2] in the API docs.
## Example Usage
```
resource "aws_lambda_event_source_mapping" "event_source_mapping" {
batch_size = 100
event_source_arn = "arn:aws:kinesis:REGION:123456789012:stream/stream_name"
enabled = true
function_name = "arn:aws:lambda:REGION:123456789012:function:function_name"
starting_position = "TRIM_HORIZON|LATEST"
}
```
## Argument Reference
* `batch_size` - (Optional) The largest number of records that Lambda will retrieve from your event source at the time of invocation. Defaults to `100`.
* `event_source_arn` - (Required) The event source ARN - can either be a Kinesis or DynamoDB stream.
* `enabled` - (Optional) Determines if the mapping will be enabled on creation. Defaults to `true`.
* `function_name` - (Required) The name or the ARN of the Lambda function that will be subscribing to events.
* `starting_position` - (Required) The position in the stream where AWS Lambda should start reading. Can be one of either `TRIM_HORIZON` or `LATEST`.
## Attributes Reference
* `function_arn` - The the ARN of the Lambda function the event source mapping is sending events to. (Note: this is a computed value that differs from `function_name` above.)
* `last_modified` - The date this resource was last modified.
* `last_processing_result` - The result of the last AWS Lambda invocation of your Lambda function.
* `state` - The state of the event source mapping.
* `state_transition_reason` - The reason the event source mapping is in its current state.
* `uuid` - The UUID of the created event source mapping.
[1]: http://docs.aws.amazon.com/lambda/latest/dg/welcome.html
[2]: http://docs.aws.amazon.com/lambda/latest/dg/API_CreateEventSourceMapping.html