Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below works, however, adding

xxx.addCommands('<persist>true</persist>')
is not straightforward due to the forWindows() function wrapping the commands in tags.

// Instance details
const ssmaUserData = UserData.forWindows()
ssmaUserData.addCommands('mkdir -p C:/helloworld; ');

const ec2Instance = new ec2.Instance(this, 'SdkInstance', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.NANO),
  machineImage: awsAMI,
  securityGroup: mySecurityGroup,
  vpcSubnets: {subnetType: ec2.SubnetType.PUBLIC},
  keyName: "EC2Connect",
  userData: ssmaUserData
});

I've tried using

ssmaUserData.addOnExitCommands("<persist>true</persist>")
and similar approaches without success. Does anyone know how to achieve persistence in this case?

Here are the logs indicating that the approach taken does not result in persistence...

2021/03/11 12:56:51Z: Userdata execution begins
2021/03/11 12:56:51Z: Zero or more than one <persist> tag was not provided
2021/03/11 12:56:51Z: Unregistering the persist scheduled task
2021/03/11 12:56:55Z: Zero or more than one <runAsLocalSystem> tag was not provided
2021/03/11 12:56:55Z: Zero or more than one <script> tag was not provided
2021/03/11 12:56:55Z: Zero or more than one <powershellArguments> tag was not provided
2021/03/11 12:56:55Z: <powershell> tag was provided.. running powershell content
2021/03/11 13:08:34Z: Userdata execution begins
2021/03/11 13:08:34Z: Zero or more than one <persist> tag was not provided
2021/03/11 13:08:34Z: Unregistering the persist scheduled task
2021/03/11 13:08:37Z: Zero or more than one <runAsLocalSystem> tag was not provided
2021/03/11 13:08:37Z: Zero or more than one <script> tag was not provided
2021/03/11 13:08:37Z: Zero or more than one <powershellArguments> tag was not provided
2021/03/11 13:08:37Z: <powershell> tag was provided.. running powershell content
2021/03/11 13:08:42Z: Message: The output from user scripts: 

Answer №1

Understood! Whenever I utilized the UserData.forWindows() method, as detailed in AWS documentation, it automatically inserted the <PowerShell> tags. This meant that if I specified <Persist>, it would wrap around the tag... To resolve this issue, I switched to using UserData.custom(). After testing the updated code below, I can confirm that everything is functioning perfectly!

const script = `
<powershell>
  Start-Transcript -OutputDirectory C:/
  Write-Output HelloWorld
  Stop-Transcript
</powershell>
<persist>true</persist>
`;

const ssmaUserData = UserData.custom(script)

const ec2Instance = new ec2.Instance(this, 'SdkInstance', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.NANO),
  machineImage: awsAMI,
  securityGroup: mySecurityGroup,
  vpcSubnets: {subnetType: ec2.SubnetType.PUBLIC},
  keyName: "EC2Connect",
  userData: ssmaUserData,
});

Answer №2

To simplify your script writing process, utilize the available methods provided to perform tasks such as S3 downloads.

After completing the UserData configuration, retrieve the script and include any necessary flags.

For instance (similar approach can be applied in typescript):

    instance_userdata = ec2.UserData.for_windows()
    #... perform various actions like: instance_userdata.add_s3_download_command(...)

    data_script = instance_userdata.render()
    #https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-windows-user-data.html#user-data-execution
    data_script += "<persist>true</persist>"
    persistent_userdata = ec2.UserData.custom(data_script)

Answer №3

If you haven't already, consider adding userDataCausesReplacement: true. I faced a similar issue in the past and including this line resolved it for me.

// Customizing instance details
const userData = UserData.forWindows()
userData.addCommands('mkdir -p C:/helloworld; ');

const newEC2Instance = new ec2.Instance(this, 'CustomInstance', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.NANO),
  machineImage: awsAMI,
  securityGroup: mySecurityGroup,
  vpcSubnets: {subnetType: ec2.SubnetType.PUBLIC},
  keyName: "EC2Connect",
  userData: userData,
  userDataCausesReplacement: true
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After the "markerClick" event triggers in Angular2 SebmGoogleMapMarker, the view fails to update

I am dealing with an array structured like this: locations: marker[] = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)', iconUrl: 'img/marker.png'}, {id: '2&apos ...

Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies. Firstly, I have a function that adds data to Firebase: addpost() { let newposts = new Posts( this.addForm.value ) this.postsservice.addPosts(newposts); } Ne ...

Utilizing TypeScript interfaces with additional parameter object members does not result in the anticipated compilation error

Consider the different types listed below: type Person = { id: string; name: string; }; interface PeopleRepository { getPerson(query: { id: string }): Person; } class Repository implements PeopleRepository { getPerson({ id, age }: { id: string; ...

How to Generate a Unique URL in Angular 7 Using Typescript

I'm struggling to display or download a .pdf file in my Angular 7 project due to issues with window.URL.createObjectURL. Here's the code snippet I've written: this.userService.getFile(report.id).subscribe( res => { console.log(res) ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

Combining array elements into functions with RxJS observables

I am facing a scenario where I have an array of values that need to be processed sequentially using observables in RxJS. Is there a more optimized way to achieve this instead of using nested subscriptions? let num = 0; let myObs = new Observable(obs ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Can you tell me the data type of IconButtons in Material UI when using TypeScript?

Currently, I am in the process of creating a sidebar using Material UI in Next JS with typescript. My plan is to create a helper function that will help display items within the sidebar. // LeftSidebar.tsx import {List,ListItem,ListItemButton,ListItemIcon ...

Encountered an error while trying to generate the Component class for the ColorlibStepIcon from Material UI in TypeScript

I am trying to convert the ColorlibStepIcon functional component into a class component for my Stepper. Unfortunately, I have not been successful and keep encountering errors. I have attempted some changes but it is still not working as expected. You can ...

The transition() function in Angular 2.1.0 is malfunctioning

I am struggling to implement animations in my Angular 2 application. I attempted to use an example I found online and did some research, but unfortunately, I have not been successful. Can anyone please assist me? import {Component, trigger, state, anima ...

Utilizing Angular 4 with Ahead-Of-Time compilation in combination with Electron, as well as

I am new to Angular/Typescript and currently developing a cross-platform Desktop application with Electron and Angular 4. My current challenge involves using a Service in different components, but I need this service to be loaded from a separate file based ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

Exploring type delegation in TypeScript

Here is a scenario where I am using the builder pattern in my code: export class ValidationBuilderBase implements IValidationBuilder { public isRequired(): IValidationBuilder { const validationResult = Validators.required(this.baseControl); ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...