16/07/2023 - AWS, TERRAFORM
In this example we are going to use Terraform to configure AWS EventBridge to periodically call a HTTP endpoint once every minute. It will send a basic POST request with a simple authentication header but without body or any other URL parameters which is each to add. The only thing that you need to be aware of is that, the "connection" resource uses AWS Secret Manager behind the scene to handle secrets so if you are using AWS Free Tier, it is free to use only for the first month at the time of writing this post.
terraform {
required_version = "~> 1.4.4"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.41.0"
}
}
}
provider "aws" {
profile = "development"
region = "eu-west-1"
}
locals {
auth_token = "this-is-my-static-auth-token"
}
resource "aws_cloudwatch_event_connection" "this" {
name = "api-key"
description = "Used as a simple key-value header authentication"
authorization_type = "API_KEY"
auth_parameters {
api_key {
key = "X-Auth-Token"
value = local.auth_token
}
}
}
resource "aws_cloudwatch_event_api_destination" "this" {
name = "audit-user-access"
description = "Records user access data for auditing purposes"
invocation_endpoint = "https://webhook.site/PUT-YOUR-UUID-HERE"
http_method = "POST"
invocation_rate_limit_per_second = 1
connection_arn = aws_cloudwatch_event_connection.this.arn
}
resource "aws_cloudwatch_event_rule" "this" {
name = "once-every-minute"
description = "Run once every minute"
schedule_expression = "cron(* * * * ? *)"
}
resource "aws_cloudwatch_event_target" "this" {
target_id = "audit-user-access-once-every-minute"
rule = aws_cloudwatch_event_rule.this.name
arn = aws_cloudwatch_event_api_destination.this.arn
role_arn = aws_iam_role.this.arn
}
resource "aws_iam_role" "this" {
name = "once-every-minute-cron-executor"
managed_policy_arns = [aws_iam_policy.this.arn]
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "events.amazonaws.com"
}
},
]
})
}
resource "aws_iam_policy" "this" {
name = "once-every-minute-cron-executor"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "events:InvokeApiDestination"
Effect = "Allow"
Resource = aws_cloudwatch_event_api_destination.this.arn
},
]
})
}