Repository navigation
Conversation
Add `UserData.forWindowsEc2LaunchV2()`, which renders user data in the EC2Launch v2 YAML format. Commands added with `addCommands()` and the other `add*Command()` methods form a single PowerShell `executeScript` input, and other EC2Launch v2 tasks can be added with `addTask()` using the `Ec2LaunchV2Task` factory methods, or `Ec2LaunchV2Task.custom()` for tasks without one. There is no factory method for the `writeFile` task: although it is documented for user data, EC2Launch v2 2.5.2 does not load user data that contains it. closes aws#36781 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Tick the box to add this pull request to the merge queue (same as
|
|
|
||||||||||||||
|
|
||||||||||||||
|
Automated review A maintainer will still review this — treat the notes below as a starting point. 📌 Commit This PR adds 🔴 2 blocking · 🟡 12 recommended · ⚪ 2 optional Files with findings (4)Generated automatically. React 👍 or 👎 to tell us whether this review helped, so we can improve these reviews. |
There was a problem hiding this comment.
See the review summary comment for the overview; the notes below are inline.
| const content = this.onExitLines.length === 0 | ||
| ? this.lines | ||
| : [ | ||
| '$success = $true', | ||
| 'try {', | ||
| ...this.lines, | ||
| '} catch {', | ||
| '$success = $false', | ||
| 'throw', | ||
| '} finally {', | ||
| ...this.onExitLines, | ||
| '}', | ||
| ]; | ||
| return renderEc2LaunchV2Script(this.options, Ec2LaunchV2ScriptType.POWERSHELL, content.join('\n')); |
There was a problem hiding this comment.
🔴 Blocking — The on-exit wrapper in renderCommandScript() sets $success = $true and only clears it in catch. A PowerShell exit is not an exception, so catch is skipped, but finally still runs with $success still $true. As a result, addSignalOnExitCommand() sends cfn-signal --success true when the script calls exit 1 or any other failing exit N, so a CreationPolicy passes on an instance whose bootstrap failed. It sends the same success signal on exit 3010, which the EC2Launch v2 settings describe as the only supported way for a script to reboot and run again. A method that reports success for a script that exited with failure is not what users expect (AGENTS.md#your-role). The README only mentions the reboot case.
Suggested change: Run the on-exit commands only when the script finished normally or threw, not on an explicit exit:
const content = this.onExitLines.length === 0
? this.lines
: [
'$success = $true',
'$finished = $false',
'try {',
...this.lines,
'$finished = $true',
'} catch {',
'$success = $false',
'$finished = $true',
'throw',
'} finally {',
'if ($finished) {',
...this.onExitLines,
'}',
'}',
];With this change, exit 3010 sends no signal and the run after the reboot sends it. exit 1 also sends no signal, so the stack fails on the CreationPolicy timeout, as with forWindows(). Update the README migration bullet and the unit tests that pin the rendered wrapper to match.
There was a problem hiding this comment.
Fixed in 2f55e31 as suggested: a $finished flag means on-exit commands (including cfn-signal) only run when the commands complete or throw. After exit 1 no signal is sent, so the CreationPolicy times out as with forWindows(). After exit 3010 the signal is sent by the run after the reboot. The unit tests pin the new wrapper, and the README migration bullet describes this behaviour.
| /** | ||
| * Render an EC2Launch v2 user data document | ||
| * | ||
| * Uses YAML 1.1 rules, so strings such as `yes` or `on` are quoted, and | ||
| * literal block scalars for multi-line strings, so scripts stay readable and | ||
| * values substituted into them by CloudFormation need no escaping. | ||
| */ | ||
| function renderEc2LaunchV2Yaml(value: any): string { | ||
| const doc = new YAML.Document({ version: '1.1' }); | ||
| doc.contents = YAML.createNode(removeUndefined(value)) as any; | ||
| useLiteralBlocks(doc.contents); | ||
| return doc.toString(); | ||
| } | ||
|
|
||
| function removeUndefined(value: any): any { | ||
| if (Array.isArray(value)) { | ||
| return value.map(removeUndefined); | ||
| } | ||
| if (value !== null && typeof value === 'object') { | ||
| return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => [k, removeUndefined(v)])); | ||
| } | ||
| return value; | ||
| } | ||
|
|
||
| function useLiteralBlocks(node: any) { | ||
| if (node?.items) { | ||
| // Maps contain pairs, sequences contain nodes | ||
| node.items.forEach((item: any) => useLiteralBlocks(item?.value !== undefined && item?.key !== undefined ? item.value : item)); | ||
| } else if (typeof node?.value === 'string' && node.value.includes('\n')) { | ||
| node.type = 'BLOCK_LITERAL'; | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — useLiteralBlocks picks the YAML scalar style from the token placeholder text, not from the value CloudFormation substitutes. It only uses a |- block when the placeholder already contains \n, so single-line content holding a token is emitted as a plain scalar. The token test expects exactly this: content: Write-Host + {Ref: AWS::Region}. If a parameter or import resolves to text containing : , #, or a leading quote or [, the YAML becomes invalid or is silently cut off. A common pattern like addCommands(Fn.sub(fs.readFileSync('script.ps1', 'utf8'), {...})) deploys multi-line text at column 0, which breaks parsing even inside a literal block. So the docstring's "need no escaping" claim is too broad (AGENTS.md#token-safety).
Suggested change: Render any string that contains a newline or an unresolved token as a literal block, which is safe for any single-line substituted value:
} else if (typeof node?.value === 'string' && (node.value.includes('\n') || Token.isUnresolved(node.value))) {
node.type = 'BLOCK_LITERAL';
}Then update the 'keeps tokens in commands intact' test to expect the |- form. Also narrow the docstring and README to say that values substituted by CloudFormation must be single-line, since multi-line values from Fn.sub/Fn.join cannot be indented correctly inside YAML.
There was a problem hiding this comment.
Fixed in 2f55e31: any string containing an unresolved token is now rendered as a literal block, in every task input (not only script content). The token test expects the |- form, and a new test covers a token in executeProgram.path. The docstring and README now say that substituted values must be single-line.
| /** | ||
| * Arguments passed to the shell that runs the script (not to the script itself) | ||
| * | ||
| * Only supported for PowerShell scripts. | ||
| * | ||
| * @default - EC2Launch v2 passes `-ExecutionPolicy Unrestricted` | ||
| */ | ||
| readonly arguments?: string[]; | ||
| } | ||
|
|
||
| /** | ||
| * Options when constructing UserData for Windows using the EC2Launch v2 format | ||
| * | ||
| * These options apply to the PowerShell script made up of the commands added | ||
| * with `addCommands()` and the other `add*Command()` methods. | ||
| */ | ||
| export interface Ec2LaunchV2UserDataOptions extends Ec2LaunchV2ScriptOptions { | ||
| } | ||
|
|
||
| /** | ||
| * Options for the EC2Launch v2 `executeScript` task | ||
| */ | ||
| export interface Ec2LaunchV2ExecuteScriptOptions extends Ec2LaunchV2ScriptOptions { | ||
| /** | ||
| * The content of the script | ||
| */ | ||
| readonly content: string; | ||
|
|
||
| /** | ||
| * The type of the script | ||
| * | ||
| * @default Ec2LaunchV2ScriptType.POWERSHELL | ||
| */ | ||
| readonly type?: Ec2LaunchV2ScriptType; | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — Ec2LaunchV2Task.executeScript() takes a single options struct that holds both type (PowerShell or batch) and arguments, and arguments is documented as "Only supported for PowerShell scripts". So { type: BATCH, arguments: [...] } compiles, and the mistake only shows up at synth time as an Ec2LaunchV2BatchScriptArguments error. The design guidelines prefer separate interfaces over shared ones with runtime validation when variants have different requirements (interface-design). Once this ships in stable aws-cdk-lib, splitting the shape will need a deprecation cycle.
Suggested change: Offer one factory per script type, for example Ec2LaunchV2Task.executePowerShell(options: Ec2LaunchV2PowerShellScriptOptions) (content, frequency, runAs, detach, arguments) and Ec2LaunchV2Task.executeBatch(options: Ec2LaunchV2BatchScriptOptions) (no arguments). The factory then sets type, the runtime check goes away, and Ec2LaunchV2UserDataOptions extends the PowerShell options. If you keep a single executeScript, give the batch case its own options interface without arguments at minimum.
There was a problem hiding this comment.
Done in 2f55e31: executeScript() is replaced by executePowerShell(options: Ec2LaunchV2PowerShellScriptOptions) and executeBatch(options: Ec2LaunchV2BatchScriptOptions). Only the PowerShell options (Ec2LaunchV2PowerShellOptions, which Ec2LaunchV2UserDataOptions extends) have arguments. The factory sets type, so the Ec2LaunchV2ScriptType enum and the runtime check are gone.
| test('renders an empty task list without commands or tasks', () => { | ||
| const userData = ec2.UserData.forWindowsEc2LaunchV2(); | ||
|
|
||
| expect(parse(userData)).toEqual({ version: 1.1, tasks: [] }); | ||
| }); |
There was a problem hiding this comment.
🔴 Blocking — No test covers a command placeholder that is registered but ends up empty. Two branches handle this case: renderCommandScript() returns undefined, and render() drops the task when rendered.length === 0. Every test that calls addCommands/addOnExitCommands passes at least one argument, and the empty-task-list test never registers the placeholder. If either branch regresses, addCommands(...[]) would emit an executeScript input with empty content next to the real tasks, and the suite would stay green (CONTRIBUTING.md#step-3).
Suggested change: ```ts
test('omits the command script when no commands were added', () => {
const userData = ec2.UserData.forWindowsEc2LaunchV2();
userData.addCommands();
userData.addTask(ec2.Ec2LaunchV2Task.startSsm());
expect(parse(userData)).toEqual({ version: 1.1, tasks: [{ task: 'startSsm' }] });
});
test('keeps a user executeScript input when the command placeholder is empty', () => {
const userData = ec2.UserData.forWindowsEc2LaunchV2();
userData.addCommands();
userData.addTask(ec2.Ec2LaunchV2Task.executeScript({ content: 'script' }));
expect(parse(userData).tasks).toEqual([{ task: 'executeScript', inputs: [
{ frequency: 'once', type: 'powershell', runAs: 'localSystem', content: 'script' },
] }]);
});
| test('fails to add a task with inputs twice', () => { | ||
| // GIVEN | ||
| const userData = ec2.UserData.forWindowsEc2LaunchV2(); | ||
| userData.addTask(ec2.Ec2LaunchV2Task.hostName()); | ||
|
|
||
| // THEN | ||
| expect(() => userData.addTask(ec2.Ec2LaunchV2Task.hostName({ reboot: true }))) | ||
| .toThrow(/task "setHostName" has already been added/); | ||
| }); | ||
|
|
||
| test('fails to add commands after a custom executeScript task without a list of inputs', () => { | ||
| // GIVEN | ||
| const userData = ec2.UserData.forWindowsEc2LaunchV2(); | ||
| userData.addTask(ec2.Ec2LaunchV2Task.custom('executeScript', { content: 'x' })); | ||
|
|
||
| // THEN | ||
| expect(() => userData.addCommands('command1')).toThrow(/task "executeScript" has already been added/); | ||
| }); |
There was a problem hiding this comment.
🟡 Recommended — The duplicate-task guard in mergeTask (existing !== undefined || inputs !== undefined) is only tested map-then-map, map-then-list, and with neither side having inputs. No test has inputs on only one side. If the || became &&, every current test would still pass, but startSsm() followed by custom('startSsm', { x: 1 }) would silently drop the second task's inputs instead of throwing (AGENTS.md#unit-tests).
Suggested change: ```ts
test.each([
[ec2.Ec2LaunchV2Task.startSsm(), ec2.Ec2LaunchV2Task.custom('startSsm', { x: 1 })],
[ec2.Ec2LaunchV2Task.custom('startSsm', { x: 1 }), ec2.Ec2LaunchV2Task.startSsm()],
[ec2.Ec2LaunchV2Task.executeProgram({ path: 'a.exe' }), ec2.Ec2LaunchV2Task.custom('executeProgram', { path: 'b.exe' })],
])('fails to merge incompatible inputs for the same task', (first, second) => {
const userData = ec2.UserData.forWindowsEc2LaunchV2();
userData.addTask(first);
expect(() => userData.addTask(second)).toThrow(/has already been added/);
});
There was a problem hiding this comment.
Added the test.each in 2f55e31, covering inputs on one side only in both orders, and list inputs followed by map inputs.
|
|
||
| test.each(['a-very-long-hostname', 'web_01', '12345', ''])('fails for invalid host name %j', (hostName) => { | ||
| expect(() => ec2.Ec2LaunchV2Task.hostName({ hostName })) | ||
| .toThrow(/host name must be at most 15 characters/); |
There was a problem hiding this comment.
🟡 Recommended — The host name length check (hostName.length > 15) is never tested at its limit. The rejected values are 20 characters or invalid for other reasons, and the only accepted value, web-01, is 6 characters. An off-by-one change (>= 15 or > 16) would pass the suite. The first would reject valid 15-character names. The second would allow names the task definitions say EC2Launch v2 rejects (AGENTS.md#unit-tests).
Suggested change: Pin both sides of the limit:
test('accepts a 15 character host name', () => {
expect(() => ec2.Ec2LaunchV2Task.hostName({ hostName: 'abcdefghijklmno' })).not.toThrow();
});Also add 'abcdefghijklmnop' (16 characters) to the existing rejection test.each. An accepted value such as '1web' would show that names starting with a digit are allowed.
There was a problem hiding this comment.
Added in 2f55e31: abcdefghijklmno (15) and 1web are accepted, and abcdefghijklmnop (16) is rejected.
| test('fails to initialize an empty list of devices', () => { | ||
| expect(() => ec2.Ec2LaunchV2Task.initializeVolume({ devices: [] })) | ||
| .toThrow(/devices must not be empty/); | ||
| }); | ||
|
|
||
| test.each(['', 'DE', '1', 'Ä'])('fails for invalid drive letter %j', (letter) => { | ||
| expect(() => ec2.Ec2LaunchV2Task.initializeVolume({ devices: [{ device: 'xvdb', letter }] })) | ||
| .toThrow(/drive letter must be a single letter/); | ||
| }); |
There was a problem hiding this comment.
🟡 Recommended — initializeVolume has two Token.isUnresolved guards, one for the devices list and one for each drive letter, but neither has a test that passes a token. If the letter guard were removed, a tokenized letter would wrongly throw and nothing would catch it. The list guard skips the empty check but then iterates and maps over the token marker, so it would render device: undefined entries (AGENTS.md#token-safety).
Suggested change: ```ts
test('does not validate a tokenized drive letter', () => {
const letter = Lazy.string({ produce: () => 'DE' });
expect(() => ec2.Ec2LaunchV2Task.initializeVolume({ devices: [{ device: 'xvdb', letter }] })).not.toThrow();
});
Then either add a test for a tokenized `devices` list that checks the rendered output, or drop that list guard if a tokenized list of structs isn't a supported input.
There was a problem hiding this comment.
Added the tokenized drive letter test in 2f55e31. I dropped the guard on the devices list: it is a list of structs, which cannot be a token, so the guard protected nothing.
| const userData = ec2.UserData.forWindowsEc2LaunchV2(); | ||
| userData.addTask(ec2.Ec2LaunchV2Task.executeProgram({ | ||
| path: 'C:\\Windows\\System32\\cmd.exe', | ||
| arguments: ['/c', 'mkdir', createdDir], | ||
| })); | ||
| userData.addCommands( | ||
| `if (-not (Test-Path -Path '${createdDir}' -PathType Container)) { throw 'executeProgram task did not run' }`, | ||
| ); |
There was a problem hiding this comment.
🟡 Recommended — The integration test is well designed: the instance only signals once EC2Launch v2 has loaded the YAML and run both tasks in order. But it only deploys executeProgram and the command executeScript. The other factories (hostName, wallpaper, initializeVolume, sysprep, startSsm, enableOpenSsh, enableJumboFrames, optimizeEna, custom) are checked only against documentation. The writeFile case already shows the docs can be wrong here (INTEGRATION_TESTS.md#when-required).
Suggested change: Add the tasks that don't disrupt the instance to the same user data. The existing signal already proves the document loaded:
userData.addTask(ec2.Ec2LaunchV2Task.startSsm());
userData.addTask(ec2.Ec2LaunchV2Task.wallpaper({
attributes: [ec2.Ec2LaunchV2WallpaperAttribute.INSTANCE_ID],
instanceTags: ec2.Ec2LaunchV2WallpaperTags.all(),
}));
userData.addTask(ec2.Ec2LaunchV2Task.hostName({ hostName: 'cdk-integ', reboot: false }));
userData.addTask(ec2.Ec2LaunchV2Task.initializeVolume({ devices: [{ device: 'xvdf', letter: 'D' }] })); // with an extra EBS block deviceLeave out sysprep, optimizeEna and enableJumboFrames, since they may shut down, reboot or change the network. Note in the PR body which factories are verified only against the docs.
There was a problem hiding this comment.
Added in 2f55e31: initializeVolume with an extra 1 GiB EBS volume at xvdf, plus hostName (no reboot), wallpaper and startSsm. The script now also fails unless D:\ exists, so the signal verifies that initializeVolume ran, not only that it loaded. Redeployed successfully. Separately from the integ test, I launched one instance per factory with only that task and checked the agent logged User data format: yaml_1.1. That covers sysprep, optimizeEna, enableJumboFrames and enableOpenSsh, but only shows they load, not what they do. The PR description now says so.
| There is no factory method for the `writeFile` task: although it is documented for user data, EC2Launch v2 does not | ||
| load user data that contains it. Use `Set-Content` in `addCommands()` to write files instead. |
There was a problem hiding this comment.
🟡 Recommended — The README says EC2Launch v2 "does not load user data that contains" writeFile, stated as permanent service behavior. The task definitions page lists writeFile as allowed in the UserData stage. The PR's own Ec2LaunchV2Task JSDoc limits the claim to the version you tested (2.5.2), but the README drops that version. The module README is published as the API docs (AGENTS.md#module-readmes), so if a later agent version loads writeFile, it would state something false about AWS.
| There is no factory method for the `writeFile` task: although it is documented for user data, EC2Launch v2 does not | |
| load user data that contains it. Use `Set-Content` in `addCommands()` to write files instead. | |
| There is no factory method for the `writeFile` task: although it is documented for user data, EC2Launch v2 | |
| (tested with version 2.5.2) does not load user data that contains it. Use `Set-Content` in `addCommands()` | |
| to write files instead, or `Ec2LaunchV2Task.custom('writeFile', [...])` on agent versions that support it. |
There was a problem hiding this comment.
Applied the suggested wording in 2f55e31.
| * Commands added with `addOnExitCommands()` run in a `finally` block, so they also run when the script calls `exit`. This | ||
| includes `exit 3010`, which EC2Launch v2 uses to reboot the instance and run the script again, so a signal added with | ||
| `addSignalOnExitCommand()` is sent before such a reboot. |
There was a problem hiding this comment.
⚪ Optional — The migration bullet says a signal from addSignalOnExitCommand() "is sent before such a reboot", but doesn't say it reports success. For anyone moving from forWindows() who gates a CreationPolicy on this signal, that difference matters: the resource completes as successful before the run after the reboot has done its work. If the on-exit behavior changes as raised on renderCommandScript(), this bullet should describe the new behavior instead.
Suggested change: If the current behavior is kept, say explicitly that a signal added with addSignalOnExitCommand() reports success before such a reboot, so the resource's CreationPolicy can complete before the run after the reboot finishes.
There was a problem hiding this comment.
Rewrote the bullet in 2f55e31 to describe the new behaviour: on-exit commands, including the signal, run after the commands complete or throw. They do not run on exit, so after exit 3010 they run at the end of the run after the reboot.
- Run on-exit commands, including the CloudFormation signal, only when the commands complete or throw, not on an explicit `exit`. Previously `exit 1` or `exit 3010` sent a success signal. - Replace `Ec2LaunchV2Task.executeScript()` with `executePowerShell()` and `executeBatch()`, so batch scripts cannot be given PowerShell arguments. - Render strings containing tokens as literal blocks, so single-line values substituted by CloudFormation need no escaping. - Drop the token guard on the `initializeVolume` devices list, which cannot be a token. - Cover more tasks in the integration test, and add unit tests for empty command scripts, task merging, host name limits and tokens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
See the review summary comment for the overview; the notes below are inline.
| function removeUndefined(value: any): any { | ||
| if (Array.isArray(value)) { | ||
| return value.map(removeUndefined); | ||
| } | ||
| if (value !== null && typeof value === 'object') { | ||
| return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => [k, removeUndefined(v)])); | ||
| } | ||
| return value; | ||
| } |
There was a problem hiding this comment.
🔴 Blocking — removeUndefined rebuilds every non-null object with Object.fromEntries(Object.entries(value)…), and this includes IResolvable tokens passed through Ec2LaunchV2Task.custom(taskName, inputs?: any), such as Fn.getAtt(...), Lazy.any(...) or a CfnReference. The token turns into a plain map of its own fields and is never resolved. An Intrinsic renders as YAML like value: {Ref: X} plus typeHint/creationStack keys. A Reference walks into its target construct's scope tree, and the recursion never ends. Any object implementing IResolvable is a token and must be checked before it is changed (token-safety). Python, Java, C# and Go users get get_att results as IResolvable, so putting one straight into custom() inputs is a natural thing to do.
Suggested change: Check for a resolvable before walking into it, and turn it into a string token. useLiteralBlocks already renders string tokens as block literals:
function removeUndefined(value: any): any {
if (Tokenization.isResolvable(value)) {
return Token.asString(value);
}
if (Array.isArray(value)) {
return value.map(removeUndefined);
}
if (value !== null && typeof value === 'object') {
return Object.fromEntries(Object.entries(value)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => [k, removeUndefined(v)]));
}
return value;
}If you'd rather not support non-string tokens, throw an UnscopedValidationError with a lit code there that tells the caller to use Token.asString(). Either way, add a unit test that passes Fn.getAtt(...) in custom() inputs and checks the resolved output.
There was a problem hiding this comment.
Fixed in 546ee67. Task inputs are now normalized when the task is created: IResolvable values become string tokens (as suggested), and number tokens become stringified number tokens so they resolve too. List tokens are rejected with Ec2LaunchV2ListToken, because a list cannot be substituted into the YAML document. The same function also renders the document. Tests check that a getAtt() in custom() inputs resolves to Fn::GetAtt, that a number token resolves to its Ref, and that a list token fails, both in custom() and in executeProgram arguments.
| private ensureCommandScript() { | ||
| if (!this.hasCommandScript) { | ||
| this.mergeTask('executeScript', [() => this.renderCommandScript()]); | ||
| this.hasCommandScript = true; | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — The first addCommands()/addOnExitCommands() call registers the command script, and its cfn-signal, inside executeScript at that point in the task order. Any task added later runs after the signal, so CloudFormation reports success before the instance is configured, and failures in those tasks never reach the stack. Users often don't control this order: Instance attaches cfn-init commands in its constructor when init is set, so addTask(initializeVolume()) after creating the instance runs after the signal. forWindows() always signals last, and this flavour silently drops that guarantee (general-principles).
Suggested change: Preferred: in render(), emit the executeScript task last when the command script is registered, and keep the command-script function as the last element of its inputs. The signal then follows every other task, as it does with forWindows(). sysprep already runs last on the agent side. Then document that executePowerShell/executeBatch inputs run with the command script at the end. At minimum, have addTask() throw an UnscopedValidationError when the command script is already registered and the new task would land after it, and explain where the signal lands in the README.
There was a problem hiding this comment.
Fixed in 546ee67 with the preferred approach. Once commands have been added, render() emits the executeScript task after all other tasks, with the command script as its last input, so the signal follows every other task, as with forWindows(). The duplicate checks are unchanged: the first add*Command() call still fails if executeScript was added with map inputs. A new test creates an Instance with the user data, adds the signal and commands, then adds tasks: they render before the command script. The README and class docs describe this, including that executePowerShell/executeBatch inputs run together with the command script at the end. The integ snapshot is unchanged, because it already added its tasks first.
|
|
||
| test('can add custom tasks', () => { | ||
| // GIVEN | ||
| const userData = ec2.UserData.forWindowsEc2LaunchV2(); | ||
|
|
||
| // WHEN | ||
| userData.addTask(ec2.Ec2LaunchV2Task.custom('futureTask', { setting: 'on', count: 1 })); | ||
| userData.addTask(ec2.Ec2LaunchV2Task.custom('futureListTask', [{ a: 'yes' }])); | ||
| userData.addTask(ec2.Ec2LaunchV2Task.custom('futureListTask', [{ a: 'no' }])); | ||
|
|
||
| // THEN | ||
| const rendered = userData.render(); | ||
| expect(rendered).toContain('setting: "on"'); | ||
| expect(YAML.parse(rendered, { version: '1.1' }).tasks).toEqual([ | ||
| { task: 'futureTask', inputs: { setting: 'on', count: 1 } }, | ||
| { task: 'futureListTask', inputs: [{ a: 'yes' }, { a: 'no' }] }, | ||
| ]); |
There was a problem hiding this comment.
🟡 Recommended — The only token tests use single-line string tokens (Aws.REGION, Lazy.string, Aws.STACK_NAME). No test passes these through task inputs:
- an
IResolvableobject, e.g.custom('x', { id: res.getAtt('Id') }) - a number token
- a list token, e.g.
executeProgram({ arguments: Fn.split(...) })
custom() is the documented escape hatch, so passing resource attributes through it is expected. removeUndefined copies such objects field by field, and list tokens end up as encoded markers in a YAML string (token-safety).
Suggested change: ```ts
test('keeps a token object in custom task inputs intact', () => {
const stack = new Stack();
const userData = ec2.UserData.forWindowsEc2LaunchV2();
const res = new CfnResource(stack, 'R', { type: 'Test::Resource' });
userData.addTask(ec2.Ec2LaunchV2Task.custom('futureTask', { id: res.getAtt('Id') }));
expect(JSON.stringify(stack.resolve(userData.render()))).toContain('"Fn::GetAtt":["R","Id"]');
});
test('handles a list token in executeProgram arguments', () => {
const stack = new Stack();
const userData = ec2.UserData.forWindowsEc2LaunchV2();
userData.addTask(ec2.Ec2LaunchV2Task.executeProgram({ path: 'C:\a.exe', arguments: Fn.split(',', Aws.STACK_NAME) }));
expect(() => stack.resolve(userData.render())).toThrow(/* expected message */);
});
If these inputs aren't meant to be supported, reject them up front with an `UnscopedValidationError` and add a `fails …` test that checks the message.
There was a problem hiding this comment.
Added in 546ee67: a getAtt() and a number token in custom() inputs, checked against the resolved output, and a list token in executeProgram arguments and in custom() inputs, which now fails up front with a specific message (see the thread on removeUndefined).
| EC2Launch v2 allows each task only once in user data, so tasks run in the order they were first added. Scripts added | ||
| with `Ec2LaunchV2Task.executePowerShell()` or `Ec2LaunchV2Task.executeBatch()` are inputs of the `executeScript` | ||
| task, like the commands added with `addCommands()`, and adding `executeProgram` again appends to the inputs of the | ||
| existing task. Tasks without a factory method in `Ec2LaunchV2Task` can be added with `Ec2LaunchV2Task.custom()`. |
There was a problem hiding this comment.
🟡 Recommended — This paragraph, repeated in the Ec2LaunchV2UserData class JSDoc (user-data.ts lines 844-848), says "tasks run in the order they were first added". Three problems:
- It doesn't say that the
addCommands()script, and thecfn-signalinside it, takes its slot on the firstadd*Command()call. Tasks added afterwards, including everyaddTask()afternew Instance(..., { init }), run after the signal. sysprepalways runs last, whatever the insertion order (sysprep task).- AWS doesn't document the "only once" rule, yet the paragraph presents it as service behaviour (module-readmes).
Suggested change: Replace the paragraph with something like: "Tasks run in the order they were first added (except sysprep, which EC2Launch v2 always runs last). The script made up of addCommands() and the other add*Command() methods takes its place the first time one of those methods is called. If the CloudFormation signal sent by addSignalOnExitCommand() should wait for other tasks, add them before calling those methods, including before passing init to an Instance. EC2Launch v2 (tested with version 2.5.2) does not load user data that repeats a task, so …". Make the matching change in the class JSDoc.
There was a problem hiding this comment.
Rewritten in 546ee67. The README now says that the executeScript task holding the commands, and so the signal, runs after all other tasks, including tasks added after passing init to an Instance (the ordering itself changed as discussed on ensureCommandScript). It also says that EC2Launch v2 always runs sysprep last. On the third point: AWS does document the rule. The user data schema section says "A task must only appear once in the user data tasks array." The README now links to it.
| /** | ||
| * Add an EC2Launch v2 task to the user data | ||
| */ |
There was a problem hiding this comment.
⚪ Optional — The addTask() JSDoc only says "Add an EC2Launch v2 task to the user data". mergeTask does three different things:
- it appends when the inputs are lists;
- it silently ignores a repeated task that has no inputs (e.g.
startSsm()twice); - it throws
Ec2LaunchV2DuplicateTaskfor any other repeat (e.g.hostName()twice).
This is the main mutation method on the new class, and users can't find out about the throw without reading the source (jsdoc).
| /** | |
| * Add an EC2Launch v2 task to the user data | |
| */ | |
| /** | |
| * Add an EC2Launch v2 task to the user data | |
| * | |
| * Adding a task whose inputs are a list (`executeScript`, `executeProgram`) | |
| * again appends to its inputs. Adding a task without inputs again has no | |
| * effect. Adding any other task again throws an error. | |
| */ |
- Render the `executeScript` task after all other tasks once commands have been added, with the command script as its last input, so the CloudFormation signal from `addSignalOnExitCommand()` follows every other task, as with `UserData.forWindows()`. Previously tasks added after the first `addCommands()` call, such as tasks added after an `Instance` with `init`, ran after the signal. - Turn token objects and number tokens in task inputs into string tokens instead of copying their fields, and reject list tokens, which cannot be substituted into a YAML document. - Document the task merging rules on `addTask()` and the task order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
See the review summary comment for the overview; the notes below are inline.
| * Switching an existing instance to the new format is a user data change like any other: the instance is not | ||
| replaced unless `userDataCausesReplacement` is set, and a script with frequency `once` does not run again on it. |
There was a problem hiding this comment.
🔴 Blocking — This migration bullet says the instance "is not replaced unless userDataCausesReplacement is set". That's wrong for any Instance created with initOptions. userDataCausesReplacement defaults to true when initOptions is passed, and the logical ID uses props.userDataCausesReplacement ?? props.initOptions. So for an Instance that uses init + initOptions, moving from forWindows() to forWindowsEc2LaunchV2() changes the user data hash, and CloudFormation replaces the instance. The default behaviour is part of the user contract (default-behavior), and the README points at exactly this init setup.
| * Switching an existing instance to the new format is a user data change like any other: the instance is not | |
| replaced unless `userDataCausesReplacement` is set, and a script with frequency `once` does not run again on it. | |
| * Switching an existing instance to the new format is a user data change like any other: the instance is | |
| replaced if `userDataCausesReplacement` is `true`, which is the default when `initOptions` is passed to the | |
| `Instance`. Otherwise it is updated in place, and a script with frequency `once` does not run again on it. |
There was a problem hiding this comment.
Correct, thanks: Instance uses props.userDataCausesReplacement ?? props.initOptions. Applied the suggested wording in 31b92cb.
| Scripts added with `Ec2LaunchV2Task.executePowerShell()` or `Ec2LaunchV2Task.executeBatch()` are inputs of the | ||
| `executeScript` task, and adding `executeProgram` again appends to the inputs of the existing task. Adding any other | ||
| task with inputs twice is an error. Tasks without a factory method in `Ec2LaunchV2Task` can be added with | ||
| `Ec2LaunchV2Task.custom()`. |
There was a problem hiding this comment.
⚪ Optional — "Adding any other task with inputs twice is an error" isn't true for tasks added with Ec2LaunchV2Task.custom() that have list inputs. mergeTask appends whenever both the existing and the new inputs are arrays, and the custom() JSDoc says so. The README's own custom('writeFile', [...]) suggestion is that case. As written, the README and the JSDoc disagree, and a user who expects an error gets merged inputs instead.
| Scripts added with `Ec2LaunchV2Task.executePowerShell()` or `Ec2LaunchV2Task.executeBatch()` are inputs of the | |
| `executeScript` task, and adding `executeProgram` again appends to the inputs of the existing task. Adding any other | |
| task with inputs twice is an error. Tasks without a factory method in `Ec2LaunchV2Task` can be added with | |
| `Ec2LaunchV2Task.custom()`. | |
| Scripts added with `Ec2LaunchV2Task.executePowerShell()` or `Ec2LaunchV2Task.executeBatch()` are inputs of the | |
| `executeScript` task, and adding `executeProgram`, or a task added with `Ec2LaunchV2Task.custom()` whose inputs are a | |
| list, again appends to the inputs of the existing task. Adding any other task with inputs twice is an error. Tasks | |
| without a factory method in `Ec2LaunchV2Task` can be added with `Ec2LaunchV2Task.custom()`. |
|
|
||
| function useLiteralBlocks(node: any) { | ||
| if (node?.items) { | ||
| // Maps contain pairs, sequences contain nodes | ||
| node.items.forEach((item: any) => useLiteralBlocks(item?.value !== undefined && item?.key !== undefined ? item.value : item)); | ||
| } else if (typeof node?.value === 'string' && (node.value.includes('\n') || Token.isUnresolved(node.value))) { | ||
| node.type = 'BLOCK_LITERAL'; | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — useLiteralBlocks sets BLOCK_LITERAL on strings that contain a newline or a token, but the yaml v1 stringifier doesn't always honour it. It switches to a double-quoted scalar when the value contains a control character, including \r from CRLF line endings, or when the last line is only whitespace. With a token in the string, CloudFormation then substitutes a raw value inside "...". A value containing \ or " (for example C:\temp\new) is either corrupted by escape sequences or makes YAML that EC2Launch v2 won't load. The JSDoc's "need no escaping" claim relies on the block style always applying (token-safety).
| function useLiteralBlocks(node: any) { | |
| if (node?.items) { | |
| // Maps contain pairs, sequences contain nodes | |
| node.items.forEach((item: any) => useLiteralBlocks(item?.value !== undefined && item?.key !== undefined ? item.value : item)); | |
| } else if (typeof node?.value === 'string' && (node.value.includes('\n') || Token.isUnresolved(node.value))) { | |
| node.type = 'BLOCK_LITERAL'; | |
| } | |
| function useLiteralBlocks(node: any) { | |
| if (node?.items) { | |
| // Maps contain pairs, sequences contain nodes | |
| node.items.forEach((item: any) => useLiteralBlocks(item?.value !== undefined && item?.key !== undefined ? item.value : item)); | |
| } else if (typeof node?.value === 'string') { | |
| const value = node.value.replace(/\r\n?/g, '\n'); | |
| node.value = value; | |
| const hasToken = Token.isUnresolved(value); | |
| if (value.includes('\n') || hasToken) { | |
| if (hasToken && (/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value) || /\n[\t ]+$/.test(value))) { | |
| throw new UnscopedValidationError(lit`Ec2LaunchV2TokenNotLiteral`, `values containing tokens must not contain control characters or end with a whitespace-only line, got ${JSON.stringify(value)}`); | |
| } | |
| node.type = 'BLOCK_LITERAL'; | |
| } | |
| } | |
| } |
There was a problem hiding this comment.
Confirmed against yaml 1.10: it falls back to a double-quoted scalar for CRLF, control characters (including NEL), a whitespace-only last line, and a string of only a newline. Fixed in 31b92cb, but slightly differently from the suggestion. Rather than copying those rules into a regex, the renderer renders each string that contains a token as a literal block on its own, and throws Ec2LaunchV2TokenNotLiteral if the library would not use one. That way the check follows the library. I did not normalize CRLF to LF. Strings without tokens are still escaped correctly in a quoted scalar, so it is not needed for them, and it would silently change batch scripts: cmd.exe misparses labels and goto in files with LF line endings. The README asks for LF line endings in scripts that contain tokens. Tests cover CRLF content without tokens (kept as is), and a carriage return, a control character, or a whitespace-only last line with a token (fails).
| for (const [task, inputs] of this.tasks) { | ||
| if (!(this.hasCommandScript && task === COMMAND_SCRIPT_TASK)) { | ||
| addRendered(task, inputs); | ||
| } | ||
| } | ||
| // The command script, which may send the CloudFormation signal, runs last | ||
| if (this.hasCommandScript) { | ||
| addRendered(COMMAND_SCRIPT_TASK, [...this.tasks.get(COMMAND_SCRIPT_TASK), this.renderCommandScript()]); | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — render() moves executeScript to the end only when hasCommandScript is set, and any add*Command() call from anywhere sets it. Scripts the user adds with executePowerShell()/executeBatch() are inputs of that task, so they move too. Their position no longer follows the user's own addTask order. Take executePowerShell (create C:\setup) followed by executeProgram (C:\setup\install.exe). It works alone, but once passed to new Instance(..., { init }), which adds cfn-init commands in its constructor, the program runs before the directory exists. This breaks least surprise and the fixed-invariant principle (general-principles).
Suggested change: Always render executeScript last when it is present, whether or not commands were added, and append the command script only when one is registered:
for (const [task, inputs] of this.tasks) {
if (task !== COMMAND_SCRIPT_TASK) {
addRendered(task, inputs);
}
}
if (this.tasks.has(COMMAND_SCRIPT_TASK)) {
const scripts = this.tasks.get(COMMAND_SCRIPT_TASK);
addRendered(COMMAND_SCRIPT_TASK, Array.isArray(scripts)
? [...scripts, ...(this.hasCommandScript ? [this.renderCommandScript()] : [])]
: scripts);
}The signal still follows every other task, and the rule becomes fixed: all scripts run after the other tasks, and sysprep runs last. Update the class JSDoc and the README ordering section to match.
There was a problem hiding this comment.
Done in 31b92cb as suggested: executeScript always renders after all other tasks, and the command script is appended only when registered. The README and class docs now state the fixed rule: scripts run in the order added, after all other tasks, then the commands. A new test covers the case without commands, with your example. Under the fixed rule that example now always runs the program first, which the README states.
| function useLiteralBlocks(node: any) { | ||
| if (node?.items) { | ||
| // Maps contain pairs, sequences contain nodes |
There was a problem hiding this comment.
🟡 Recommended — useLiteralBlocks handles map pairs (recursing into item.value) differently from sequence items (recursing into the item itself). Every token test reaches it through a map pair, such as path or the custom id/count, so the list-item path is never exercised. Realistic inputs reach it: executeProgram({ arguments: [bucket.bucketName] }) or Ec2LaunchV2WallpaperTags.of(tagToken). If that path broke, the token would render as a plain scalar and the suite would stay green (unit-tests).
Suggested change: ```ts
test('renders tokens in list items as literal blocks', () => {
const stack = new Stack();
const userData = ec2.UserData.forWindowsEc2LaunchV2();
userData.addTask(ec2.Ec2LaunchV2Task.executeProgram({ path: 'C:\a.exe', arguments: ['/x', Aws.STACK_NAME] }));
expect(stack.resolve(userData.render())).toEqual({
'Fn::Join': ['', [
Match.stringLikeRegexp('arguments:\n {10}- /x\n {10}- \|-\n {12}$'),
{ Ref: 'AWS::StackName' },
Match.anyValue(),
]],
});
});
Or assert the exact literal prefix, as the existing `path` token test does.
There was a problem hiding this comment.
Added in 31b92cb, asserting the exact literal prefix for a token in executeProgram arguments.
| */ | ||
| function renderEc2LaunchV2Yaml(value: any): string { | ||
| const doc = new YAML.Document({ version: '1.1' }); | ||
| doc.contents = YAML.createNode(normalizeEc2LaunchV2Value(value)) as any; | ||
| useLiteralBlocks(doc.contents); | ||
| return doc.toString(); |
There was a problem hiding this comment.
🟡 Recommended — renderEc2LaunchV2Yaml calls doc.toString() without setting a line width. yaml v1 defaults strOptions.fold.lineWidth to 80, so a single-line string over 80 characters with no newline or token is folded across lines. Examples are a long addCommands() line, a long executeProgram path, or a long argument. Exact-text tests use only short values, parse() round-trips pass whether or not the output is folded, and the integ test's long lines sit in a |- block that is never folded. So nothing checks what the agent actually receives for this common input (unit-tests).
Suggested change: Pin the exact output for one long single-line command:
test('renders a long single-line command', () => {
const userData = ec2.UserData.forWindowsEc2LaunchV2();
const cmd = `Write-Host '${'x'.repeat(100)}'`;
userData.addCommands(cmd);
expect(userData.render()).toContain(`content: ${cmd}\n`); // or the intended folded/literal form
});If folding isn't intended, disable it (line width 0) or force BLOCK_LITERAL in the renderer, then pin that output. Consider adding one long single-line addCommands to the integ test as well.
There was a problem hiding this comment.
Folding was not intended. In 31b92cb the renderer sets the yaml library line width to 0 while rendering and restores it afterwards (it is a global option in yaml v1, and rendering is synchronous). A new test pins a long command and a long path on single lines. I did not add a long line to the integration test: lines are no longer folded, so it would exercise nothing the unit test does not, and command lines already sit in a literal block there.
- Render the `executeScript` task after all other tasks whether or not commands were added, so scripts keep a fixed position. - Disable line folding when rendering, and fail when a string with a token cannot be rendered as a literal block (for example because it contains a carriage return), as CloudFormation would substitute the value into a quoted scalar unescaped. - Correct the README on instance replacement with `initOptions`, and on merging list inputs of custom tasks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Issue # (if applicable)
Closes #36781.
Reason for this change
UserData.forWindows()only produces the legacy XML (<powershell>) format. Instances running the EC2Launch v2 agent (the default on AWS Windows Server 2022 and later AMIs) also accept a YAML document listing tasks to run. This gives control the XML format lacks, for example initializing volumes, setting the host name, running programs, running scripts as a specific account, or running them detached.Description of changes
UserData.forWindowsEc2LaunchV2(options)returns a newEc2LaunchV2UserData. Commands added withaddCommands(),addS3DownloadCommand(),addExecuteFileCommand()andaddSignalOnExitCommand()produce the same PowerShell asforWindows(). Together they form one PowerShell input of theexecuteScripttask. The options (frequency,runAs,detach,arguments) map to that input.Ec2LaunchV2UserData.addTask(task)adds other tasks. TheEc2LaunchV2Taskfactory methods cover the tasks EC2Launch v2 accepts in user data:executePowerShellandexecuteBatch(both theexecuteScripttask, with separate option structs because only PowerShell takesarguments),executeProgram,initializeVolume,hostName(setHostName),wallpaper(setWallpaper),sysprep,enableJumboFrames,enableOpenSsh,optimizeEnaandstartSsm.Ec2LaunchV2Task.custom(name, inputs)is an escape hatch for anything else.yamlpackage aws-cdk-lib already bundles. It uses YAML 1.1 quoting, so strings such asyes/onstay strings for the agent's parser. Multi-line strings and strings containing tokens become literal blocks, so scripts stay readable and single-line values substituted by CloudFormation need no escaping. Multi-line substituted values are not supported; the README says so.forWindows().Existing behaviour is unchanged:
forWindows()output is identical, andWindowsImage/forOperatingSystem()still default to it, so no feature flag is needed.Design decisions worth a look
executeProgramor another script again appends to the task's inputs, which are lists. Adding another task that has inputs twice throws. Adding a task without inputs (e.g.startSsm) twice is a no-op. Tasks render in the order they were first added, except that theexecuteScripttask, which holds all scripts, always renders after all other tasks: user scripts in the order added, then the command script. So the signal fromaddSignalOnExitCommand()follows every other task, as withforWindows(), even for tasks added after anInstancewithinit. The rule is fixed, so a script cannot prepare something for a later non-script task; this is documented.getAtt()passed tocustom()) and number tokens are substituted as strings. List tokens are rejected up front, because a list cannot be substituted into the YAML document. Strings containing tokens are always literal blocks; if the yaml library could not render one as such (e.g. it contains a carriage return), rendering fails rather than producing a quoted scalar that CloudFormation would substitute into unescaped. Line folding is disabled.writeFilefactory. AWS documentswriteFileas allowed in user data, but EC2Launch v2 2.5.2 (current Windows Server 2022 AMI) logsUser data format: not_loadableand runs nothing when user data contains it. That happens whetherinputsis a list or a map, and with frequencyonceoralways. I tested each task factory's output on real instances. Every other task was accepted asyaml_1.1; onlywriteFilewas rejected. It stays reachable viacustom()in case the agent is fixed, and the docs suggestSet-ContentinaddCommands()instead.setXxxmethod names (Java setter conflict), sosetHostName/setWallpaperare exposed ashostName()/wallpaper(). Their docs name the AWS tasks.try/catch/finallyinstead of thetrapplusthrow "Success"used byforWindows(). With the trap, even a successful script terminates with an error, which EC2Launch v2 records as a failed task. A$finishedflag means on-exit commands, including the signal fromaddSignalOnExitCommand(), only run when the commands complete or throw, never on an explicitexit. Afterexit 1no signal is sent, as withforWindows(). Afterexit 3010, which EC2Launch v2 uses to reboot and re-run the script, the signal comes from the run after the reboot.frequencydefaults toONCEandrunAstoLOCAL_SYSTEM.setHostName.rebootand thesysprepbooleans are always rendered, defaulting tofalse, because the agent's own defaults are undocumented.Ec2LaunchV2prefix, AWS's name for the agent, rather thanWindowsV2, which reads like a Windows version.Describe any new or updated permissions being added
None.
Description of how you validated changes
forWindows()tests pass unchanged.integ.userdata-ec2launch-v2, deployed on Windows Server 2022 with EC2Launch v2.5.2.initializeVolumeformats an extra EBS volume asD:and anexecuteProgramtask creates a directory. The PowerShell commands fail unless both exist, then signal CloudFormation throughaddSignalOnExitCommand(). The user data also containshostName,wallpaperandstartSsm. The instance only completes if the agent loaded the whole document and ran the tasks in order.User data format:console line (seewriteFileabove).sysprep,optimizeEna,enableJumboFramesandenableOpenSshare left out of the integration test because they may shut down, reboot or reconfigure the network, so for them only loading is verified; their behaviour is verified only against the AWS documentation.main.Checklist
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license
🤖 Generated with Claude Code