slipperypete
slipperypete

Reputation: 6284

How to make aws_cloudwatch_event_rule with terraform and localstack?

I am using terraform(terraform) and localstack(localstack) and trying to create a aws_cloudwatch_event_rule. I get an error:

Error: Updating CloudWatch Event Rule failed: UnrecognizedClientException: The security token included in the request is invalid. status code: 400, request id: 2d0671b9-cb55-4872-8e8c-82e26f4336cb

Im not sure why im getting this error because this works to create the resource in AWS but not on localstack 🤷‍♂️. Does anybody have any suggestions as to how to fix this? Thanks.

Its a large terraform project so I cant share all the code. This is the relevant section.

resource "aws_cloudwatch_event_rule" "trigger" {
  name        = "trigger-event"
  description = "STUFF"
  schedule_expression = "cron(0 */1 * * ? *)"
}

resource "aws_cloudwatch_event_target" "trigger_target" {
  rule      = "${aws_cloudwatch_event_rule.trigger.name}"
  arn       = "${trigger.arn}"
}

Upvotes: 1

Views: 3841

Answers (1)

verespej
verespej

Reputation: 830

I realize this is an old question, but I just ran into this problem. I wanted to share what resolved it for me, in case it helps others who end up here. This works for me with terraform 0.12 (should work for 0.13 as well) and AWS provider 3.x.

When you get the The security token included in the request is invalid error, it usually means terraform attempted to perform the operation against real AWS rather than localstack.

The following should resolve the issue with creating CloudWatch Event rules.

  1. Make sure you're running the events service in localstack. It's this service, and not cloudwatch, that provides the CloudWatch Events interface. E.g. if you're running localstack from the command line:
SERVICES=cloudwatch,events localstack start
  1. Make sure the AWS provider in the terraform config is pointed to localstack. Like from step (1), we need to make sure to have a setting specifically for CloudWatch Events. In the AWS provider config, that's cloudwatchevents.
provider "aws" {
  version = "~> 3.0"

  profile                     = "<profile used for localstack>"
  region                      = "<region configured for localstack>"
  skip_credentials_validation = true
  skip_metadata_api_check     = true
  skip_requesting_account_id  = true

  endpoints {
    # Update the urls below if you've e.g. customized localstack's port
    cloudwatch        = "http://localhost:4566"
    cloudwatchevents  = "http://localhost:4566"
    iam               = "http://localhost:4566"
    sts               = "http://localhost:4566"
  }
}

Now, the terraform apply should successfully run against localstack.

One more gotcha to be aware of is that localstack currently doesn't persist CloudWatch or CloudWatch Events data, even if you enable persistence. So when you kill or restart localstack, any CloudWatch Events rules will be lost.

Upvotes: 5

Related Questions