feat(cloudformation): CodeBuild/CodePipeline CFN provisioning (#2685)

* feat(cloudformation): provision CodePipeline pipelines and actions

New CodePipelineCfnProvisioner handles AWS::CodePipeline::Pipeline,
AWS::CodePipeline::CustomActionType, and AWS::CodePipeline::Webhook by
lowering the PascalCase CloudFormation properties into the camelCase
CodePipeline API shapes and delegating to the service, so stacks and the
API produce identical pipelines.

Ref resolves to the pipeline name (generated CloudFormation-style when
Name is omitted), Fn::GetAtt Version and webhook Url are populated, an
existing physical ID routes updates through UpdatePipeline instead of
recreating, DisableInboundStageTransitions is applied after creation,
and deletes tolerate already-removed resources.

(cherry picked from commit 8007d0b7e872d573217309fccd756c66a2d339a4)

* fix(cloudformation): bundle cfn-response into inline ZipFile Lambdas

AWS injects the cfn-response (Node.js) and cfnresponse (Python) modules
into functions created through CloudFormation's inline ZipFile property,
and custom-resource handlers across AWS Solutions templates rely on
that — Landing Zone Accelerator's installer stack fails its very first
Custom::CreateUUID resource with 'Cannot find module cfn-response'
without it.

The bundled modules follow the documented AWS implementations but pick
the transport and port from the ResponseURL instead of hardcoding
https:443, because Floci's custom-resource callback URL is plain http
on the emulator's port.

(cherry picked from commit 7028f5a85daba6ba9d83032dc940cebe45c0b348)

* refactor(cloudformation): extract inline ZipFile packaging

CloudFormationResourceProvisioner is a monolith being dismantled, so the
cfn-response bundling added there moves to its own InlineZipPackager,
ready to travel with the eventual Lambda provisioner extraction. No
behavior change.

(cherry picked from commit d0d4bff84bda9c143606a8922500515dbe5bc0c0)

* fix(cloudformation): keep CodePipeline action config keys verbatim

Action and rule configuration maps carry provider-defined string keys
(Owner, Repo, ProjectName, ...) that executors match exactly; the
PascalCase-to-camelCase property transform was rewriting them, so
CloudFormation-created pipelines could never run their GitHub source or
CodeBuild actions. Configuration subtrees now pass through untouched.

(cherry picked from commit 213e33d9f005ee4df6a66272a91f47ac67a3b7a3)

* feat(cloudformation): provision CodeBuild projects

AWS::CodeBuild::Project was falling through to the stub path, so
CloudFormation-created pipelines referenced build projects that did not
exist — Landing Zone Accelerator's installer pipeline failed its
Install stage with 'Project not found'. The new provisioner lowers the
PascalCase properties into the CodeBuild API shape (including the
irregular all-lowercase buildspec field), supports update-in-place, and
exposes Ref as the project name and Fn::GetAtt Arn.

(cherry picked from commit 7d616b87c7fa58693537dfe7d9d86cd63437ea75)

* fix(codepipeline): correct three CFN provisioning bugs in CodePipelineCfnProvisioner

- DisableInboundStageTransitions is a declarative list: a stage removed from it on
  update must be re-enabled, not left disabled after UPDATE_COMPLETE.
- CustomActionType has no update operation; a change to Category/Provider/Version
  is a replacement (create the new identity, delete the superseded one) rather than
  a silent physicalId swap with no corresponding service call.
- Webhook's RegisterWithThirdParty must be read from the resolved/lowercased node,
  not the raw unresolved props, so intrinsics (Ref, Fn::If) are honored.

* fix(codebuild): convert the JSON handler's Map entity instead of dropping it

CodeBuildJsonHandler.handle(...) returns Response.ok(Map.of(...)), never a
JsonNode, so the instanceof check in CodeBuildCfnProvisioner.handle always
missed and silently fell back to an empty ObjectNode -- forcing the guessed
ARN fallback even when the handler returned the real project ARN. Convert
non-JsonNode entities with ObjectMapper.valueToTree, and close the Response.

* fix(cloudformation): UTF-8 encode the injected Python cfn-response callback body

http.client encodes a str request body as latin-1, raising UnicodeEncodeError
for any response Reason/Data containing non-Latin-1 characters and failing
the callback before it's sent. Encode the JSON body to UTF-8 bytes first.

* docs(cloudformation): merge the duplicate Lambda resource-type row

Two Lambda rows in the supported-resource-types table gave inconsistent
descriptions (one had Version/Alias, the other the cfn-response detail).
Consolidate into a single row.

* fix(codepipeline): fix stage-transition and rename bugs found in re-review

- Only re-enable stage transitions this stack previously disabled (tracked via a
  new __FlociCodePipelineDisabledStages attribute); a stage disabled externally
  (a manual gate, a human) and never listed in DisableInboundStageTransitions is
  no longer touched by an unrelated update.
- Pipeline Name has no rename operation in CodePipeline; a template Name that
  differs from the tracked physical ID is now treated as a replacement (create
  under the new name, delete the old one) instead of calling UpdatePipeline
  against a pipeline that doesn't exist or belongs to someone else.
- Webhook Name rename now deletes the previously-owned webhook after PutWebhook
  upserts under the new name, instead of orphaning it.

* fix(codepipeline): handle legacy stage tracking and failed-replacement cleanup

- A resource stored before __FlociCodePipelineDisabledStages existed has no
  tracking record; fall back to reconciling every declared stage on its first
  post-upgrade update instead of skipping reconciliation and leaving a removed
  entry disabled forever.
- If stage-transition reconciliation fails after a rename's replacement (or a
  fresh create) already succeeded, best-effort delete the just-created pipeline
  before rethrowing. CloudFormation reverts this resource to its previous
  physicalId on a failed update, so without this the new pipeline is orphaned
  and a corrected retry hits PipelineNameInUseException.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 20:23:18 -04:00
1 parent 09d813d13f
commit ac94232910
10 files changed
+1207 -14

No files matched your search

@@ -2875,19 +2875,7 @@ public class CloudFormationResourceProvisioner {
private record LambdaCodeSpec(Map<String, Object> request, String identity) {}
private static String sourceToZipBase64(String source, String handler, String runtime) {
String module = handler.contains(".") ? handler.substring(0, handler.lastIndexOf('.')) : "index";
String ext = runtime.startsWith("python") ? ".py" : ".js";
try {
var baos = new ByteArrayOutputStream();
try (var zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry(module + ext));
zos.write(source.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
} catch (Exception e) {
throw new RuntimeException("Failed to create zip from ZipFile source", e);
}
return InlineZipPackager.sourceToZipBase64(source, handler, runtime);
}
private static String defaultHandlerZipBase64() {
@@ -0,0 +1,132 @@
package io.github.hectorvent.floci.services.cloudformation;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Builds the deployment package for a Lambda function declared with CloudFormation's
* inline {@code ZipFile} property.
*
* <p>Matches the real service's special-casing of that code path: AWS injects the
* {@code cfn-response} (Node.js) / {@code cfnresponse} (Python) module into ZipFile
* packages so custom-resource handlers can send their CloudFormation callbacks, and
* Solutions-style templates (e.g. Landing Zone Accelerator's installer) rely on it.
* Lives outside {@code CloudFormationResourceProvisioner} so the eventual Lambda
* provisioner extraction can take it along unchanged.</p>
*/
final class InlineZipPackager {
/**
* The cfn-response module for Node.js. Unlike AWS's canonical module this one honors
* the ResponseURL's protocol and port, because Floci's ResponseURL is plain http on
* the emulator's port.
*/
private static final String CFN_RESPONSE_JS = """
exports.SUCCESS = "SUCCESS";
exports.FAILED = "FAILED";
exports.send = function (event, context, responseStatus, responseData, physicalResourceId, noEcho) {
var responseBody = JSON.stringify({
Status: responseStatus,
Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName,
PhysicalResourceId: physicalResourceId || context.logStreamName,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
NoEcho: noEcho || false,
Data: responseData
});
console.log("Response body:\\n", responseBody);
var url = require("url");
var parsedUrl = url.parse(event.ResponseURL);
var isHttps = parsedUrl.protocol === "https:";
var transport = isHttps ? require("https") : require("http");
var options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port || (isHttps ? 443 : 80),
path: parsedUrl.path,
method: "PUT",
headers: { "content-type": "", "content-length": Buffer.byteLength(responseBody) }
};
var request = transport.request(options, function (response) {
console.log("Status code: " + response.statusCode);
context.done();
});
request.on("error", function (error) {
console.log("send(..) failed executing request(..): " + error);
context.done();
});
request.write(responseBody);
request.end();
};
""";
/** The Python counterpart AWS injects as {@code cfnresponse}. */
private static final String CFN_RESPONSE_PY = """
import http.client
import json
import urllib.parse
SUCCESS = "SUCCESS"
FAILED = "FAILED"
def send(event, context, responseStatus, responseData, physicalResourceId=None,
noEcho=False, reason=None):
response_url = event['ResponseURL']
response_body = json.dumps({
'Status': responseStatus,
'Reason': reason or "See the details in CloudWatch Log Stream: "
+ context.log_stream_name,
'PhysicalResourceId': physicalResourceId or context.log_stream_name,
'StackId': event['StackId'],
'RequestId': event['RequestId'],
'LogicalResourceId': event['LogicalResourceId'],
'NoEcho': noEcho,
'Data': responseData,
})
print("Response body:", response_body)
body_bytes = response_body.encode('utf-8')
parsed = urllib.parse.urlparse(response_url)
conn_class = http.client.HTTPSConnection if parsed.scheme == 'https' \\
else http.client.HTTPConnection
conn = conn_class(parsed.hostname, parsed.port)
path = parsed.path + ('?' + parsed.query if parsed.query else '')
conn.request('PUT', path, body=body_bytes,
headers={'content-type': '', 'content-length': str(len(body_bytes))})
response = conn.getresponse()
print("Status code:", response.status)
""";
private InlineZipPackager() {}
static String sourceToZipBase64(String source, String handler, String runtime) {
String module = handler.contains(".") ? handler.substring(0, handler.lastIndexOf('.')) : "index";
String ext = runtime.startsWith("python") ? ".py" : ".js";
try {
var baos = new ByteArrayOutputStream();
try (var zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry(module + ext));
zos.write(source.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
if (runtime.startsWith("nodejs")) {
zos.putNextEntry(new ZipEntry("node_modules/cfn-response/package.json"));
zos.write("{\"name\":\"cfn-response\",\"main\":\"cfn-response.js\"}"
.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("node_modules/cfn-response/cfn-response.js"));
zos.write(CFN_RESPONSE_JS.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
} else if (runtime.startsWith("python")) {
zos.putNextEntry(new ZipEntry("cfnresponse.py"));
zos.write(CFN_RESPONSE_PY.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
} catch (Exception e) {
throw new RuntimeException("Failed to create zip from ZipFile source", e);
}
}
}
@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Set;
/**
* CloudFormation provisioning for CodeBuild: {@code AWS::CodeBuild::Project}.
*
* <p>CloudFormation properties are PascalCase while the CodeBuild API is camelCase; the
* recursive first-letter-lowercase transform maps them, with one irregular field —
* {@code BuildSpec} is {@code buildspec} (all lowercase) on the wire.</p>
*/
@ApplicationScoped
public class CodeBuildCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CodeBuildCfnProvisioner.class);
private final CodeBuildJsonHandler codeBuildJsonHandler;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
@Inject
public CodeBuildCfnProvisioner(CodeBuildJsonHandler codeBuildJsonHandler,
RegionResolver regionResolver, ObjectMapper mapper) {
this.codeBuildJsonHandler = codeBuildJsonHandler;
this.regionResolver = regionResolver;
this.mapper = mapper;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::CodeBuild::Project");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
ObjectNode request = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
boolean update = r.getPhysicalId() != null && !r.getPhysicalId().isBlank();
String name = request.path("name").asText(null);
if (name == null || name.isBlank()) {
name = update ? r.getPhysicalId() : ctx.generatePhysicalName(r.getLogicalId(), 150, false);
request.put("name", name);
}
JsonNode response = handle(update ? "UpdateProject" : "CreateProject",
request, ctx.region(), ctx.accountId());
r.setPhysicalId(name);
r.getAttributes().put("Arn",
response.path("project").path("arn").asText(
"arn:aws:codebuild:" + ctx.region() + ":" + ctx.accountId() + ":project/" + name));
}
@Override
public void delete(String resourceType, String physicalId, String region) {
try {
handle("DeleteProject", mapper.createObjectNode().put("name", physicalId),
region, regionResolver.getAccountId());
} catch (AwsException e) {
LOG.debugv("CodeBuild CFN delete of {0} tolerated: {1}", physicalId, e.getMessage());
}
}
private JsonNode handle(String action, ObjectNode request, String region, String account) {
try {
jakarta.ws.rs.core.Response response =
codeBuildJsonHandler.handle(action, request, region, account);
try {
// The handler returns Response.ok(Map.of(...)) for every JSON action, never a
// JsonNode directly, so the entity must be converted rather than downcast.
Object entity = response.getEntity();
return entity instanceof JsonNode node ? node : mapper.valueToTree(entity);
} finally {
response.close();
}
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InternalFailure",
"CodeBuild " + action + " failed: " + e.getMessage(), 500);
}
}
private JsonNode lowerKeys(JsonNode node) {
if (node instanceof ObjectNode objectNode) {
ObjectNode result = mapper.createObjectNode();
objectNode.fields().forEachRemaining(entry -> {
String key = entry.getKey();
String lowered = "BuildSpec".equals(key)
? "buildspec"
: key.isEmpty() ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
result.set(lowered, lowerKeys(entry.getValue()));
});
return result;
}
if (node instanceof ArrayNode arrayNode) {
ArrayNode result = mapper.createArrayNode();
arrayNode.forEach(entry -> result.add(lowerKeys(entry)));
return result;
}
return node;
}
}
@@ -0,0 +1,275 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.codepipeline.CodePipelineService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Set;
/**
* CloudFormation provisioning for CodePipeline: {@code AWS::CodePipeline::Pipeline},
* {@code AWS::CodePipeline::CustomActionType}, and {@code AWS::CodePipeline::Webhook}.
*
* <p>CloudFormation properties are PascalCase while the CodePipeline API is camelCase;
* a recursive first-letter-lowercase transform is lossless for this resource schema, so
* the resolved properties become the API request directly.</p>
*/
@ApplicationScoped
public class CodePipelineCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CodePipelineCfnProvisioner.class);
private final CodePipelineService codePipelineService;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
@Inject
public CodePipelineCfnProvisioner(CodePipelineService codePipelineService,
RegionResolver regionResolver, ObjectMapper mapper) {
this.codePipelineService = codePipelineService;
this.regionResolver = regionResolver;
this.mapper = mapper;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::CodePipeline::Pipeline",
"AWS::CodePipeline::CustomActionType",
"AWS::CodePipeline::Webhook");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case "AWS::CodePipeline::Pipeline" -> provisionPipeline(r, props, ctx);
case "AWS::CodePipeline::CustomActionType" -> provisionCustomActionType(r, props, ctx);
case "AWS::CodePipeline::Webhook" -> provisionWebhook(r, props, ctx);
default -> throw new IllegalStateException(
"CodePipelineCfnProvisioner cannot handle " + r.getResourceType());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
String account = regionResolver.getAccountId();
try {
switch (resourceType) {
case "AWS::CodePipeline::Pipeline" -> codePipelineService.handle("DeletePipeline",
mapper.createObjectNode().put("name", physicalId), region, account);
case "AWS::CodePipeline::CustomActionType" -> {
String[] parts = physicalId.split("\\|");
codePipelineService.handle("DeleteCustomActionType", mapper.createObjectNode()
.put("category", parts[0])
.put("provider", parts.length > 2 ? parts[2] : "")
.put("version", parts.length > 3 ? parts[3] : "1"),
region, account);
}
case "AWS::CodePipeline::Webhook" -> codePipelineService.handle("DeleteWebhook",
mapper.createObjectNode().put("name", physicalId), region, account);
default -> { }
}
} catch (AwsException e) {
LOG.debugv("CodePipeline CFN delete of {0} {1} tolerated: {2}",
resourceType, physicalId, e.getMessage());
}
}
private static final String DISABLED_STAGES_ATTR = "__FlociCodePipelineDisabledStages";
private void provisionPipeline(StackResource r, JsonNode props, ProvisionContext ctx) {
ObjectNode declaration = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
JsonNode transitions = declaration.remove("disableInboundStageTransitions");
JsonNode tags = declaration.remove("tags");
declaration.remove("restartExecutionOnUpdate");
String previousPhysicalId = r.getPhysicalId();
boolean update = previousPhysicalId != null && !previousPhysicalId.isBlank();
String explicitName = declaration.path("name").asText(null);
// Name is part of a pipeline's identity -- CodePipeline has no rename operation, so a
// template Name that differs from the tracked physical ID is a replacement, not an
// in-place update (UpdatePipeline would otherwise target/overwrite the wrong pipeline).
boolean rename = update && explicitName != null && !explicitName.isBlank()
&& !explicitName.equals(previousPhysicalId);
boolean create = !update || rename;
String name = explicitName != null && !explicitName.isBlank()
? explicitName
: (update ? previousPhysicalId : ctx.generatePhysicalName(r.getLogicalId(), 100, false));
if (explicitName == null || explicitName.isBlank()) {
declaration.put("name", name);
}
ObjectNode request = mapper.createObjectNode();
request.set("pipeline", declaration);
JsonNode response;
if (create) {
if (tags != null && tags.isArray() && !tags.isEmpty()) {
request.set("tags", tags);
}
response = codePipelineService.handle("CreatePipeline", request, ctx.region(), ctx.accountId());
} else {
response = codePipelineService.handle("UpdatePipeline", request, ctx.region(), ctx.accountId());
}
java.util.Set<String> desiredDisabledStages = new java.util.LinkedHashSet<>();
if (transitions != null && transitions.isArray()) {
for (JsonNode transition : transitions) {
desiredDisabledStages.add(transition.path("stageName").asText());
}
}
try {
// DisableInboundStageTransitions is declarative, but only for the stages CloudFormation
// itself disabled: a stage disabled externally (e.g. a manual gate) and never listed here
// must be left alone. Re-enable only stages this resource previously disabled and has now
// dropped from the list, tracked via DISABLED_STAGES_ATTR across deployments.
if (!create) {
String previouslyManaged = r.getAttributes().get(DISABLED_STAGES_ATTR);
Iterable<String> candidateStages;
if (previouslyManaged != null) {
candidateStages = previouslyManaged.isBlank()
? java.util.List.of() : java.util.Arrays.asList(previouslyManaged.split(","));
} else {
// A resource stored before DISABLED_STAGES_ATTR existed has no record of what it
// previously disabled. Fall back to reconciling every declared stage rather than
// skipping reconciliation outright, which would leave a removed entry disabled
// forever after this one legacy update.
java.util.List<String> declaredStages = new java.util.ArrayList<>();
if (declaration.path("stages").isArray()) {
for (JsonNode stage : declaration.path("stages")) {
declaredStages.add(stage.path("name").asText());
}
}
candidateStages = declaredStages;
}
for (String stageName : candidateStages) {
if (!desiredDisabledStages.contains(stageName)) {
codePipelineService.handle("EnableStageTransition", mapper.createObjectNode()
.put("pipelineName", name)
.put("stageName", stageName)
.put("transitionType", "Inbound"),
ctx.region(), ctx.accountId());
}
}
}
for (String stageName : desiredDisabledStages) {
JsonNode transition = null;
for (JsonNode candidate : transitions) {
if (stageName.equals(candidate.path("stageName").asText())) {
transition = candidate;
break;
}
}
codePipelineService.handle("DisableStageTransition", mapper.createObjectNode()
.put("pipelineName", name)
.put("stageName", stageName)
.put("transitionType", "Inbound")
.put("reason", transition.path("reason").asText("Disabled by CloudFormation")),
ctx.region(), ctx.accountId());
}
} catch (RuntimeException e) {
if (create) {
// The pipeline was just created (fresh, or as a rename's replacement) and stage
// reconciliation then failed. CloudFormation reverts this resource to its previous
// physicalId on a failed update, so the half-provisioned pipeline must be torn down
// now, or a corrected retry hits PipelineNameInUseException on the same name.
try {
codePipelineService.handle("DeletePipeline",
mapper.createObjectNode().put("name", name), ctx.region(), ctx.accountId());
} catch (RuntimeException cleanupFailure) {
e.addSuppressed(cleanupFailure);
}
}
throw e;
}
r.getAttributes().put(DISABLED_STAGES_ATTR, String.join(",", desiredDisabledStages));
if (rename) {
delete("AWS::CodePipeline::Pipeline", previousPhysicalId, ctx.region());
}
r.setPhysicalId(name);
r.getAttributes().put("Version",
String.valueOf(response.path("pipeline").path("version").asInt(1)));
}
private void provisionCustomActionType(StackResource r, JsonNode props, ProvisionContext ctx) {
ObjectNode request = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
request.remove("tags");
String physicalId = request.path("category").asText() + "|Custom|"
+ request.path("provider").asText() + "|" + request.path("version").asText("1");
String previousPhysicalId = r.getPhysicalId();
// Category/Provider/Version are this resource's identity — CodePipeline has no update
// operation for a custom action type, so a change to any of them is a replacement:
// create the new identity, then best-effort delete the old one it superseded.
if (previousPhysicalId == null || previousPhysicalId.isBlank()
|| !previousPhysicalId.equals(physicalId)) {
codePipelineService.handle("CreateCustomActionType", request, ctx.region(), ctx.accountId());
if (previousPhysicalId != null && !previousPhysicalId.isBlank()) {
delete("AWS::CodePipeline::CustomActionType", previousPhysicalId, ctx.region());
}
}
r.setPhysicalId(physicalId);
}
private void provisionWebhook(StackResource r, JsonNode props, ProvisionContext ctx) {
ObjectNode webhook = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
JsonNode registerNode = webhook.remove("registerWithThirdParty");
boolean register = registerNode != null && registerNode.asBoolean(false);
String previousPhysicalId = r.getPhysicalId();
boolean update = previousPhysicalId != null && !previousPhysicalId.isBlank();
String name = webhook.path("name").asText(null);
boolean rename = update && name != null && !name.isBlank() && !name.equals(previousPhysicalId);
if (name == null || name.isBlank()) {
name = update ? previousPhysicalId : ctx.generatePhysicalName(r.getLogicalId(), 100, false);
webhook.put("name", name);
}
JsonNode response = codePipelineService.handle("PutWebhook",
mapper.createObjectNode().set("webhook", webhook), ctx.region(), ctx.accountId());
if (register) {
codePipelineService.handle("RegisterWebhookWithThirdParty",
mapper.createObjectNode().put("webhookName", name), ctx.region(), ctx.accountId());
}
// Name is this resource's identity; PutWebhook upserts under the new name unconditionally,
// so a rename must also clean up the webhook the stack previously owned or it's orphaned.
if (rename) {
delete("AWS::CodePipeline::Webhook", previousPhysicalId, ctx.region());
}
r.setPhysicalId(name);
r.getAttributes().put("Url", response.path("webhook").path("url").asText(""));
}
/**
* Recursively lowercases the first letter of every object key — except inside
* {@code Configuration} maps, whose keys are opaque provider-defined strings
* ({@code Owner}, {@code Repo}, {@code ProjectName}, ...) that the action executors
* match verbatim.
*/
private JsonNode lowerKeys(JsonNode node) {
if (node instanceof ObjectNode objectNode) {
ObjectNode result = mapper.createObjectNode();
objectNode.fields().forEachRemaining(entry -> {
String key = entry.getKey();
if ("Configuration".equals(key)) {
result.set("configuration", entry.getValue().deepCopy());
return;
}
String lowered = key.isEmpty()
? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
result.set(lowered, lowerKeys(entry.getValue()));
});
return result;
}
if (node instanceof ArrayNode arrayNode) {
ArrayNode result = mapper.createArrayNode();
arrayNode.forEach(entry -> result.add(lowerKeys(entry)));
return result;
}
return node;
}
}