AWS CDK ec2.实例用户数据..不坚持:(



我正试图使用AWS CDK启动一个ec2实例,在大多数情况下,它工作得很好,但我希望userData能够持久存在,以便在每次启动时运行。。。令人烦恼的是,这没有文档记录(在我能找到的任何地方(,我只是不知道在哪里/如何定义它。下面是我的代码,但由于用户数据是由forWindows()提供的,我不能只添加xxx.addCommands('<persist>true</persist>'),因为forWindows((将代码放在标记中。。。

// 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
});

我曾尝试使用ssmaUserData.addOnExitCommands("<persist>true</persist>")及其变体,但没有成功,有人知道如何做到这一点吗?

下面的日志表明这不是用持久性运行的。。。

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: 

明白了!因此,每当我使用AWS充分记录的UserData.forWindows()时,它都会自动添加<PowerShell>标签,这意味着如果我定义<Persist>,它将包含标签。。。为了解决这个问题,我需要使用UserData.custom()。我已经测试了下面的代码,它运行得很好!

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,
});

为了避免在字符串中编写所有脚本,您可以使用提供的方法,特别是如果您想进行S3下载之类的操作。

完成UserData后,只需获取脚本并附加标志即可。

示例(在python中,但可以在typescript中以相同的方式完成(:

instance_userdata = ec2.UserData.for_windows()
#... do lots os 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)

最新更新