Skip to content

Instantly share code, notes, and snippets.

@mizzy
Last active December 25, 2024 06:06
Show Gist options
  • Save mizzy/941d6763a0d3486d3047489eb503c0c6 to your computer and use it in GitHub Desktop.
Save mizzy/941d6763a0d3486d3047489eb503c0c6 to your computer and use it in GitHub Desktop.
locals {
params = {
dev = {
cluster_arn = data.aws_ecs_cluster.dev.arn
subnets = [
data.aws_subnet.dev_private_subnet_a.id,
data.aws_subnet.dev_private_subnet_c.id,
]
security_groups = [data.aws_security_group.dev_default.id]
}
prod = {
cluster_arn = data.aws_ecs_cluster.prod.arn
subnets = [
data.aws_subnet.private_subnet_a.id,
data.aws_subnet.private_subnet_c.id,
]
security_groups = [data.aws_security_group.default.id]
}
}
main_task = {
Type = "Task"
Resource = "arn:aws:states:::ecs:runTask.sync"
ResultPath = "$.result"
Catch = [
{
ErrorEquals = ["States.TaskFailed"]
ResultPath = "$.error-info"
Next = "NotifyFailure"
}
]
End = true
}
overrides = var.command == null ? {
Overrides = {
ContainerOverrides = [{
Name = "${var.name}-${var.environment}"
"Command.$" = "States.Array('sh', '-c', $.command)"
}]
}
} : {}
parameters = {
Parameters = merge({
LaunchType = "FARGATE"
PlatformVersion = "1.4.0"
Cluster = local.params[var.environment]["cluster_arn"]
TaskDefinition = var.environment == "prod" ? aws_ecs_task_definition.prod[0].arn : aws_ecs_task_definition.dev[0].arn
EnableExecuteCommand = true
PropagateTags = "TASK_DEFINITION"
NetworkConfiguration = {
AwsvpcConfiguration = {
Subnets = local.params[var.environment]["subnets"]
SecurityGroups = local.params[var.environment]["security_groups"]
AssignPublicIp = "DISABLED"
}
}
}, local.overrides)
}
retry_on_error = var.retry_on_error == false ? {} : {
Retry = [
{
ErrorEquals = ["States.ALL"]
MaxAttempts = 3
IntervalSeconds = 30
BackoffRate = 2
}
]
}
}
resource "aws_sfn_state_machine" "main" {
name = "${var.name}-${var.environment}"
role_arn = data.aws_iam_role.step_function.arn
definition = jsonencode({
Comment = "${var.name}-${var.environment}"
StartAt = "Main"
States = {
Main = merge(local.main_task, local.parameters, local.retry_on_error)
NotifyFailure = {
Type = "Task"
Resource = "arn:aws:states:::sns:publish"
Parameters = {
TopicArn = data.aws_sns_topic.slack_notification.arn
Subject = "${var.name}-${var.environment} failed"
Message = {
Status = "Fail"
"Arn.$" = "$$.Execution.Id"
"StartTime.$" = "$$.Execution.StartTime"
SlackApp = "Talentio"
SlackChannel = "tech"
}
}
Next = "FailState"
}
FailState = {
Type = "Fail"
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment