Home > Blockchain >  Create trigger using Cloudformation to launch a lambda function and verify in what region is availab
Create trigger using Cloudformation to launch a lambda function and verify in what region is availab

Time:02-16

I have the following structure:

  • A S3 bucket where I upload files
  • A Cloud formation template where I'm creating a lambda function to process the files those are uploaded in the s3 bucket.

Now I want to create a trigger(it's my first time) using Cloudformation to launch automatically the lambda function when a file is uploaded in the S3 bucket. The problem here is I have the lambda function in two different regions(us-east-1 and us-west-2) and only one S3 bucket shared. I want to select by default the us-west-2 to trigger the lambda function and in the case that us-west-2 is not available change the region and launch the lambda function using us-east-1.

CodePudding user response:

What you want is not possible to achieve in plain CloudFormatin. You need to develop custom resource for such a logic.

CodePudding user response:

You want something like this:

Your function will need to accept a CustomResource Request and respond appropriately.

You will need to process on either the Create request, the Update request, or both. You need to respond to the request with Success (or Fail).

Be aware you might-can't remember not get an update request unless the AWS::CloudFormation::CustomResource has some values updated. In that case, a sentinel property on the custom resource filled with a date or UUID will force it to recreate.

The Condition on the AWS::CloudFormation::CustomResource will conditionally create it (thus calling your function conditionally) only if the stack is in us-west-1. You could also attach this condition to the function if you desire.

You could remove the condition altogether and check the region the lambda function is located in during execution, this is probably cleaner anyway.

{
  "Resources": {
    "MyLambdaFunction": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "Role": {
          "Ref": "MyLambdaFunctionRole"
        }
      }
    },
    "CustomResource": {
      "Condition": "IsUsWest",
      "Type": "AWS::CloudFormation::CustomResource",
      "Properties": {
        "ServiceToken": {
          "Fn::GetAtt": [
            "MyLambdaFunction",
            "Arn"
          ]
        }
      }
    }
  },
  "Parameters": {
    "MyLambdaFunctionRole": {
      "Type": "String"
    }
  },
  "Conditions": {
    "IsUsWest": {
      "Fn::Equals": [
        {
          "Ref": "AWS::Region"
        },
        "us-west-1"
      ]
    }
  }
}
  • Related