feat(eventbridge): run ECS tasks from classic rule targets (#3484)

PutTargets now parses EcsParameters on an ECS cluster ARN target and
the invoker calls ecs:RunTask when the rule fires, mirroring how the
Scheduler already delivers to ECS. An InputTransformer shaped as a
TaskOverride is parsed into containerOverrides and passed through, per
AWS's documented ECS target behavior.

* Fix #2558

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-12 14:00:19 -04:00
1 parent 6507f32aea
commit cfe9f84ffe
8 files changed
+697 -3

No files matched your search

@@ -0,0 +1,206 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
/**
* Verifies that a classic EventBridge rule target pointing at an ECS cluster (with
* {@code EcsParameters}, the shape Terraform's {@code aws_cloudwatch_event_target}
* {@code ecs_target} block or {@code aws events put-targets} produces) round-trips
* through PutTargets/ListTargetsByRule and actually calls ECS RunTask when the rule fires.
*/
@QuarkusTest
class EventBridgeEcsRunTaskIntegrationTest {
private static final String EVENT_BRIDGE_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113.";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void putEventsEcsClusterTargetRunsTaskWithEcsParameters() {
String suffix = Long.toString(System.nanoTime(), 36);
String clusterName = "eb-ecs-cluster-" + suffix;
String family = "eb-ecs-family-" + suffix;
String ruleName = "eb-ecs-rule-" + suffix;
String source = "local.ecstest";
String detailType = "EcsTestTrigger";
String clusterArn = createCluster(clusterName);
String taskDefinitionArn = registerTaskDefinition(family);
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutRule")
.body("""
{"Name":"%s","EventPattern":"{\\"source\\":[\\"%s\\"],\\"detail-type\\":[\\"%s\\"]}"}
""".formatted(ruleName, source, detailType))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutTargets")
.body("""
{
"Rule": "%s",
"Targets": [{
"Id": "ecs-target",
"Arn": "%s",
"EcsParameters": {
"TaskDefinitionArn": "%s",
"TaskCount": 1,
"LaunchType": "FARGATE",
"Group": "eb-ecs-group-%s",
"NetworkConfiguration": {
"awsvpcConfiguration": {
"Subnets": ["subnet-1", "subnet-2"],
"SecurityGroups": ["sg-1"],
"AssignPublicIp": "ENABLED"
}
}
}
}]
}
""".formatted(ruleName, clusterArn, taskDefinitionArn, suffix))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedEntryCount", equalTo(0));
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.ListTargetsByRule")
.body("""
{"Rule": "%s"}
""".formatted(ruleName))
.when()
.post("/")
.then()
.statusCode(200)
.body("Targets[0].Arn", equalTo(clusterArn))
.body("Targets[0].EcsParameters.TaskDefinitionArn", equalTo(taskDefinitionArn))
.body("Targets[0].EcsParameters.TaskCount", equalTo(1))
.body("Targets[0].EcsParameters.LaunchType", equalTo("FARGATE"))
.body("Targets[0].EcsParameters.Group", equalTo("eb-ecs-group-" + suffix))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets",
hasItem("subnet-1"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.SecurityGroups",
hasItem("sg-1"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.AssignPublicIp",
equalTo("ENABLED"));
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutEvents")
.body("""
{
"Entries": [{
"Source": "%s",
"DetailType": "%s",
"Detail": "{}"
}]
}
""".formatted(source, detailType))
.when()
.post("/")
.then()
.statusCode(200);
ecs("ListTasks")
.body("""
{"cluster": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.statusCode(200)
.body("taskArns", hasSize(1));
String taskArn = ecs("ListTasks")
.body("""
{"cluster": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.extract().path("taskArns[0]");
ecs("DescribeTasks")
.body("""
{
"cluster": "%s",
"tasks": ["%s"]
}
""".formatted(clusterName, taskArn))
.when()
.post("/")
.then()
.statusCode(200)
.body("tasks[0].taskDefinitionArn", equalTo(taskDefinitionArn))
.body("tasks[0].launchType", equalTo("FARGATE"))
.body("tasks[0].startedBy", equalTo("eb-ecs-group-" + suffix))
.body("tasks[0].lastStatus", notNullValue());
}
private static String createCluster(String clusterName) {
return ecs("CreateCluster")
.body("""
{"clusterName": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.statusCode(200)
.body("cluster.clusterArn", containsString(clusterName))
.extract().path("cluster.clusterArn");
}
private static String registerTaskDefinition(String family) {
return ecs("RegisterTaskDefinition")
.body("""
{
"family": "%s",
"containerDefinitions": [
{
"name": "app",
"image": "nginx:latest",
"cpu": 256,
"memory": 512,
"essential": true
}
],
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"networkMode": "awsvpc"
}
""".formatted(family))
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("taskDefinition.taskDefinitionArn");
}
private static io.restassured.specification.RequestSpecification ecs(String action) {
return given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", ECS_TARGET_PREFIX + action);
}
}
@@ -4,8 +4,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.eventbridge.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
@@ -34,6 +39,7 @@ class EventBridgeInvokerTest {
private BatchService batchService;
private FirehoseService firehoseService;
private EventBridgeService eventBridgeService;
private EcsService ecsService;
private RegionResolver regionResolver;
@BeforeEach
@@ -44,6 +50,7 @@ class EventBridgeInvokerTest {
batchService = mock(BatchService.class);
firehoseService = mock(FirehoseService.class);
eventBridgeService = mock(EventBridgeService.class);
ecsService = mock(EcsService.class);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(eventBridgeService.putEvents(anyList(), anyString(), any()))
@@ -55,6 +62,8 @@ class EventBridgeInvokerTest {
batchService,
firehoseService,
eventBridgeService,
ecsService,
new io.github.hectorvent.floci.services.ecs.EcsJsonHandler(ecsService, new ObjectMapper()),
regionResolver,
new ObjectMapper(),
mock(io.github.hectorvent.floci.config.EmulatorConfig.class)
@@ -157,6 +166,138 @@ class EventBridgeInvokerTest {
);
}
@Test
void invokeTarget_ecsClusterTarget_runsTaskWithEcsParameters() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:3");
ecsParameters.setTaskCount(2);
ecsParameters.setLaunchType("FARGATE");
ecsParameters.setGroup("my-group");
AwsVpcConfiguration awsVpcConfiguration = new AwsVpcConfiguration();
awsVpcConfiguration.setSubnets(List.of("subnet-1", "subnet-2"));
awsVpcConfiguration.setSecurityGroups(List.of("sg-1"));
awsVpcConfiguration.setAssignPublicIp("ENABLED");
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsVpcConfiguration);
ecsParameters.setNetworkConfiguration(networkConfiguration);
target.setEcsParameters(ecsParameters);
invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1");
ArgumentCaptor<io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration> networkCaptor =
ArgumentCaptor.forClass(io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration.class);
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:3"),
eq(2),
eq(LaunchType.FARGATE),
isNull(),
eq("my-group"),
eq(List.of()),
networkCaptor.capture(),
eq("us-west-2")
);
assertEquals(List.of("subnet-1", "subnet-2"),
networkCaptor.getValue().getAwsvpcConfiguration().getSubnets());
assertEquals(List.of("sg-1"),
networkCaptor.getValue().getAwsvpcConfiguration().getSecurityGroups());
assertEquals("ENABLED", networkCaptor.getValue().getAwsvpcConfiguration().getAssignPublicIp());
}
@Test
void invokeTarget_ecsClusterTarget_defaultsTaskCountAndGroupWhenAbsent() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1");
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
eq(List.of()),
isNull(),
eq("us-west-2")
);
}
@Test
void invokeTarget_ecsClusterTargetWithInputTransformer_passesThroughContainerOverrides() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
target.setInputTransformer(new InputTransformer(
Map.of("orderId", "$.detail.orderId"),
"{\"containerOverrides\":[{\"name\":\"app\",\"command\":[\"process\",\"<orderId>\"],"
+ "\"environment\":[{\"name\":\"ORDER_ID\",\"value\":\"<orderId>\"}]}]}"));
invoker.invokeTarget(target, "{\"detail\":{\"orderId\":\"o-42\"}}", "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<io.github.hectorvent.floci.services.ecs.model.ContainerOverride>> overridesCaptor =
ArgumentCaptor.forClass(List.class);
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
overridesCaptor.capture(),
isNull(),
eq("us-west-2")
);
io.github.hectorvent.floci.services.ecs.model.ContainerOverride override = overridesCaptor.getValue().get(0);
assertEquals("app", override.getName());
assertEquals(List.of("process", "o-42"), override.getCommand());
assertEquals("ORDER_ID", override.getEnvironment().get(0).name());
assertEquals("o-42", override.getEnvironment().get(0).value());
}
@Test
void invokeTarget_ecsClusterTargetWithMalformedTransformedOutput_launchesWithoutOverrides() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
target.setInput("not-json");
assertDoesNotThrow(() -> invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1"));
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
eq(List.of()),
isNull(),
eq("us-west-2")
);
}
@Test
void invokeTarget_ecsClusterTargetWithoutEcsParameters_skipsWithoutThrowing() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
assertDoesNotThrow(() -> invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1"));
verify(ecsService, never()).runTask(any(), any(), anyInt(), any(), any(), any(), anyList(), any(), any());
}
@Test
void invokeTarget_firehoseTarget_putsEventJsonAsRecordData() {
Target target = new Target("id1",