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

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

I'm baffled as to why TypeScript isn't throwing an error in this situation

I anticipated an error to occur in this code snippet, indicating that b.resDetails is possibly undefined, however, no such error occurred. Can someone please provide an explanation for this unexpected behavior? I'm quite perplexed. type BasicD ...

Distributing utility functions universally throughout the entire React application

Is there a way to create global functions in React that can be imported into one file and shared across all pages? Currently, I have to import helper.tsx into each individual file where I want to use them. For example, the helper.tsx file exports functio ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

What is the method to transfer the outcome of a GET request into a POST request?

My task involves sending a GET request to retrieve information from . When the request is made, it generates a random image and returns a JSON object that includes details such as "fileSizeBytes" and "url". My goal is to extract the "url" value and then ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Upon upgrading to Angular 8, the function this._delegate.setNgStyle is not recognized

Following the update of my project from Angular 7 to Angular 8 and resolving all errors caused by breaking changes, I am encountering a new issue: <div fxFill ngStyle.xs="overflow:auto"> This line is resulting in the following error: ERROR Type ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

What are the steps for customizing the interface in TypeScript?

After fixing a type error related to adding custom functions to the gun chain by including bind():any within IGunChainReference in @types/gun/index.ts, I am wondering how to transfer this modification to one of my project files. I have not been able to fi ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

What causes a folder to disappear after rerunning in nest.js?

When working on my project using nest.js in MacOS Sonoma, I encountered a problem where the image folder src/products/images gets deleted after every project rerun (npm start). The images are saved like this: for (const image of images) { const fileName ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Looking for a regular expression to verify if the URL inputted is valid in TypeScript

After conducting thorough research, I discovered that none of the suggested URLs met my criteria, prompting me to raise a new query. Here are my specific requirements: * The URL may or may not include 'http' or 'https' * The URL can co ...

Alternative for using useRouteMatch to retrieve parameters

I'm currently refactoring this code and struggling to find a suitable replacement for this section. This is due to the react-router-dom v6 no longer having the useRouteMatch feature, which I relied on to extract parameters from the URL: import React, ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows: <mat-card *ngFor="let record of records"> <span class="doc ...

Ways to determine the number of duplicate items in an Array

I have an array of objects that contain part numbers, brand names, and supplier names. I need to find a concise and efficient way to determine the count of duplicate objects in the array. [ { partNum: 'ACDC1007', brandName: 'Electric&apo ...