feat(cloudformation): provision ElastiCache replication groups (#8448)

CloudFormation now provisions AWS::ElastiCache::ReplicationGroup instead
of completing the stack with no cache behind it. The group is created
through the ElastiCache service, Ref returns its id, and Fn::GetAtt
exposes the configuration endpoint for a cluster-mode group or the
primary, reader and per-node read endpoints otherwise. A create-only
change replaces the group, an explicit ReplicationGroupId that stays the
same is refused, and an update that reuses the group warns only about the
properties it ignores.

Optional booleans in the ElastiCache, IoT authorizer, API Gateway API key
and StackSet provisioners are read through
ProvisionContext.resolveOptionalBoolean, which refuses a value that is
neither true nor false instead of reading it as false.

Closes #8447
This commit is contained in:
Maxence LEFEBVRE authored and GitHub committed 2026-11-15 11:40:48 -04:00
1 parent 3fa20af859
commit 9e05c07bfc
16 files changed
+512 -34

No files matched your search

@@ -82,11 +82,11 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
if (customerId != null && !customerId.isBlank()) {
request.put("customerId", customerId);
}
Boolean enabled = resolveBoolean(props, "Enabled", ctx);
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
if (enabled != null) {
request.put("enabled", enabled);
}
Boolean generateDistinctId = resolveBoolean(props, "GenerateDistinctId", ctx);
Boolean generateDistinctId = ctx.resolveOptionalBoolean(props, "GenerateDistinctId");
if (generateDistinctId != null) {
request.put("generateDistinctId", generateDistinctId);
}
@@ -110,7 +110,7 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
if (value != null && !value.isBlank()) {
rejectIfChanged("Value", existing.getValue(), value);
}
Boolean requestedDistinct = resolveBoolean(props, "GenerateDistinctId", ctx);
Boolean requestedDistinct = ctx.resolveOptionalBoolean(props, "GenerateDistinctId");
if (requestedDistinct != null) {
boolean existingDistinct = !Objects.equals(existing.getId(), existing.getValue());
if (requestedDistinct != existingDistinct) {
@@ -119,7 +119,7 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
}
// Enabled defaults to false when the template omits it, as in the AWS registry schema.
Boolean enabled = resolveBoolean(props, "Enabled", ctx);
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
List<Map<String, String>> patches = patchesTo(existing, ctx.resolveOptional(props, "CustomerId"),
ctx.resolveOptional(props, "Description"), enabled != null && enabled);
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
@@ -182,11 +182,6 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("APIKeyId", key.getId());
}
private static Boolean resolveBoolean(JsonNode props, String name, ProvisionContext ctx) {
String resolved = ctx.resolveOptional(props, name);
return resolved == null || resolved.isBlank() ? null : Boolean.parseBoolean(resolved);
}
private static void rejectIfChanged(String property, String existing, String requested) {
if (!Objects.equals(blankToNull(existing), blankToNull(requested))) {
throw replacementNotSupported(property);
@@ -14,18 +14,21 @@ import io.floci.aws.services.elasticache.model.CacheSubnetGroup;
import io.floci.aws.services.elasticache.model.ElastiCacheUser;
import io.floci.aws.services.elasticache.model.ElastiCacheUserGroup;
import io.floci.aws.services.elasticache.model.Endpoint;
import io.floci.aws.services.elasticache.model.ReplicationGroup;
import io.floci.aws.services.elasticache.model.ReplicationGroupSettings;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Provisions AWS::ElastiCache::CacheCluster, SubnetGroup, User and UserGroup. A cache cluster needs
* Provisions AWS::ElastiCache::CacheCluster, ReplicationGroup, SubnetGroup, User and UserGroup. A cache cluster needs
* the Memcached service as well as the Redis one, because the two engines keep their clusters in
* separate stores.
*/
@@ -36,6 +39,7 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CACHE_CLUSTER = "AWS::ElastiCache::CacheCluster";
private static final String REPLICATION_GROUP = "AWS::ElastiCache::ReplicationGroup";
private static final String SUBNET_GROUP = "AWS::ElastiCache::SubnetGroup";
private static final String USER = "AWS::ElastiCache::User";
private static final String USER_GROUP = "AWS::ElastiCache::UserGroup";
@@ -45,7 +49,16 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
private static final List<String> UNSUPPORTED_CLUSTER_PROPERTIES = List.of("CacheSecurityGroupNames",
"NotificationTopicArn", "AZMode", "PreferredAvailabilityZones", "LogDeliveryConfigurations",
"SnapshotArns", "SnapshotName");
private static final List<String> UNSUPPORTED_REPLICATION_GROUP_PROPERTIES = List.of("CacheSecurityGroupNames",
"NotificationTopicArn", "PreferredCacheClusterAZs", "LogDeliveryConfigurations", "SnapshotArns",
"SnapshotName", "GlobalReplicationGroupId", "NodeGroupConfiguration", "PrimaryClusterId",
"SnapshottingClusterId", "DataTieringEnabled");
private static final List<String> REPLICATION_GROUP_ENDPOINT_ATTRIBUTES = List.of(
"PrimaryEndPoint.Address", "PrimaryEndPoint.Port", "ReaderEndPoint.Address", "ReaderEndPoint.Port",
"ReadEndPoint.Addresses", "ReadEndPoint.Addresses.List", "ReadEndPoint.Ports", "ReadEndPoint.Ports.List",
"ConfigurationEndPoint.Address", "ConfigurationEndPoint.Port");
private static final int CLUSTER_ID_MAX_LENGTH = 50;
private static final int REPLICATION_GROUP_ID_MAX_LENGTH = 40;
private static final int SUBNET_GROUP_NAME_MAX_LENGTH = 255;
private final ElastiCacheService elastiCacheService;
@@ -60,7 +73,12 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
return Set.of(CACHE_CLUSTER, SUBNET_GROUP, USER, USER_GROUP);
return Set.of(CACHE_CLUSTER, REPLICATION_GROUP, SUBNET_GROUP, USER, USER_GROUP);
}
@Override
public Map<String, Set<String>> jsonAttributes() {
return Map.of(REPLICATION_GROUP, Set.of("ReadEndPoint.Addresses.List", "ReadEndPoint.Ports.List"));
}
@Override
@@ -71,6 +89,7 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
switch (r.getResourceType()) {
case CACHE_CLUSTER -> provisionCacheCluster(r, props, ctx);
case REPLICATION_GROUP -> provisionReplicationGroup(r, props, ctx);
case SUBNET_GROUP -> provisionSubnetGroup(r, props, ctx);
case USER -> provisionUser(r, props, ctx);
case USER_GROUP -> provisionUserGroup(r, props, ctx);
@@ -209,10 +228,10 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
putEndpointAttributes(r, cluster);
}
private void warnUnsupportedClusterProperties(String id, JsonNode props) {
for (String name : UNSUPPORTED_CLUSTER_PROPERTIES) {
private static void warnUnsupportedProperties(String kind, String id, JsonNode props, List<String> names) {
for (String name : names) {
if (props.hasNonNull(name)) {
LOG.warnv("ElastiCache cache cluster {0}: {1} is accepted and ignored", id, name);
LOG.warnv("ElastiCache {0} {1}: {2} is accepted and ignored", kind, id, name);
}
}
}
@@ -231,7 +250,7 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
private CacheCluster createCluster(String id, String engine, Integer port, JsonNode props,
ProvisionContext ctx) {
warnUnsupportedClusterProperties(id, props);
warnUnsupportedProperties("cache cluster", id, props, UNSUPPORTED_CLUSTER_PROPERTIES);
List<String> securityGroupIds = ctx.resolveStringList(props, "VpcSecurityGroupIds");
ElastiCacheService.CreateCacheClusterRequest request = new ElastiCacheService.CreateCacheClusterRequest(
id,
@@ -294,6 +313,163 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
}
}
private void provisionReplicationGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
String description = ctx.resolveOptional(props, "ReplicationGroupDescription");
if (description == null || description.isBlank()) {
throw new AwsException("ValidationException", "ReplicationGroupDescription is required", 400);
}
String explicitId = ctx.resolveOptional(props, "ReplicationGroupId");
if (explicitId != null && explicitId.length() > REPLICATION_GROUP_ID_MAX_LENGTH) {
throw new AwsException("ValidationException",
"ReplicationGroupId exceeds maximum length of " + REPLICATION_GROUP_ID_MAX_LENGTH, 400);
}
ReplicationGroup prior = ctx.isUpdate() ? findReplicationGroup(ctx.priorPhysicalId()) : null;
// As for a cache cluster: a create-only change replaces the group, which needs a new id.
boolean createOnlyChanged = prior != null && ctx.changes(REPLICATION_GROUP, props).requiresReplacement();
if (createOnlyChanged && explicitId != null && explicitId.equals(ctx.priorPhysicalId())) {
throw new AwsException("InvalidParameterValue", "Updating a create-only property of replication group "
+ explicitId + " requires a new ReplicationGroupId", 400);
}
String id = createOnlyChanged && explicitId == null
? ctx.generatePhysicalName(r.getLogicalId(), REPLICATION_GROUP_ID_MAX_LENGTH, true)
: ctx.stablePhysicalName(explicitId, r.getLogicalId(), REPLICATION_GROUP_ID_MAX_LENGTH, true);
ReplicationGroup group;
if (ctx.reusesPriorEntity(id)) {
group = prior != null ? prior : findReplicationGroup(id);
if (group == null) {
LOG.warnv("ElastiCache replication group {0} was deleted outside the stack, recreating it", id);
group = createReplicationGroup(id, description, props, ctx);
} else {
warnIgnoredReplicationGroupChanges(id, group, description, props, ctx);
}
} else {
group = createReplicationGroup(id, description, props, ctx);
}
r.setPhysicalId(id);
putReplicationGroupEndpointAttributes(r, group);
}
private static void warnIgnoredReplicationGroupChanges(String id, ReplicationGroup group, String description,
JsonNode props, ProvisionContext ctx) {
List<String> changed = new ArrayList<>();
if (!description.equals(group.getDescription())) {
changed.add("ReplicationGroupDescription");
}
String nodeType = ctx.resolveOptional(props, "CacheNodeType");
if (nodeType != null && !nodeType.equals(group.getCacheNodeType())) {
changed.add("CacheNodeType");
}
String version = ctx.resolveOptional(props, "EngineVersion");
if (version != null && !version.equals(group.getEngineVersion())) {
changed.add("EngineVersion");
}
Integer clusters = ctx.resolveOptionalInt(props, "NumCacheClusters");
if (clusters != null && clusters != group.getNumCacheClusters()) {
changed.add("NumCacheClusters");
}
// the service stores user group ids in lowercase
Set<String> userGroupIds = new HashSet<>();
ctx.resolveStringList(props, "UserGroupIds").forEach(g -> userGroupIds.add(g.toLowerCase(Locale.ROOT)));
if (!userGroupIds.equals(group.getUserGroupIds())) {
changed.add("UserGroupIds");
}
if (!changed.isEmpty()) {
LOG.warnv("ElastiCache replication group {0}: in-place modification is not supported, changes to {1} "
+ "are ignored", id, String.join(", ", changed));
}
}
private ReplicationGroup createReplicationGroup(String id, String description, JsonNode props,
ProvisionContext ctx) {
warnUnsupportedProperties("replication group", id, props, UNSUPPORTED_REPLICATION_GROUP_PROPERTIES);
String authToken = ctx.resolveOptional(props, "AuthToken");
boolean hasAuthToken = authToken != null && !authToken.isBlank();
List<String> userGroupIds = ctx.resolveStringList(props, "UserGroupIds");
List<String> securityGroupIds = ctx.resolveStringList(props, "SecurityGroupIds");
ReplicationGroupSettings settings = new ReplicationGroupSettings(
ctx.resolveOptionalBoolean(props, "AtRestEncryptionEnabled"),
ctx.resolveOptional(props, "KmsKeyId"),
ctx.resolveOptionalInt(props, "SnapshotRetentionLimit"),
ctx.resolveOptional(props, "SnapshotWindow"),
ctx.resolveOptional(props, "TransitEncryptionMode"),
ctx.resolveOptionalBoolean(props, "TransitEncryptionEnabled"));
return elastiCacheService.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
id,
description,
hasAuthToken ? AuthMode.PASSWORD : AuthMode.NO_AUTH,
hasAuthToken ? authToken : null,
ctx.region(),
ctx.resolveOptional(props, "Engine"),
ctx.resolveOptional(props, "EngineVersion"),
ctx.resolveOptional(props, "CacheNodeType"),
ctx.resolveOptional(props, "CacheParameterGroupName"),
ctx.resolveOptional(props, "CacheSubnetGroupName"),
ctx.resolveOptional(props, "ClusterMode"),
ctx.resolveOptionalInt(props, "NumNodeGroups"),
ctx.resolveOptionalInt(props, "ReplicasPerNodeGroup"),
ctx.resolveOptionalInt(props, "NumCacheClusters"),
ctx.resolveOptionalBoolean(props, "AutomaticFailoverEnabled"),
ctx.resolveOptionalBoolean(props, "MultiAZEnabled"),
ctx.resolveOptionalInt(props, "Port"),
settings,
ctx.resolveTags(props, "Tags"),
userGroupIds.isEmpty() ? null : userGroupIds,
securityGroupIds.isEmpty() ? null : securityGroupIds));
}
/**
* Sets the endpoint attributes AWS exposes for the group's mode: a cluster-mode group answers on its
* ConfigurationEndPoint, any other on its primary and reader endpoints and one read endpoint per node.
*/
private void putReplicationGroupEndpointAttributes(StackResource r, ReplicationGroup group) {
REPLICATION_GROUP_ENDPOINT_ATTRIBUTES.forEach(r.getAttributes()::remove);
Endpoint endpoint = group.getConfigurationEndpoint();
if (endpoint == null) {
return;
}
String port = String.valueOf(endpoint.port());
if (group.isClusterEnabled()) {
r.getAttributes().put("ConfigurationEndPoint.Address", endpoint.address());
r.getAttributes().put("ConfigurationEndPoint.Port", port);
return;
}
r.getAttributes().put("PrimaryEndPoint.Address", endpoint.address());
r.getAttributes().put("PrimaryEndPoint.Port", port);
r.getAttributes().put("ReaderEndPoint.Address", endpoint.address());
r.getAttributes().put("ReaderEndPoint.Port", port);
List<String> addresses = new ArrayList<>();
List<String> ports = new ArrayList<>();
for (ElastiCacheService.MemberCacheCluster member : elastiCacheService.memberCacheClusters(group)) {
addresses.add(endpoint.address());
ports.add(String.valueOf(member.port()));
}
r.getAttributes().put("ReadEndPoint.Addresses", String.join(",", addresses));
r.getAttributes().put("ReadEndPoint.Ports", String.join(",", ports));
try {
r.getAttributes().put("ReadEndPoint.Addresses.List", MAPPER.writeValueAsString(addresses));
r.getAttributes().put("ReadEndPoint.Ports.List", MAPPER.writeValueAsString(ports));
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}
private ReplicationGroup findReplicationGroup(String groupId) {
if (groupId == null || groupId.isBlank()) {
return null;
}
try {
return elastiCacheService.getReplicationGroup(groupId);
} catch (AwsException e) {
if ("ReplicationGroupNotFoundFault".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private void provisionSubnetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
String description = ctx.resolveOptional(props, "Description");
if (description == null || description.isBlank()) {
@@ -448,6 +624,8 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
elastiCacheService.deleteCacheCluster(physicalId);
}
}, "CacheClusterNotFound");
case REPLICATION_GROUP -> CfnDeletes.safeDelete("ElastiCache replication group", physicalId,
() -> elastiCacheService.deleteReplicationGroup(physicalId), "ReplicationGroupNotFoundFault");
case SUBNET_GROUP -> CfnDeletes.safeDelete("ElastiCache subnet group", physicalId,
() -> elastiCacheService.deleteCacheSubnetGroup(physicalId), "CacheSubnetGroupNotFoundFault");
case USER_GROUP -> CfnDeletes.safeDelete("ElastiCache user group", physicalId,
@@ -82,13 +82,13 @@ public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
}
String explicitName = resolvePresent(props, "AuthorizerName", ctx);
boolean hasExplicitName = explicitName != null;
String signingDisabled = resolveBoolean(props, "SigningDisabled", ctx);
Boolean signingDisabled = ctx.resolveOptionalBoolean(props, "SigningDisabled");
ObjectNode declared = MAPPER.createObjectNode().put("authorizerFunctionArn", functionArn);
putIfPresent(declared, "status", resolvePresent(props, "Status", ctx));
putIfPresent(declared, "tokenKeyName", resolvePresent(props, "TokenKeyName", ctx));
String caching = resolveBoolean(props, "EnableCachingForHttp", ctx);
Boolean caching = ctx.resolveOptionalBoolean(props, "EnableCachingForHttp");
if (caching != null) {
declared.put("enableCachingForHttp", Boolean.parseBoolean(caching));
declared.put("enableCachingForHttp", caching);
}
JsonNode keys = props == null ? null : ctx.engine().resolveNode(props.get("TokenSigningPublicKeys"));
if (keys != null && keys.isObject()) {
@@ -111,7 +111,7 @@ public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
? authorizerService.describeAuthorizer(ctx.priorPhysicalId(), ctx.region())
: null;
// ponytail: compared with the stored flag, so an absent SigningDisabled reads as its API default false.
boolean signingChanged = prior != null && prior.isSigningDisabled() != Boolean.parseBoolean(signingDisabled);
boolean signingChanged = prior != null && prior.isSigningDisabled() != Boolean.TRUE.equals(signingDisabled);
boolean nameWasGenerated = NAME_MODE_GENERATED.equals(attributesBefore.get(NAME_MODE_ATTR));
if ((signingChanged || nameWasGenerated) && hasExplicitName && explicitName.equals(ctx.priorPhysicalId())) {
throw new AwsException("ValidationError",
@@ -132,7 +132,7 @@ public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
}
} else {
if (signingDisabled != null) {
declared.put("signingDisabled", Boolean.parseBoolean(signingDisabled));
declared.put("signingDisabled", signingDisabled);
}
if (!tags.isEmpty()) {
ArrayNode tagList = declared.putArray("tags");
@@ -181,15 +181,6 @@ public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
return literal || (value != null && !value.isEmpty()) ? value : null;
}
/** A present boolean property, refused unless it is true or false rather than read as false. */
private static String resolveBoolean(JsonNode props, String name, ProvisionContext ctx) {
String value = resolvePresent(props, name, ctx);
if (value != null && !"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
throw new AwsException("ValidationError", TYPE + " " + name + " must be true or false, got " + value, 400);
}
return value;
}
private static void putIfPresent(ObjectNode body, String field, String value) {
if (value != null) {
body.put(field, value);
@@ -204,6 +204,24 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
}
}
/**
* Resolves an optional boolean property, or null when it is absent or explicitly null. An intrinsic
* that resolves to empty ({@code AWS::NoValue}) stays null too. Any other value has to be true or
* false in any case, the string forms CloudFormation also accepts included; anything else, a
* whitespace-only intrinsic result included, is refused rather than read as false.
*/
public Boolean resolveOptionalBoolean(JsonNode props, String name) {
String value = resolveOptional(props, name);
if (value == null || (value.isEmpty() && !props.get(name).isTextual())) {
return null;
}
String trimmed = value.trim();
if (!"true".equalsIgnoreCase(trimmed) && !"false".equalsIgnoreCase(trimmed)) {
throw new AwsException("ValidationError", "Value of property " + name + " must be a boolean.", 400);
}
return Boolean.parseBoolean(trimmed);
}
/**
* Resolves an optional property through the engine, falling back to {@code defaultValue} when it
* is absent or resolves to blank. Shared by the per-service provisioners so none carries its own
@@ -347,8 +347,7 @@ public class StackSetCfnProvisioner implements CfnResourceProvisioner {
}
private static Boolean optionalBoolean(JsonNode node, String name, ProvisionContext ctx) {
String value = ctx.resolveOptional(node.isObject() ? node : null, name);
return value == null || value.isBlank() ? null : Boolean.valueOf(value);
return ctx.resolveOptionalBoolean(node.isObject() ? node : null, name);
}
}