jerome
jerome

Reputation: 43

How to create files on EC2 init

I want to create a file with some code in it on a EC2 Instance creation. I use AWS Cloudformation to do so in yaml format.

Do you see something? I can't find my mistake...


Resources:
  TEST: ## Creation of a WordpressUser that will be used by WebServers
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init:
        config:
          files:
            /home/setup:
              content: "coucou"
              mode : "000644"
              owner: root
              group: root
    Properties:
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: !Ref AWS::Region
      ImageId: ami-0bff0560e5fbc705c
      InstanceType: t2.micro
      SecurityGroupIds:
        - sg-0afaa61c82d3fe182
      SubnetId: subnet-0fe15919cc08eb4e8
      Tags:
        - Key: name
          Value: Initiate RDS

Upvotes: 2

Views: 1699

Answers (1)

Pedro Arantes
Pedro Arantes

Reputation: 5379

You also need to provide cnf-init to your template. Check this link:

The cfn-init helper script reads template metadata from the AWS::CloudFormation::Init key and acts accordingly to:

  • List item
  • Fetch and parse metadata from AWS CloudFormation
  • Install packages
  • Write files to disk
  • Enable/disable and start/stop services

Complementing your template:

Resources:
  TEST: ## Creation of a WordpressUser that will be used by WebServers
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init:
        config:
          files:
            /home/setup:
              content: "coucou"
              mode : "000644"
              owner: root
              group: root
    Properties:
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: !Ref AWS::Region
      ImageId: ami-0bff0560e5fbc705c
      InstanceType: t2.micro
      SecurityGroupIds:
        - sg-0afaa61c82d3fe182
      SubnetId: subnet-0fe15919cc08eb4e8
      Tags:
        - Key: name
          Value: Initiate RDS
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe
          yum update -y
          # Install the files and packages from the metadata
          yum install -y aws-cfn-bootstrap
          /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource TEST --region ${AWS::Region}
          # Start up the cfn-hup daemon to listen for changes to the EC2 metadata
          /opt/aws/bin/cfn-hup || error_exit 'Failed to start cfn-hup'
          # Signal the status from cfn-init
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource TEST  --region ${AWS::Region}

You may also want to check this step by step showing how to deploy an EC2 instance with CloudFormation.

Upvotes: 3

Related Questions