feat(cloudformation): provision AWS::BedrockAgentCore::Runtime, RuntimeEndpoint and Memory (#5226)

* feat(cloudformation): provision AWS::BedrockAgentCore::Runtime, RuntimeEndpoint and Memory

The AgentCore control plane is emulated but had no CloudFormation provisioner,
so the three types fell through to the generic stub that exposes only Arn and
a template using Fn::GetAtt [Memory, MemoryArn] in an IAM policy failed the
stack. BedrockAgentCoreCfnProvisioner maps every template property the
services can store onto CreateAgentRuntime / CreateAgentRuntimeEndpoint /
CreateMemory, publishes Ref as the registry schema's primaryIdentifier and
Fn::GetAtt for every read-only property, updates in place when the
create-only properties are unchanged and replaces otherwise, and deletes on
stack teardown. Properties the emulated services have no model for are logged
once at warn and listed in the docs.

* fix(cloudformation): make AgentCore updates rollback-aware and authoritative

Reachable through CfnProvisionerFixture (two-service inference arm). In-place
updates snapshot the prior runtime, endpoint and memory configuration and tags,
restore them on rollback, and delete a created entity when a later step of the
same provision fails. The template is authoritative: UpdateAgentRuntime replaces
the full configuration as AWS's PUT does (omitted authorizer, protocol and
environment are cleared on the SDK path too), and the partial-update Memory and
Endpoint calls get a replace-omitted overload for the provisioner. Nested
AWS::NoValue members are omitted rather than stored blank, and the control
service validates networkMode and serverProtocol with the API's
ValidationException wording.

* fix(cloudformation): accept AGUI runtimes and share the guarded provision helper

The protocol check left out AGUI, which the AgentCore API and the Runtime
schema allow, so an AG-UI runtime was refused through the API and in a stack.

Ec2NetworkCfnProvisioner and BedrockAgentCoreCfnProvisioner carried the same
guarded helper; it now lives on CfnRollback, taking the provisioner's
in-place undo as a callback, and both use it.
This commit is contained in:
danielxoi authored and GitHub committed 2026-10-12 21:38:57 -04:00
1 parent 999ccde676
commit f50437efba
16 files changed
+1642 -83

No files matched your search

@@ -40,6 +40,8 @@ public class BedrockAgentCoreControlService {
static final String STATUS_DELETING = "DELETING";
private static final String ARN_SERVICE = "bedrock-agentcore";
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}");
private static final List<String> NETWORK_MODES = List.of("PUBLIC", "VPC");
private static final List<String> SERVER_PROTOCOLS = List.of("MCP", "HTTP", "A2A", "AGUI");
private static final String ID_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int MAX_PAGE = 100;
@@ -103,6 +105,7 @@ public class BedrockAgentCoreControlService {
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("ValidationException", "roleArn is required", 400);
}
validateConfiguration(networkConfiguration, protocolConfiguration);
Instant now = Instant.now();
String id = name + "-" + randomId();
@@ -157,6 +160,11 @@ public class BedrockAgentCoreControlService {
"AgentCore runtime version not found: " + wanted, 404));
}
/**
* UpdateAgentRuntime is a PUT that publishes a new version holding exactly the configuration
* the request carries, so an omitted (null) description, authorizer, protocol or environment
* is cleared on the new version rather than carried over from the previous one.
*/
public AgentRuntime updateAgentRuntime(String id, JsonNode artifact, JsonNode networkConfiguration,
String roleArn, String description, Map<String, String> environmentVariables,
JsonNode authorizerConfiguration, JsonNode protocolConfiguration,
@@ -170,6 +178,7 @@ public class BedrockAgentCoreControlService {
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("ValidationException", "roleArn is required", 400);
}
validateConfiguration(networkConfiguration, protocolConfiguration);
AgentRuntime runtime = getAgentRuntime(id, region);
Instant now = Instant.now();
@@ -179,15 +188,9 @@ public class BedrockAgentCoreControlService {
runtime.setDescription(description);
runtime.setAgentRuntimeArtifact(artifact);
runtime.setNetworkConfiguration(networkConfiguration);
if (authorizerConfiguration != null) {
runtime.setAuthorizerConfiguration(authorizerConfiguration);
}
if (protocolConfiguration != null) {
runtime.setProtocolConfiguration(protocolConfiguration);
}
if (environmentVariables != null) {
runtime.setEnvironmentVariables(new HashMap<>(environmentVariables));
}
runtime.setAuthorizerConfiguration(authorizerConfiguration);
runtime.setProtocolConfiguration(protocolConfiguration);
runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>());
runtime.setLastUpdatedAt(now);
runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now));
@@ -196,6 +199,30 @@ public class BedrockAgentCoreControlService {
return runtime;
}
/**
* The enum members of a runtime's network and protocol configuration, rejected with the API's
* ValidationException wording. The artifact and the rest of each blob stay opaque.
*/
private static void validateConfiguration(JsonNode networkConfiguration, JsonNode protocolConfiguration) {
requireEnum(networkConfiguration.path("networkMode"), "networkConfiguration.networkMode", NETWORK_MODES);
if (protocolConfiguration != null && !protocolConfiguration.isNull()) {
requireEnum(protocolConfiguration.path("serverProtocol"), "protocolConfiguration.serverProtocol",
SERVER_PROTOCOLS);
}
}
private static void requireEnum(JsonNode value, String member, List<String> allowed) {
if (value.isMissingNode() || value.isNull()) {
throw new AwsException("ValidationException", member + " is required", 400);
}
if (!value.isTextual() || !allowed.contains(value.asText())) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + value.asText() + "' at '" + member
+ "' failed to satisfy constraint: Member must satisfy enum value set: "
+ allowed, 400);
}
}
public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) {
Optional<AgentRuntime> found = storage.get(key(region, id));
if (found.isEmpty()) {
@@ -269,22 +296,23 @@ public class BedrockAgentCoreControlService {
// ──────────────────────────── Tagging (Phase 4) ────────────────────────────
public Map<String, String> getTagsByArn(String region, String arn) {
return new HashMap<>(findByArn(region, arn).getTags());
return new HashMap<>(getAgentRuntimeByArn(region, arn).getTags());
}
public void tagByArn(String region, String arn, Map<String, String> tags) {
AgentRuntime runtime = findByArn(region, arn);
AgentRuntime runtime = getAgentRuntimeByArn(region, arn);
runtime.getTags().putAll(tags);
storage.put(key(region, runtime.getAgentRuntimeId()), runtime);
}
public void untagByArn(String region, String arn, List<String> keys) {
AgentRuntime runtime = findByArn(region, arn);
AgentRuntime runtime = getAgentRuntimeByArn(region, arn);
keys.forEach(runtime.getTags()::remove);
storage.put(key(region, runtime.getAgentRuntimeId()), runtime);
}
private AgentRuntime findByArn(String region, String arn) {
/** The runtime a runtime ARN names, at any version; ResourceNotFoundException when none does. */
public AgentRuntime getAgentRuntimeByArn(String region, String arn) {
String uuid = uuidFromArn(arn);
String prefix = keyPrefix(region);
return storage.scan(k -> k.startsWith(prefix)).stream()
@@ -341,8 +369,20 @@ public class BedrockAgentCoreControlService {
return findEndpoint(runtime, name);
}
/** UpdateAgentRuntimeEndpoint on the API: a null version or description is left as it is. */
public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, String region) {
return updateEndpoint(runtimeId, name, agentRuntimeVersion, description, false, region);
}
/**
* Updates an endpoint from arguments that are its whole declared configuration when
* {@code replaceOmitted} is true: a null description then clears the stored one, which the API
* call leaves alone. A null version keeps the endpoint on the version it serves either way, as
* UpdateAgentRuntimeEndpoint does.
*/
public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, boolean replaceOmitted, String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name);
if (agentRuntimeVersion != null) {
@@ -350,7 +390,7 @@ public class BedrockAgentCoreControlService {
endpoint.setTargetVersion(agentRuntimeVersion);
endpoint.setLiveVersion(agentRuntimeVersion);
}
if (description != null) {
if (description != null || replaceOmitted) {
endpoint.setDescription(description);
}
endpoint.setLastUpdatedAt(Instant.now());
@@ -402,6 +442,32 @@ public class BedrockAgentCoreControlService {
MAX_PAGE, "ValidationException");
}
/** An endpoint together with the runtime that holds it. */
public record EndpointLocation(AgentRuntime runtime, AgentRuntimeEndpoint endpoint) {
}
/**
* The endpoint an endpoint ARN ({@code agentEndpoint/<uuid>}) names, with its runtime, or empty
* when no runtime in the region holds it. Endpoints are addressed by runtime id and name on the
* API, so this is the only way back from the ARN CloudFormation keeps as the physical id.
*/
public Optional<EndpointLocation> findEndpointByArn(String region, String arn) {
String[] parts = arn == null ? new String[0] : arn.split(":");
if (parts.length < 6 || !parts[5].startsWith("agentEndpoint/")) {
return Optional.empty();
}
String uuid = parts[5].substring("agentEndpoint/".length());
String prefix = keyPrefix(region);
for (AgentRuntime runtime : storage.scan(k -> k.startsWith(prefix))) {
for (AgentRuntimeEndpoint endpoint : runtime.getEndpoints()) {
if (uuid.equals(endpoint.getUuid())) {
return Optional.of(new EndpointLocation(runtime, endpoint));
}
}
}
return Optional.empty();
}
private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) {
return runtime.getEndpoints().stream()
.filter(e -> e.getName().equals(name))
@@ -97,21 +97,32 @@ public class BedrockAgentCoreMemoryService {
"Memory not found: " + id, 404));
}
/** UpdateMemory on the API: a null field is left as it is, as on AWS. */
public Memory update(String id, String description, Integer eventExpiryDuration,
String memoryExecutionRoleArn, String region) {
return update(id, description, eventExpiryDuration, memoryExecutionRoleArn, false, region);
}
/**
* Updates a memory from arguments that are its whole declared configuration when
* {@code replaceOmitted} is true: a null description or execution role then clears the stored
* one, which the API call leaves alone.
*/
public Memory update(String id, String description, Integer eventExpiryDuration,
String memoryExecutionRoleArn, boolean replaceOmitted, String region) {
// Validate all inputs before mutating: get() returns the live stored object,
// so a throw after the first setter would leave a partially applied update.
if (eventExpiryDuration != null) {
validateExpiry(eventExpiryDuration);
}
Memory memory = get(id, region);
if (description != null) {
if (description != null || replaceOmitted) {
memory.setDescription(description);
}
if (eventExpiryDuration != null) {
memory.setEventExpiryDuration(eventExpiryDuration);
}
if (memoryExecutionRoleArn != null) {
if (memoryExecutionRoleArn != null || replaceOmitted) {
memory.setMemoryExecutionRoleArn(memoryExecutionRoleArn);
}
memory.setUpdatedAt(Instant.now());
@@ -158,22 +169,23 @@ public class BedrockAgentCoreMemoryService {
// ── Tagging ──
public Map<String, String> getTagsByArn(String region, String arn) {
return new HashMap<>(findByArn(region, arn).getTags());
return new HashMap<>(getByArn(region, arn).getTags());
}
public void tagByArn(String region, String arn, Map<String, String> tags) {
Memory memory = findByArn(region, arn);
Memory memory = getByArn(region, arn);
memory.getTags().putAll(tags);
storage.put(key(region, memory.getMemoryId()), memory);
}
public void untagByArn(String region, String arn, List<String> keys) {
Memory memory = findByArn(region, arn);
Memory memory = getByArn(region, arn);
keys.forEach(memory.getTags()::remove);
storage.put(key(region, memory.getMemoryId()), memory);
}
private Memory findByArn(String region, String arn) {
/** The memory a memory ARN names; ValidationException for any other ARN, ResourceNotFoundException when gone. */
public Memory getByArn(String region, String arn) {
String[] parts = arn == null ? new String[0] : arn.split(":");
if (parts.length < 6 || !parts[5].startsWith("memory/")) {
throw new AwsException("ValidationException", "Unsupported resource ARN: " + arn, 400);
@@ -0,0 +1,635 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService.EndpointLocation;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* CloudFormation provisioning for the Amazon Bedrock AgentCore control plane:
* {@code AWS::BedrockAgentCore::Runtime}, {@code AWS::BedrockAgentCore::RuntimeEndpoint} and
* {@code AWS::BedrockAgentCore::Memory}.
*
* <p>Physical ids and {@code Ref} follow each registry schema's {@code primaryIdentifier}: the
* runtime's {@code AgentRuntimeId}, the endpoint's {@code AgentRuntimeEndpointArn} and the
* memory's {@code MemoryArn}. The template reference prose says the runtime's {@code Ref} is its
* ARN, but the schema (and CDK's generated {@code RuntimeReference}) identify a runtime by id, and
* the schema is what CloudFormation resolves against. Every top-level read-only property each
* schema declares is published for {@code Fn::GetAtt}; the runtime's nested
* {@code WorkloadIdentityDetails} is published in the dotted form GetAtt addresses it by.
*
* <p>An update whose create-only properties are unchanged (the runtime's name; the endpoint's
* runtime id and name; the memory's name and encryption key) is applied in place through the
* service's update call and a tag diff, so the physical id survives as it does on AWS. The
* template is the whole declared configuration: a property it no longer carries is cleared on the
* entity, not left over from the previous update. What the in-place update changes is snapshotted
* first (see {@link #IN_PLACE_PRIOR_ATTR}) so a stack rollback, or this provision failing after
* the change, puts the entity back. Any create-only change creates the replacement and leaves the
* displaced entity to the {@link ReplacementCleanup} record, deleted once the stack update commits.
*
* <p>Template properties the emulated service has no model for are accepted and logged once at
* warn, by name, rather than failing the stack; the template is still valid CloudFormation.
*/
@ApplicationScoped
public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreCfnProvisioner.class);
private static final String RUNTIME = "AWS::BedrockAgentCore::Runtime";
private static final String RUNTIME_ENDPOINT = "AWS::BedrockAgentCore::RuntimeEndpoint";
private static final String MEMORY = "AWS::BedrockAgentCore::Memory";
/**
* Template properties the backing service does not store. The runtime's capacity provider,
* filesystems, lifecycle, platform version and request-header allowlist, and the memory's
* strategies, indexed keys, namespace keys and stream delivery have no representation in the
* emulated control plane; the endpoint model carries no tags.
*/
private static final Set<String> RUNTIME_NOT_STORED = Set.of("CapacityProviderConfiguration",
"FilesystemConfigurations", "LifecycleConfiguration", "PlatformVersion", "RequestHeaderConfiguration");
private static final Set<String> RUNTIME_ENDPOINT_NOT_STORED = Set.of("Tags");
private static final Set<String> MEMORY_NOT_STORED = Set.of("IndexedKeys", "MemoryStrategies",
"NamespaceKeys", "StreamDeliveryResources");
private static final Set<String> WARNED_NOT_STORED = ConcurrentHashMap.newKeySet();
/**
* The API requires a network configuration; the template does not. CloudFormation fills in the
* public mode AWS documents as the default
* (https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_NetworkConfiguration.html).
*/
private static final String DEFAULT_NETWORK_MODE = "PUBLIC";
/**
* What an in-place update changed on a reused entity, recorded before the change so a stack
* rollback can put it back: the runtime's configuration and tags, the endpoint's target version
* and description, the memory's mutable properties and tags. Internal, like the other
* {@code __Floci} attributes.
*/
static final String IN_PLACE_PRIOR_ATTR = "__FlociBedrockAgentCorePrior";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final BedrockAgentCoreControlService runtimeService;
private final BedrockAgentCoreMemoryService memoryService;
@Inject
public BedrockAgentCoreCfnProvisioner(BedrockAgentCoreControlService runtimeService,
BedrockAgentCoreMemoryService memoryService) {
this.runtimeService = runtimeService;
this.memoryService = memoryService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(RUNTIME, RUNTIME_ENDPOINT, MEMORY);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
switch (r.getResourceType()) {
case RUNTIME -> provisionRuntime(r, props, ctx);
case RUNTIME_ENDPOINT -> provisionRuntimeEndpoint(r, props, ctx);
case MEMORY -> provisionMemory(r, props, ctx);
default -> throw new AwsException("ValidationError",
"Unsupported resource type: " + r.getResourceType(), 400);
}
ReplacementCleanup.record(r, ctx, attributesBefore);
}
// ──────────────────────────── Runtime ────────────────────────────
private void provisionRuntime(StackResource r, JsonNode props, ProvisionContext ctx) {
String region = ctx.region();
String name = required(props, "AgentRuntimeName", ctx, RUNTIME);
String roleArn = required(props, "RoleArn", ctx, RUNTIME);
JsonNode artifact = apiShape(props, "AgentRuntimeArtifact", ctx);
if (artifact == null) {
throw new AwsException("ValidationError", RUNTIME + " requires AgentRuntimeArtifact", 400);
}
JsonNode network = apiShape(props, "NetworkConfiguration", ctx);
if (network == null) {
network = JsonNodeFactory.instance.objectNode().put("networkMode", DEFAULT_NETWORK_MODE);
}
String description = ctx.resolveOrDefault(props, "Description", null);
Map<String, String> environment = resolveStringMap(props, "EnvironmentVariables", ctx);
JsonNode authorizer = apiShape(props, "AuthorizerConfiguration", ctx);
// The template's ProtocolConfiguration is the bare protocol enum; the API wraps it.
String protocol = ctx.resolveOrDefault(props, "ProtocolConfiguration", null);
JsonNode protocolConfiguration = protocol == null ? null
: JsonNodeFactory.instance.objectNode().put("serverProtocol", protocol);
Map<String, String> tags = ctx.resolveTags(props, "Tags");
warnNotStored(RUNTIME, props, RUNTIME_NOT_STORED);
AgentRuntime prior = ctx.isUpdate() ? findRuntime(ctx.priorPhysicalId(), region) : null;
if (prior != null && name.equals(prior.getAgentRuntimeName())) {
// Every UpdateAgentRuntime publishes a new version, as on AWS, so an UpdateStack that
// left this runtime alone must not call it and bump the version for nothing.
boolean configurationChanged = !(Objects.equals(roleArn, prior.getRoleArn())
&& Objects.equals(description, prior.getDescription())
&& artifact.equals(prior.getAgentRuntimeArtifact())
&& network.equals(prior.getNetworkConfiguration())
&& Objects.equals(authorizer, prior.getAuthorizerConfiguration())
&& Objects.equals(protocolConfiguration, prior.getProtocolConfiguration())
&& environment.equals(prior.getEnvironmentVariables()));
String arn = runtimeService.arn(prior, String.valueOf(prior.getLatestVersion()), region);
Map<String, String> priorTags = runtimeService.getTagsByArn(region, arn);
if (configurationChanged || !priorTags.equals(tags)) {
ObjectNode snapshot = inPlacePrior(prior.getAgentRuntimeId(), region);
if (configurationChanged) {
ObjectNode configuration = snapshot.putObject("runtime");
configuration.put("roleArn", prior.getRoleArn());
configuration.put("description", prior.getDescription());
configuration.set("artifact", prior.getAgentRuntimeArtifact());
configuration.set("network", prior.getNetworkConfiguration());
configuration.set("authorizer", prior.getAuthorizerConfiguration());
configuration.set("protocol", prior.getProtocolConfiguration());
configuration.set("environment", MAPPER.valueToTree(prior.getEnvironmentVariables()));
}
snapshot.set("tags", MAPPER.valueToTree(priorTags));
writeInPlacePrior(r, snapshot);
}
JsonNode finalNetwork = network;
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
AgentRuntime runtime = configurationChanged
? runtimeService.updateAgentRuntime(prior.getAgentRuntimeId(), artifact, finalNetwork, roleArn,
description, environment, authorizer, protocolConfiguration, region)
: prior;
reconcileRuntimeTags(arn, tags, region);
publishRuntime(r, runtime, region);
});
} else {
AgentRuntime runtime = runtimeService.createAgentRuntime(name, artifact, network, roleArn, description,
environment, authorizer, protocolConfiguration, null, region);
publishRuntime(r, runtime, region);
CfnRollback.guarded(r, ctx, true,
() -> runtimeService.deleteAgentRuntime(runtime.getAgentRuntimeId(), null, region),
() -> undoInPlace(r), () -> {
if (!tags.isEmpty()) {
runtimeService.tagByArn(region, r.getAttributes().get("AgentRuntimeArn"), tags);
}
});
}
}
private void reconcileRuntimeTags(String arn, Map<String, String> desired, String region) {
List<String> stale = ProvisionContext.staleTagKeys(runtimeService.getTagsByArn(region, arn), desired);
if (!stale.isEmpty()) {
runtimeService.untagByArn(region, arn, stale);
}
if (!desired.isEmpty()) {
runtimeService.tagByArn(region, arn, desired);
}
}
private void publishRuntime(StackResource r, AgentRuntime runtime, String region) {
String version = String.valueOf(runtime.getLatestVersion());
r.setPhysicalId(runtime.getAgentRuntimeId());
r.getAttributes().put("AgentRuntimeArn", runtimeService.arn(runtime, version, region));
r.getAttributes().put("AgentRuntimeId", runtime.getAgentRuntimeId());
r.getAttributes().put("AgentRuntimeVersion", version);
r.getAttributes().put("Status", runtime.getStatus());
r.getAttributes().put("CreatedAt", runtime.getCreatedAt().toString());
r.getAttributes().put("LastUpdatedAt", runtime.getLastUpdatedAt().toString());
// The emulated runtime is READY from creation, so there is never a failure to report.
r.getAttributes().put("FailureReason", "");
r.getAttributes().put("WorkloadIdentityDetails.WorkloadIdentityArn", runtime.getWorkloadIdentityArn());
}
/** The runtime a prior physical id names, or null when it names none (gone, or a dispatcher stub). */
private AgentRuntime findRuntime(String agentRuntimeId, String region) {
try {
return runtimeService.getAgentRuntime(agentRuntimeId, region);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
// ──────────────────────────── RuntimeEndpoint ────────────────────────────
private void provisionRuntimeEndpoint(StackResource r, JsonNode props, ProvisionContext ctx) {
String region = ctx.region();
String runtimeId = required(props, "AgentRuntimeId", ctx, RUNTIME_ENDPOINT);
String name = required(props, "Name", ctx, RUNTIME_ENDPOINT);
String version = ctx.resolveOrDefault(props, "AgentRuntimeVersion", null);
String description = ctx.resolveOrDefault(props, "Description", null);
warnNotStored(RUNTIME_ENDPOINT, props, RUNTIME_ENDPOINT_NOT_STORED);
EndpointLocation prior = ctx.isUpdate()
? runtimeService.findEndpointByArn(region, ctx.priorPhysicalId()).orElse(null)
: null;
if (prior != null && runtimeId.equals(prior.runtime().getAgentRuntimeId())
&& name.equals(prior.endpoint().getName())) {
AgentRuntimeEndpoint existing = prior.endpoint();
// An omitted version leaves the endpoint on the version it serves, as UpdateAgentRuntimeEndpoint does.
boolean unchanged = (version == null || version.equals(existing.getTargetVersion()))
&& Objects.equals(description, existing.getDescription());
if (unchanged) {
publishRuntimeEndpoint(r, prior.runtime(), existing, region);
return;
}
ObjectNode snapshot = inPlacePrior(runtimeId, region);
ObjectNode endpointPrior = snapshot.putObject("endpoint");
endpointPrior.put("name", name);
endpointPrior.put("targetVersion", existing.getTargetVersion());
endpointPrior.put("description", existing.getDescription());
writeInPlacePrior(r, snapshot);
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r),
() -> publishRuntimeEndpoint(r, prior.runtime(),
runtimeService.updateEndpoint(runtimeId, name, version, description, true, region), region));
} else {
AgentRuntimeEndpoint endpoint = runtimeService.createEndpoint(runtimeId, name, version, description,
null, region);
r.setPhysicalId(runtimeService.endpointArn(endpoint, region));
CfnRollback.guarded(r, ctx, true, () -> runtimeService.deleteEndpoint(runtimeId, name, null, region),
() -> undoInPlace(r),
() -> publishRuntimeEndpoint(r, runtimeService.getAgentRuntime(runtimeId, region), endpoint, region));
}
}
private void publishRuntimeEndpoint(StackResource r, AgentRuntime runtime, AgentRuntimeEndpoint endpoint,
String region) {
String endpointArn = runtimeService.endpointArn(endpoint, region);
r.setPhysicalId(endpointArn);
r.getAttributes().put("AgentRuntimeEndpointArn", endpointArn);
r.getAttributes().put("AgentRuntimeArn", runtimeService.arn(runtime, endpoint.getTargetVersion(), region));
r.getAttributes().put("Id", endpoint.getUuid());
r.getAttributes().put("Status", endpoint.getStatus());
r.getAttributes().put("TargetVersion", endpoint.getTargetVersion());
r.getAttributes().put("LiveVersion", endpoint.getLiveVersion());
r.getAttributes().put("CreatedAt", endpoint.getCreatedAt().toString());
r.getAttributes().put("LastUpdatedAt", endpoint.getLastUpdatedAt().toString());
// The emulated endpoint is READY from creation, so there is never a failure to report.
r.getAttributes().put("FailureReason", "");
}
// ──────────────────────────── Memory ────────────────────────────
private void provisionMemory(StackResource r, JsonNode props, ProvisionContext ctx) {
String region = ctx.region();
String name = required(props, "Name", ctx, MEMORY);
Integer eventExpiryDuration = eventExpiryDuration(props, ctx);
String description = ctx.resolveOrDefault(props, "Description", null);
String encryptionKeyArn = ctx.resolveOrDefault(props, "EncryptionKeyArn", null);
String executionRoleArn = ctx.resolveOrDefault(props, "MemoryExecutionRoleArn", null);
Map<String, String> tags = ctx.resolveTags(props, "Tags");
warnNotStored(MEMORY, props, MEMORY_NOT_STORED);
Memory prior = ctx.isUpdate() ? findMemory(ctx.priorPhysicalId(), region) : null;
if (prior != null && name.equals(prior.getName())
&& Objects.equals(encryptionKeyArn, prior.getEncryptionKeyArn())) {
boolean configurationChanged = !(Objects.equals(description, prior.getDescription())
&& eventExpiryDuration.equals(prior.getEventExpiryDuration())
&& Objects.equals(executionRoleArn, prior.getMemoryExecutionRoleArn()));
String arn = memoryService.arn(prior, region);
Map<String, String> priorTags = memoryService.getTagsByArn(region, arn);
if (configurationChanged || !priorTags.equals(tags)) {
ObjectNode snapshot = inPlacePrior(prior.getMemoryId(), region);
if (configurationChanged) {
ObjectNode configuration = snapshot.putObject("memory");
configuration.put("description", prior.getDescription());
configuration.put("eventExpiryDuration", prior.getEventExpiryDuration());
configuration.put("memoryExecutionRoleArn", prior.getMemoryExecutionRoleArn());
}
snapshot.set("tags", MAPPER.valueToTree(priorTags));
writeInPlacePrior(r, snapshot);
}
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
Memory memory = configurationChanged
? memoryService.update(prior.getMemoryId(), description, eventExpiryDuration,
executionRoleArn, true, region)
: prior;
reconcileMemoryTags(arn, tags, region);
publishMemory(r, memory, region);
});
} else {
// CreateMemory stores the tags with the memory, so there is no step after it to undo.
publishMemory(r, memoryService.create(name, eventExpiryDuration, description, encryptionKeyArn,
executionRoleArn, tags, null, region), region);
}
}
private void reconcileMemoryTags(String arn, Map<String, String> desired, String region) {
List<String> stale = ProvisionContext.staleTagKeys(memoryService.getTagsByArn(region, arn), desired);
if (!stale.isEmpty()) {
memoryService.untagByArn(region, arn, stale);
}
if (!desired.isEmpty()) {
memoryService.tagByArn(region, arn, desired);
}
}
private void publishMemory(StackResource r, Memory memory, String region) {
String arn = memoryService.arn(memory, region);
r.setPhysicalId(arn);
r.getAttributes().put("MemoryArn", arn);
r.getAttributes().put("MemoryId", memory.getMemoryId());
r.getAttributes().put("Status", memory.getStatus());
r.getAttributes().put("CreatedAt", memory.getCreatedAt().toString());
r.getAttributes().put("UpdatedAt", memory.getUpdatedAt().toString());
// The emulated memory is ACTIVE from creation, so there is never a failure to report.
r.getAttributes().put("FailureReason", "");
}
/** The memory a prior physical id names, or null when it names none (gone, or a dispatcher stub). */
private Memory findMemory(String arn, String region) {
if (!arn.startsWith("arn:")) {
return null;
}
try {
return memoryService.getByArn(region, arn);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private static Integer eventExpiryDuration(JsonNode props, ProvisionContext ctx) {
String raw = required(props, "EventExpiryDuration", ctx, MEMORY);
try {
return Integer.valueOf(raw.trim());
} catch (NumberFormatException e) {
throw new AwsException("ValidationError",
MEMORY + " EventExpiryDuration must be an integer, got " + raw, 400);
}
}
// ──────────────────────────── Delete ────────────────────────────
@Override
public void delete(String resourceType, String physicalId, String region) {
if (physicalId == null || physicalId.isBlank()) {
return;
}
switch (resourceType) {
case RUNTIME -> CfnDeletes.safeDelete("AgentCore runtime", physicalId,
() -> runtimeService.deleteAgentRuntime(physicalId, null, region),
"ResourceNotFoundException");
case RUNTIME_ENDPOINT -> runtimeService.findEndpointByArn(region, physicalId).ifPresentOrElse(
location -> CfnDeletes.safeDelete("AgentCore runtime endpoint", physicalId,
() -> runtimeService.deleteEndpoint(location.runtime().getAgentRuntimeId(),
location.endpoint().getName(), null, region),
"ResourceNotFoundException"),
() -> LOG.debugv("AgentCore runtime endpoint already gone, treating as deleted: {0}",
physicalId));
case MEMORY -> {
// A dispatcher stub from before this provisioner existed is not an ARN and names no memory.
if (!physicalId.startsWith("arn:")) {
return;
}
CfnDeletes.safeDelete("AgentCore memory", physicalId,
() -> memoryService.delete(memoryService.getByArn(region, physicalId).getMemoryId(),
null, region),
"ResourceNotFoundException");
}
default -> throw new AwsException("ValidationError",
"Unsupported resource type: " + resourceType, 400);
}
}
// ──────────────────────────── Update lifecycle ────────────────────────────
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record: the displaced entity was never touched.
* A reused entity the update changed in place is put back from the snapshot taken before the
* change, which is spent only once the restore succeeded so a restore that throws is reported
* rather than claimed. Without either, the update changed nothing about the entity. A provision
* that fails mid-way restores its own snapshot before the failure propagates (see
* {@link #guarded}), because the engine discards the attempted resource, snapshot included.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return true;
}
String snapshot = resource.getAttributes().get(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(resource, snapshot);
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
}
return true;
}
/**
* Puts the entity back the way the snapshot recorded it, through the same service calls the
* update used, and republishes the resource's attributes from the entity as it now stands: a
* restored runtime is a new version, as it would be on AWS.
*/
private void restoreInPlace(StackResource resource, String snapshot) {
ObjectNode prior = readSnapshot(resource, snapshot);
String region = prior.path("region").asText();
String entityId = prior.path("entityId").asText();
switch (resource.getResourceType()) {
case RUNTIME -> {
AgentRuntime runtime = runtimeService.getAgentRuntime(entityId, region);
if (prior.has("runtime")) {
ObjectNode configuration = (ObjectNode) prior.get("runtime");
runtime = runtimeService.updateAgentRuntime(entityId, configuration.get("artifact"),
configuration.get("network"), text(configuration, "roleArn"),
text(configuration, "description"), stringMap(configuration.get("environment")),
node(configuration, "authorizer"), node(configuration, "protocol"), region);
}
if (prior.has("tags")) {
reconcileRuntimeTags(runtimeService.arn(runtime, String.valueOf(runtime.getLatestVersion()), region),
stringMap(prior.get("tags")), region);
}
publishRuntime(resource, runtime, region);
}
case RUNTIME_ENDPOINT -> {
ObjectNode endpointPrior = (ObjectNode) prior.get("endpoint");
AgentRuntimeEndpoint endpoint = runtimeService.updateEndpoint(entityId, text(endpointPrior, "name"),
text(endpointPrior, "targetVersion"), text(endpointPrior, "description"), true, region);
publishRuntimeEndpoint(resource, runtimeService.getAgentRuntime(entityId, region), endpoint, region);
}
case MEMORY -> {
Memory memory = memoryService.get(entityId, region);
if (prior.has("memory")) {
ObjectNode configuration = (ObjectNode) prior.get("memory");
memory = memoryService.update(entityId, text(configuration, "description"),
configuration.get("eventExpiryDuration").asInt(),
text(configuration, "memoryExecutionRoleArn"), true, region);
}
if (prior.has("tags")) {
reconcileMemoryTags(memoryService.arn(memory, region), stringMap(prior.get("tags")), region);
}
publishMemory(resource, memory, region);
}
default -> throw new IllegalStateException("No in-place restore for " + resource.getResourceType());
}
}
/**
* A fresh snapshot for this resource. Each provision changes one entity in one go, so the
* snapshot is written once, before the change, with the entity's state as it stands now.
*/
private static ObjectNode inPlacePrior(String entityId, String region) {
ObjectNode node = MAPPER.createObjectNode();
node.put("region", region);
node.put("entityId", entityId);
return node;
}
private static void writeInPlacePrior(StackResource r, ObjectNode node) {
r.getAttributes().put(IN_PLACE_PRIOR_ATTR, node.toString());
}
private static ObjectNode readSnapshot(StackResource r, String snapshot) {
try {
return (ObjectNode) MAPPER.readTree(snapshot);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable in-place snapshot on " + r.getLogicalId(), e);
}
}
/**
* The in-place undo handed to {@link CfnRollback#guarded}: puts a reused entity back from its
* snapshot and spends it, leaving it in place when the restore fails so the next rollback can
* retry.
*/
private void undoInPlace(StackResource r) {
String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(r, snapshot);
r.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
}
}
// ──────────────────────────── Helpers ────────────────────────────
private static String required(JsonNode props, String name, ProvisionContext ctx, String type) {
String value = ctx.resolveOptional(props, name);
if (value == null || value.isBlank()) {
throw new AwsException("ValidationError", type + " requires " + name, 400);
}
return value;
}
/**
* A resolved object property in the API's camelCase, or null when absent. A member whose
* {@code Fn::If} selects {@code AWS::NoValue} is omitted, as CloudFormation omits it, rather
* than resolved to an empty string.
*/
private static JsonNode apiShape(JsonNode props, String name, ProvisionContext ctx) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
}
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name));
return resolved == null || resolved.isNull() || !resolved.isObject() ? null : toApiShape(resolved);
}
/** Recursively renames the members of a resolved node to the API's camelCase, dropping nulls. */
private static JsonNode toApiShape(JsonNode node) {
if (node.isObject()) {
ObjectNode out = JsonNodeFactory.instance.objectNode();
node.fields().forEachRemaining(field -> {
if (!field.getValue().isNull()) {
out.set(decapitalize(field.getKey()), toApiShape(field.getValue()));
}
});
return out;
}
if (node.isArray()) {
ArrayNode out = JsonNodeFactory.instance.arrayNode();
node.forEach(item -> out.add(toApiShape(item)));
return out;
}
return node;
}
private static String decapitalize(String key) {
return key.isEmpty() ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
}
/** A {@code {key: value}} property with each value resolved, or an empty map when absent. */
private static Map<String, String> resolveStringMap(JsonNode props, String name, ProvisionContext ctx) {
Map<String, String> values = new LinkedHashMap<>();
if (props == null || !props.has(name)) {
return values;
}
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name));
if (resolved != null && resolved.isObject()) {
resolved.fields().forEachRemaining(field -> {
String value = ctx.engine().resolve(field.getValue());
values.put(field.getKey(), value == null ? "" : value);
});
}
return values;
}
/** A snapshot's string map member, as a mutable map. */
private static Map<String, String> stringMap(JsonNode node) {
Map<String, String> values = new LinkedHashMap<>();
if (node != null && node.isObject()) {
node.fields().forEachRemaining(field -> values.put(field.getKey(), field.getValue().asText()));
}
return values;
}
private static String text(ObjectNode node, String field) {
return node.hasNonNull(field) ? node.get(field).asText() : null;
}
private static JsonNode node(ObjectNode node, String field) {
return node.hasNonNull(field) ? node.get(field) : null;
}
/** Logs, once per property per type, a template property the emulated service cannot store. */
private static void warnNotStored(String type, JsonNode props, Set<String> notStored) {
if (props == null) {
return;
}
for (String name : notStored) {
if (props.has(name) && !props.get(name).isNull() && WARNED_NOT_STORED.add(type + "." + name)) {
LOG.warnv("{0} {1} is accepted but not stored: the emulated AgentCore control plane "
+ "has no model for it.", type, name);
}
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.jboss.logging.Logger;
/**
@@ -238,4 +239,61 @@ public final class CfnRollback {
return false;
}
}
/**
* Runs the steps that follow a create or change a reused entity in place. If one of them
* throws, what this provision did is undone before the failure propagates: a created entity is
* deleted again by {@code undoCreate}, a reused one is put back by {@code undoInPlace}, which
* restores the provisioner's snapshot and is a no-op when there is none. The engine only removes
* a failed create it can see, and on a failed update it restores the previous resource metadata
* and discards the attempted one, snapshot included, so the undo has to happen here.
*
* <p>A compensation that fails is reported, never hidden. A created entity carries
* {@link #ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback deletes it
* (and reports that failing) if the undo here could not, and during an update the entity is
* also listed in the cleanup record, which the engine carries onto the restored resource and
* runs before the next committed update or the stack delete; a reused entity keeps its snapshot
* and the reason lands in {@link #UPDATE_ROLLBACK_FAILURE_ATTR}, which the engine copies onto
* the committed resource so the rollback walker reports UPDATE_ROLLBACK_FAILED instead of
* claiming the prior state is live.
*/
public static void guarded(StackResource r, ProvisionContext ctx, boolean created, Runnable undoCreate,
Runnable undoInPlace, Runnable steps) {
if (created) {
r.getAttributes().put(ROLLBACK_OWNED_ATTR, "true");
}
try {
steps.run();
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
} catch (RuntimeException e) {
if (created) {
try {
undoCreate.run();
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
} catch (RuntimeException undo) {
e.addSuppressed(undo);
String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId()
+ " by a failed update: " + undo.getMessage();
LOG.warn(reason);
r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason);
if (ctx.isUpdate()) {
// The engine restores the previous resource and keeps only what the cleanup
// record carries, so the replacement is listed there for the next cleanup.
ReplacementCleanup.recordOrphan(r, r.getPhysicalId(), r.getResourceType(), ctx.region());
}
}
} else {
try {
undoInPlace.run();
} catch (RuntimeException undo) {
e.addSuppressed(undo);
String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId()
+ " after a failed update: " + undo.getMessage();
LOG.warn(reason);
r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason);
}
}
throw e;
}
}
}
@@ -411,7 +411,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("SubnetId", subnet.getSubnetId());
r.getAttributes().put("VpcId", subnet.getVpcId());
r.getAttributes().put("AvailabilityZone", subnet.getAvailabilityZone());
guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()), () -> {
CfnRollback.guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()),
() -> undoInPlace(r), () -> {
applyTags(r, reuse, subnet.getSubnetId(), reuse ? existing.getTags() : List.of(), props, ctx);
if (mapPublicIpOnLaunch != null) {
if (reuse && ctx.isUpdate() && existing.isMapPublicIpOnLaunch() != Boolean.parseBoolean(mapPublicIpOnLaunch)) {
@@ -425,61 +426,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Runs the steps that follow an EC2 create or change a reused entity in place. If one of them
* throws, what this provision did is undone before the failure propagates: a created entity is
* deleted again, a reused one is put back from its snapshot. The engine only removes a failed
* create it can see, and on a failed update it restores the previous resource metadata and
* discards the attempted one, snapshot included, so the undo has to happen here.
*
* <p>A compensation that fails is reported, never hidden. A created entity carries
* {@link CfnRollback#ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback
* deletes it (and reports that failing) if the undo here could not, and during an update the
* entity is also listed in the cleanup record, which the engine carries onto the restored
* resource and runs before the next committed update or the stack delete; a reused entity keeps its
* snapshot and the reason lands in {@link CfnRollback#UPDATE_ROLLBACK_FAILURE_ATTR}, which the
* engine copies onto the committed resource so the rollback walker reports
* UPDATE_ROLLBACK_FAILED instead of claiming the prior state is live.
* The in-place undo handed to {@link CfnRollback#guarded}: puts a reused entity back from its
* snapshot and spends it, leaving it in place when the restore fails so the next rollback can
* retry.
*/
private void guarded(StackResource r, ProvisionContext ctx, boolean created, Runnable undoCreate, Runnable steps) {
if (created) {
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
try {
steps.run();
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
} catch (RuntimeException e) {
if (created) {
try {
undoCreate.run();
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
} catch (RuntimeException undo) {
e.addSuppressed(undo);
String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId()
+ " by a failed update: " + undo.getMessage();
LOG.warn(reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
if (ctx.isUpdate()) {
// The engine restores the previous resource and keeps only what the cleanup
// record carries, so the replacement is listed there for the next cleanup.
ReplacementCleanup.recordOrphan(r, r.getPhysicalId(), r.getResourceType(), ctx.region());
}
}
} else {
String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
try {
restoreInPlace(r, snapshot);
r.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
} catch (RuntimeException undo) {
e.addSuppressed(undo);
String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId()
+ " after a failed update: " + undo.getMessage();
LOG.warn(reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
}
}
}
throw e;
private void undoInPlace(StackResource r) {
String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(r, snapshot);
r.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
}
}
@@ -488,7 +443,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
InternetGateway igw = existing != null ? existing : ec2Service.createInternetGateway(ctx.region());
r.setPhysicalId(igw.getInternetGatewayId());
r.getAttributes().put("InternetGatewayId", igw.getInternetGatewayId());
guarded(r, ctx, existing == null, () -> ec2Service.deleteInternetGateway(ctx.region(), igw.getInternetGatewayId()),
CfnRollback.guarded(r, ctx, existing == null,
() -> ec2Service.deleteInternetGateway(ctx.region(), igw.getInternetGatewayId()), () -> undoInPlace(r),
() -> applyTags(r, existing != null, igw.getInternetGatewayId(), existing != null ? existing.getTags() : List.of(), props, ctx));
}
@@ -501,7 +457,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
RouteTable rt = reuse ? existing : ec2Service.createRouteTable(ctx.region(), vpcId);
r.setPhysicalId(rt.getRouteTableId());
r.getAttributes().put("RouteTableId", rt.getRouteTableId());
guarded(r, ctx, !reuse, () -> ec2Service.deleteRouteTable(ctx.region(), rt.getRouteTableId()),
CfnRollback.guarded(r, ctx, !reuse, () -> ec2Service.deleteRouteTable(ctx.region(), rt.getRouteTableId()),
() -> undoInPlace(r),
() -> applyTags(r, reuse, rt.getRouteTableId(), reuse ? existing.getTags() : List.of(), props, ctx));
}
@@ -569,7 +526,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
target.put("egressOnlyInternetGatewayId", current.getEgressOnlyInternetGatewayId());
target.put("vpcPeeringConnectionId", current.getVpcPeeringConnectionId());
writeInPlacePrior(r, prior);
guarded(r, ctx, false, () -> { }, () -> {
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
if (egressOnlyInternetGatewayId != null) {
// ReplaceRoute has no egress-only target; re-creating the route is the same outcome.
ec2Service.deleteRoute(ctx.region(), routeTableId, destinationCidr, destinationIpv6Cidr, destinationPrefixListId);
@@ -611,7 +568,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
NatGateway nat = reuse ? existing
: ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, tagList(props, ctx));
if (reuse) {
guarded(r, ctx, false, () -> { }, () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx));
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx));
}
r.setPhysicalId(nat.getNatGatewayId());
r.getAttributes().put("NatGatewayId", nat.getNatGatewayId());
@@ -626,7 +583,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
r.setPhysicalId(addr.getPublicIp());
r.getAttributes().put("AllocationId", addr.getAllocationId());
r.getAttributes().put("PublicIp", addr.getPublicIp());
guarded(r, ctx, existing == null, () -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()),
CfnRollback.guarded(r, ctx, existing == null,
() -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()), () -> undoInPlace(r),
() -> applyTags(r, existing != null, addr.getAllocationId(), existing != null ? existing.getTags() : List.of(), props, ctx));
}
}