diff --git a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java index f644eb8b89..23d93c4948 100644 --- a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java @@ -18,6 +18,7 @@ import io.floci.aws.services.codedeploy.model.DeploymentConfig; import io.floci.aws.services.codedeploy.model.DeploymentGroup; import io.floci.aws.services.codedeploy.model.OnPremisesInstance; import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.Tag; import io.floci.aws.services.ecs.EcsService; import io.floci.aws.services.ecs.model.CreateTaskSetRequest; import io.floci.aws.services.ecs.model.TaskSet; @@ -36,6 +37,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -1092,17 +1094,11 @@ public class CodeDeployService { // EC2 instances by tag filters List> ec2TagFilters = group.getEc2TagFilters(); if (ec2TagFilters != null && !ec2TagFilters.isEmpty()) { - Map> filters = new java.util.LinkedHashMap<>(); - for (Map filter : ec2TagFilters) { - String key = filter.get("Key"); - String value = filter.get("Value"); - if (key != null && value != null) { - filters.computeIfAbsent("tag:" + key, k -> new ArrayList<>()).add(value); - } - } try { - ec2Service.describeInstances(region, null, filters).stream() + ec2Service.describeInstances(region, List.of(), Map.of()).stream() .flatMap(r -> r.getInstances().stream()) + .filter(inst -> matchesTagFilters(ec2TagMaps(inst.getTags()), + ec2TagFilters, TagFilterMatchMode.ANY)) .map(inst -> inst.getInstanceId()) .filter(id -> id != null) .forEach(instanceIds::add); @@ -1133,6 +1129,18 @@ public class CodeDeployService { return instanceIds; } + private List> ec2TagMaps(List tags) { + if (tags == null) { return List.of(); } + List> result = new ArrayList<>(); + for (Tag tag : tags) { + Map fields = new HashMap<>(); + fields.put("Key", tag.getKey()); + fields.put("Value", tag.getValue()); + result.add(fields); + } + return result; + } + private enum TagFilterMatchMode { ALL, ANY } private boolean matchesTagFilters(List> instanceTags, diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServerIntegrationTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServerIntegrationTest.java index a05de5e147..2757e61260 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServerIntegrationTest.java @@ -4,6 +4,8 @@ import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.*; +import java.util.List; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @@ -12,6 +14,10 @@ import static org.hamcrest.Matchers.*; class CodeDeployServerIntegrationTest { private static final String CT = "application/x-amz-json-1.1"; + private static final String EC2_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + private static final String CODEDEPLOY_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/codedeploy/aws4_request"; private static String deploymentId; @@ -355,4 +361,68 @@ class CodeDeployServerIntegrationTest { .then().statusCode(200) .body("instanceNames", hasItem("on-prem-test-1")); } + + @Test + @Order(16) + void ec2DeploymentGroupMatchesAnyTagFilter() { + List instanceIds = given().header("Authorization", EC2_AUTH) + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "4") + .formParam("MaxCount", "4") + .post("/").then().statusCode(200) + .extract().xmlPath().getList("RunInstancesResponse.instancesSet.item.instanceId", String.class); + + tagEc2Instance(instanceIds.get(0), "codedeploy-ec2-team", "red"); + tagEc2Instance(instanceIds.get(1), "codedeploy-ec2-role", "web"); + tagEc2Instance(instanceIds.get(2), "codedeploy-ec2-team", "red"); + tagEc2Instance(instanceIds.get(2), "codedeploy-ec2-role", "web"); + tagEc2Instance(instanceIds.get(3), "codedeploy-ec2-env", "qa"); + + given().contentType(CT).header("Authorization", CODEDEPLOY_AUTH) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .body("{\"applicationName\":\"ec2-tag-filter-any-app\",\"computePlatform\":\"Server\"}") + .post("/").then().statusCode(200); + given().contentType(CT).header("Authorization", CODEDEPLOY_AUTH) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup") + .body(""" + { + "applicationName": "ec2-tag-filter-any-app", + "deploymentGroupName": "group", + "serviceRoleArn": "arn:aws:iam::000000000000:role/CodeDeployRole", + "ec2TagFilters": [ + {"Key": "codedeploy-ec2-team", "Value": "red", "Type": "KEY_AND_VALUE"}, + {"Key": "codedeploy-ec2-role", "Value": "web", "Type": "KEY_AND_VALUE"} + ] + } + """) + .post("/").then().statusCode(200); + String deploymentId = given().contentType(CT).header("Authorization", CODEDEPLOY_AUTH) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeployment") + .body(""" + { + "applicationName": "ec2-tag-filter-any-app", + "deploymentGroupName": "group", + "revision": {"revisionType": "AppSpecContent", "appSpecContent": {"content": "os: linux"}} + } + """) + .post("/").then().statusCode(200) + .extract().jsonPath().getString("deploymentId"); + + given().contentType(CT).header("Authorization", CODEDEPLOY_AUTH) + .header("X-Amz-Target", "CodeDeploy_20141006.ListDeploymentTargets") + .body("{\"deploymentId\":\"" + deploymentId + "\"}") + .post("/").then().statusCode(200) + .body("targetIds", containsInAnyOrder(instanceIds.get(0), instanceIds.get(1), instanceIds.get(2))); + } + + private void tagEc2Instance(String instanceId, String key, String value) { + given().header("Authorization", EC2_AUTH) + .formParam("Action", "CreateTags") + .formParam("ResourceId.1", instanceId) + .formParam("Tag.1.Key", key) + .formParam("Tag.1.Value", value) + .post("/").then().statusCode(200); + } } diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java index d6a8cbe14f..db94e3a014 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java @@ -6,6 +6,9 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.codedeploy.model.Deployment; import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.ec2.model.Reservation; +import io.floci.aws.services.ec2.model.Tag; import io.floci.aws.services.ecs.EcsService; import io.floci.aws.services.elbv2.ElbV2Service; import io.floci.aws.services.lambda.LambdaService; @@ -30,6 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -46,12 +51,14 @@ class CodeDeployServiceTest { private LambdaService lambdaService; private SsmCommandService ssmCommandService; + private Ec2Service ec2Service; private CodeDeployService service; @BeforeEach void setUp() { lambdaService = mock(LambdaService.class); ssmCommandService = mock(SsmCommandService.class); + ec2Service = mock(Ec2Service.class); service = newService(Duration.ofHours(1)); } @@ -61,7 +68,7 @@ class CodeDeployServiceTest { private CodeDeployService newService(Duration hookCallbackTimeout, Clock clock) { CodeDeployService svc = new CodeDeployService(lambdaService, mock(EcsService.class), - mock(ElbV2Service.class), ssmCommandService, mock(Ec2Service.class), new ObjectMapper(), + mock(ElbV2Service.class), ssmCommandService, ec2Service, new ObjectMapper(), new RegionResolver(REGION, ACCOUNT_ID), null, hookCallbackTimeout, clock); svc.initializeStorage(); return svc; @@ -137,6 +144,66 @@ class CodeDeployServiceTest { Set.copyOf(service.listDeploymentTargets(REGION, deploymentId))); } + @Test + void ec2DeploymentGroupMatchesAnyKeyAndValueFilter() { + stubEc2Instances(); + + assertEquals(Set.of("i-team", "i-role", "i-both"), ec2DeploymentTargets("ec2-any-app", List.of( + Map.of("Key", "team", "Value", "red", "Type", "KEY_AND_VALUE"), + Map.of("Key", "role", "Value", "web", "Type", "KEY_AND_VALUE")))); + } + + @Test + void ec2DeploymentGroupHonorsKeyOnlyAndValueOnlyFilters() { + stubEc2Instances(); + + assertEquals(Set.of("i-team", "i-both", "i-team-blue"), + ec2DeploymentTargets("ec2-key-only-app", List.of( + Map.of("Key", "team", "Value", "ignored", "Type", "KEY_ONLY")))); + assertEquals(Set.of("i-role", "i-both", "i-env-web"), + ec2DeploymentTargets("ec2-value-only-app", List.of( + Map.of("Key", "ignored", "Value", "web", "Type", "VALUE_ONLY")))); + assertEquals(Set.of("i-role", "i-both"), + ec2DeploymentTargets("ec2-default-type-app", List.of(Map.of("Key", "role", "Value", "web")))); + } + + @Test + void ec2DeploymentGroupDoesNotPassNullInstanceIdsToDescribeInstances() { + stubEc2Instances(); + ec2DeploymentTargets("ec2-lookup-app", List.of(Map.of("Key", "team", "Value", "red"))); + + verify(ec2Service).describeInstances(eq(REGION), eq(List.of()), eq(Map.of())); + } + + private Set ec2DeploymentTargets(String appName, List> filters) { + service.createApplication(REGION, appName, "Server", null); + service.createDeploymentGroup(REGION, appName, "group", null, ROLE_ARN, + Map.of("ec2TagFilters", filters), null); + String deploymentId = service.createDeployment(REGION, appName, "group", null, + Map.of("appSpecContent", Map.of("content", "os: linux")), null); + return Set.copyOf(service.listDeploymentTargets(REGION, deploymentId)); + } + + private void stubEc2Instances() { + Reservation reservation = new Reservation(); + reservation.setInstances(List.of( + ec2Instance("i-team", new Tag("team", "red")), + ec2Instance("i-role", new Tag("role", "web")), + ec2Instance("i-both", new Tag("team", "red"), new Tag("role", "web")), + ec2Instance("i-team-blue", new Tag("team", "blue")), + ec2Instance("i-env-web", new Tag("env", "web")), + ec2Instance("i-neither", new Tag("env", "qa")))); + when(ec2Service.describeInstances(eq(REGION), anyList(), anyMap())) + .thenReturn(List.of(reservation)); + } + + private Instance ec2Instance(String id, Tag... tags) { + Instance instance = new Instance(); + instance.setInstanceId(id); + instance.setTags(List.of(tags)); + return instance; + } + // ---- Server platform (SSM) hooks --------------------------------------------------- @Test