Home > Back-end >  AWS-CDK: Using InitFile to create a file in EC2 instance
AWS-CDK: Using InitFile to create a file in EC2 instance

Time:08-10

I'm trying to create a file in my EC2 instance using the InitFile construct in CDK. 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,

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. Getting this error: 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. Am I doing something wrong ?

CodePudding user response:

CloudFormation init requires the presence of cfn-init helper script on the instance. Ubuntu does not come with it, so you have to set it up yourself.

Here's the AWS guide that contains links to the installation scripts for Ubuntu 16.04/18.04/20.04. You need to add these to the user_data prop of your instance. Then cloudformation-init will work.

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:

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