简体   繁体   English

AWS-CDK:使用 InitFile 在 EC2 实例中创建文件

[英]AWS-CDK: Using InitFile to create a file in EC2 instance

I'm trying to create a file in my EC2 instance using the InitFile construct in CDK.我正在尝试使用 CDK 中的 InitFile 构造在我的 EC2 实例中创建一个文件。 Below is the code i'm using to create my EC2 instance into which i'm trying to create a file textfile.txt which would contain a text 'welcome' going by https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_ec2/InitFile.html reference during cdk initialisation,下面是我用来创建我的 EC2 实例的代码,我试图在其中创建一个文件textfile.txt ,其中包含一个文本“欢迎”,由https://docs.aws.amazon.com/cdk/ cdk 初始化期间的api/v1/python/aws_cdk.aws_ec2/InitFile.html参考,

init_data = ec2.CloudFormationInit.from_elements(
            ec2.InitFile.from_string("/home/ubuntu/textfile.txt", "welcome")
        ) 

self.ec2_instance = ec2.Instance(self,
            id='pytenv-instance',
            vpc=self.vpc,
            instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.NANO),
            machine_image=ec2.MachineImage.generic_linux(
                {'us-east-1': 'ami-083654bd07b5da81d'}
            ),
            key_name="demokeyyt18",
            security_group=self.sg,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PUBLIC
            ),
            init=init_data,
            
        )

From the EC2 configuration it is evident that the machine image here is Ubuntu.从 EC2 配置可以看出,这里的机器映像是 Ubuntu。 Getting this error: Failed to receive 1 resource signal(s) within the specified duration .出现此错误: Failed to receive 1 resource signal(s) within the specified duration Am I missing something?我错过了什么吗? Any inputs?有什么输入吗?

UPDATE: This same code works with EC2 machine image as Amazon_linux but not for Ubuntu.更新:同样的代码适用于 Amazon_linux 的 EC2 机器映像,但不适用于 Ubuntu。 Am I doing something wrong?难道我做错了什么?

CloudFormation init requires the presence of cfn-init helper script on the instance. CloudFormation init 要求实例上存在cfn-init帮助程序脚本。 Ubuntu does not come with it, so you have to set it up yourself. Ubuntu 不自带,需要自己设置。

Here's the AWS guide that contains links to the installation scripts for Ubuntu 16.04/18.04/20.04. 这是 AWS 指南,其中包含指向 Ubuntu 16.04/18.04/20.04 的安装脚本的链接。 You need to add these to the user_data prop of your instance.您需要将这些添加到实例的user_data属性中。 Then cloudformation-init will work.然后 cloudformation-init 将起作用。

If you just want to create a file when the instance starts, though, you don't have to use cfn-init at all - you could just supply the command that creates your file to the user_data prop directly:但是,如果您只想在实例启动时创建一个文件,则根本不必使用cfn-init - 您可以直接将创建文件的命令提供给user_data属性:

self.ec2_instance.user_data.add_commands("echo welcome > /home/ubuntu/textfile.txt")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM