feat: add Fn::ImportValue cross-stack reference resolution for CloudFormation (#669)

Implement cross-stack export/import support so CDK multi-stack deployments
resolve Fn::ImportValue tokens to actual values instead of passing them
through as literal strings.

Changes:
- Track exports from stack Outputs with Export.Name declarations
- Maintain a global per-region export registry in CloudFormationService
- Resolve Fn::ImportValue in CloudFormationTemplateEngine via the registry
- Add ListExports API action with AWS-compatible XML response
- Include ExportName in DescribeStacks output XML
- Validate duplicate export names across stacks (AWS-compatible error)
- Fail stack creation when Fn::ImportValue references a missing export
- Clean up exports on stack delete and update
- Route ListExports through AwsQueryController

Tests:
- Cross-stack Fn::ImportValue with Fn::Join
- Dynamic export names via Fn::Sub
- Export rename on stack update
- Duplicate export name rejection
- Missing import value failure
This commit is contained in:
Chris Wright authored and GitHub committed 2026-04-30 21:27:53 -05:00
1 parent 4bb4f24fcd
commit b15daf51ed
6 files changed
+556 -28

No files matched your search

@@ -265,7 +265,7 @@ public class AwsQueryController {
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
"CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks",
"ListStacks", "GetTemplate", "ValidateTemplate",
"ListStacks", "ListExports", "GetTemplate", "ValidateTemplate",
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
"SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet"
@@ -55,6 +55,7 @@ public class CloudFormationQueryHandler {
case "GetTemplate" -> getTemplate(params, region);
case "ValidateTemplate" -> validateTemplate(params);
case "ListStacks" -> listStacks(params, region);
case "ListExports" -> listExports(params, region);
case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build();
case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build();
case "DescribeStackResource" -> describeStackResource(params, region);
@@ -428,6 +429,27 @@ public class CloudFormationQueryHandler {
return Response.ok(xml.build()).type("text/xml").build();
}
// ── ListExports ─────────────────────────────────────────────────────────
private Response listExports(MultivaluedMap<String, String> params, String region) {
var exportEntries = cfnService.listExports(region);
XmlBuilder xml = new XmlBuilder()
.start("ListExportsResponse", CF_NS)
.start("ListExportsResult")
.start("Exports");
for (var entry : exportEntries.values()) {
xml.start("member")
.elem("ExportingStackId", entry.exportingStackId())
.elem("Name", entry.name())
.elem("Value", entry.value())
.end("member");
}
xml.end("Exports").end("ListExportsResult")
.raw(AwsQueryResponse.responseMetadata())
.end("ListExportsResponse");
return Response.ok(xml.build()).type("text/xml").build();
}
// ── Helpers ───────────────────────────────────────────────────────────────
private String stackToXml(Stack s) {
@@ -448,11 +470,16 @@ public class CloudFormationQueryHandler {
}
xml.end("Capabilities");
xml.start("Outputs");
s.getOutputs().forEach((k, v) ->
xml.start("member")
.elem("OutputKey", k)
.elem("OutputValue", v)
.end("member"));
s.getOutputs().forEach((k, v) -> {
xml.start("member")
.elem("OutputKey", k)
.elem("OutputValue", v);
String exportName = s.getOutputExportNames().get(k);
if (exportName != null) {
xml.elem("ExportName", exportName);
}
xml.end("member");
});
xml.end("Outputs");
xml.start("Tags");
s.getTags().forEach((k, v) ->
@@ -32,6 +32,8 @@ public class CloudFormationService {
private static final Logger LOG = Logger.getLogger(CloudFormationService.class);
private final ConcurrentHashMap<String, Stack> stacks = new ConcurrentHashMap<>();
// Global exports registry: region:exportName -> exportValue
private final ConcurrentHashMap<String, String> exports = new ConcurrentHashMap<>();
private final ExecutorService executor = Executors.newCachedThreadPool();
private final CloudFormationResourceProvisioner provisioner;
@@ -191,8 +193,63 @@ public class CloudFormationService {
.toList();
}
// ── ListExports ─────────────────────────────────────────────────────────
public Map<String, ExportEntry> listExports(String region) {
Map<String, ExportEntry> result = new LinkedHashMap<>();
for (Stack stack : stacks.values()) {
if (!region.equals(stack.getRegion())) {
continue;
}
for (var entry : stack.getExports().entrySet()) {
result.put(entry.getKey(), new ExportEntry(entry.getKey(), entry.getValue(), stack.getStackId()));
}
}
return result;
}
public record ExportEntry(String name, String value, String exportingStackId) {}
// ── Private ───────────────────────────────────────────────────────────────
private void removeStackExports(Stack stack, String region) {
for (String exportName : stack.getExports().keySet()) {
exports.remove(exportKey(region, exportName));
}
}
private String exportKey(String region, String exportName) {
return region + ":" + exportName;
}
private void validateExportNameAvailable(String region, String exportName,
Map<String, String> oldExports,
Map<String, String> newExports) {
if (newExports.containsKey(exportName)) {
throw new AwsException("ValidationError",
"Export with name " + exportName + " is already defined by this stack", 400);
}
if (!oldExports.containsKey(exportName) && exports.containsKey(exportKey(region, exportName))) {
throw new AwsException("ValidationError",
"Export with name " + exportName + " is already exported by another stack", 400);
}
}
private Map<String, String> resolveDefaultParameters(JsonNode template, Map<String, String> callerParams) {
Map<String, String> resolved = new HashMap<>(callerParams != null ? callerParams : Map.of());
JsonNode paramDefs = template.path("Parameters");
if (paramDefs.isObject()) {
paramDefs.fields().forEachRemaining(e -> {
String paramName = e.getKey();
JsonNode paramDef = e.getValue();
if (!resolved.containsKey(paramName) && paramDef.has("Default")) {
resolved.put(paramName, paramDef.path("Default").asText());
}
});
}
return resolved;
}
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
boolean isCreate, String region) {
try {
@@ -232,7 +289,8 @@ public class CloudFormationService {
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
config.defaultAccountId(), region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper);
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(exportKey(region, name)));
StackResource resource = stack.getResources().get(logicalId);
if (resource == null) {
@@ -255,21 +313,48 @@ public class CloudFormationService {
}
}
// Resolve outputs
stack.getOutputs().clear();
CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine(
config.defaultAccountId(), region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper);
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(exportKey(region, name)));
// Resolve outputs before mutating stack/global export state, so failed updates do not
// leave stale or partially registered exports behind.
Map<String, String> oldExports = new LinkedHashMap<>(stack.getExports());
Map<String, String> newOutputs = new LinkedHashMap<>();
Map<String, String> newExports = new LinkedHashMap<>();
Map<String, String> newOutputExportNames = new LinkedHashMap<>();
JsonNode outputs = template.path("Outputs");
if (outputs.isObject()) {
outputs.fields().forEachRemaining(e -> {
JsonNode outputDef = e.getValue();
String value = finalEngine.resolve(outputDef.path("Value"));
stack.getOutputs().put(e.getKey(), value);
newOutputs.put(e.getKey(), value);
// Register exports
JsonNode exportNode = outputDef.path("Export").path("Name");
if (!exportNode.isMissingNode()) {
String exportName = finalEngine.resolve(exportNode);
validateExportNameAvailable(region, exportName, oldExports, newExports);
newExports.put(exportName, value);
newOutputExportNames.put(e.getKey(), exportName);
}
});
}
removeStackExports(stack, region);
stack.getOutputs().clear();
stack.getOutputs().putAll(newOutputs);
stack.getExports().clear();
stack.getExports().putAll(newExports);
stack.getOutputExportNames().clear();
stack.getOutputExportNames().putAll(newOutputExportNames);
newExports.forEach((exportName, value) -> {
exports.put(exportKey(region, exportName), value);
LOG.infov("Registered export {0} = {1} from stack {2}",
exportName, value, stack.getStackName());
});
String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE";
stack.setStatus(completeStatus);
stack.setLastUpdatedTime(Instant.now());
@@ -306,6 +391,7 @@ public class CloudFormationService {
stack.setStatus("DELETE_COMPLETE");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_COMPLETE", null);
removeStackExports(stack, region);
stacks.remove(key(stack.getStackName(), region));
LOG.infov("Stack {0} deleted", stack.getStackName());
@@ -316,21 +402,6 @@ public class CloudFormationService {
}
}
private Map<String, String> resolveDefaultParameters(JsonNode template, Map<String, String> callerParams) {
Map<String, String> resolved = new HashMap<>(callerParams != null ? callerParams : Map.of());
JsonNode paramDefs = template.path("Parameters");
if (paramDefs.isObject()) {
paramDefs.fields().forEachRemaining(e -> {
String paramName = e.getKey();
JsonNode paramDef = e.getValue();
if (!resolved.containsKey(paramName) && paramDef.has("Default")) {
resolved.put(paramName, paramDef.path("Default").asText());
}
});
}
return resolved;
}
private Map<String, Boolean> resolveConditions(JsonNode template, Map<String, String> params,
Stack stack, String region) {
Map<String, Boolean> conditions = new HashMap<>();
@@ -3,12 +3,14 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.jboss.logging.Logger;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
/**
* Resolves CloudFormation intrinsic functions and pseudo-parameters in template nodes.
@@ -29,6 +31,7 @@ public class CloudFormationTemplateEngine {
private final Map<String, Boolean> conditions;
private final Map<String, JsonNode> mappings;
private final ObjectMapper objectMapper;
private final Function<String, String> importValueResolver;
CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId,
Map<String, String> parameters,
@@ -36,7 +39,8 @@ public class CloudFormationTemplateEngine {
Map<String, Map<String, String>> resourceAttributes,
Map<String, Boolean> conditions,
Map<String, JsonNode> mappings,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
Function<String, String> importValueResolver) {
this.accountId = accountId;
this.region = region;
this.stackName = stackName;
@@ -47,6 +51,7 @@ public class CloudFormationTemplateEngine {
this.conditions = conditions;
this.mappings = mappings;
this.objectMapper = objectMapper;
this.importValueResolver = importValueResolver;
}
public String resolve(JsonNode node) {
@@ -88,7 +93,7 @@ public class CloudFormationTemplateEngine {
return resolveGetAtt(node.get("Fn::GetAtt"));
}
if (node.has("Fn::ImportValue")) {
return resolve(node.get("Fn::ImportValue"));
return resolveImportValue(node.get("Fn::ImportValue"));
}
if (node.has("Fn::FindInMap")) {
return resolveFindInMap(node.get("Fn::FindInMap"));
@@ -271,4 +276,16 @@ public class CloudFormationTemplateEngine {
}
return "";
}
private String resolveImportValue(JsonNode node) {
String exportName = resolve(node);
if (importValueResolver != null) {
String value = importValueResolver.apply(exportName);
if (value != null) {
return value;
}
}
LOG.warnv("Unresolved Fn::ImportValue: {0}", exportName);
throw new AwsException("ValidationError", "No export named " + exportName + " found", 400);
}
}
@@ -15,6 +15,9 @@ public class Stack {
private List<String> capabilities = new ArrayList<>();
private Map<String, String> parameters = new LinkedHashMap<>();
private Map<String, String> outputs = new LinkedHashMap<>();
private Map<String, String> exports = new LinkedHashMap<>();
// Maps output key to its export name (when Export.Name is defined on an output)
private Map<String, String> outputExportNames = new LinkedHashMap<>();
private Map<String, StackResource> resources = new LinkedHashMap<>();
private List<StackEvent> events = new ArrayList<>();
private Map<String, ChangeSet> changeSets = new LinkedHashMap<>();
@@ -42,6 +45,10 @@ public class Stack {
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
public Map<String, String> getOutputs() { return outputs; }
public void setOutputs(Map<String, String> outputs) { this.outputs = outputs; }
public Map<String, String> getExports() { return exports; }
public void setExports(Map<String, String> exports) { this.exports = exports; }
public Map<String, String> getOutputExportNames() { return outputExportNames; }
public void setOutputExportNames(Map<String, String> outputExportNames) { this.outputExportNames = outputExportNames; }
public Map<String, StackResource> getResources() { return resources; }
public void setResources(Map<String, StackResource> resources) { this.resources = resources; }
public List<StackEvent> getEvents() { return events; }