title: Best practice to create a file in AWS EC2 instance using cloud formation
body: <p>There are a lot of options to do that and I don't know which is the best one. I tried in the beginning to do is as following:</p>
  <pre><code>ServiceInstance:
  Type: &quot;AWS::EC2::Instance&quot;
  Properties:
    ImageId: !Ref AmiId, !Ref LatestOnescoutAmi ]
    InstanceType: !Ref InstanceType
    SubnetId: !ImportValue vpc-stack-PublicASubnet
    SecurityGroupIds:
      - !Ref ServiceSecurityGroup
    KeyName: !Ref KeyName
    UserData:
      'Fn::Base64': !Sub |
        #cloud-config
        write_files:
          - path: /etc/sysconfig/cloudformation
            permissions: 0644
            owner: root
            content: |
              STACK_NAME=${AWS::StackName}
              AWS_REGION=${AWS::Region}
          - path: /etc/datadog-agent/conf.d/mysql.d/conf.yaml
            permissions: 0644
            owner: dd-agent
            content: |
              init_config:
              instances:
              - server: some-db-host
                user: some-admin
                pass: some-password
                port: 3306
                tags:
                - dbinstanceidentifier:someide
  
        runcmd:
          ## enable datadog agent
          - systemctl start datadog-agent
          - systemctl start application.service
  </code></pre>
  <p>but then my <code>/etc/datadog-agent/conf.d/mysql.d/conf.yaml</code> grew and I have around 13 blocks and it's not good to put them hardcoded inside the template. Better to keep the template generic and pass the config file as a parameter.
  But, according to this <a href="https://stackoverflow.com/a/53675005/2650254">answer here</a>, it's not possible to pass a file or content of file to cloud formation.</p>
  <p>The way above is the simplest I see among other two options I can think about.</p>
  <ol>
  <li><p>Store the config in SSM and then get it back at the ec2 start.</p>
  </li>
  <li><p>Create an Autoscaling and launch group which accepts the file path but it's more complex than I need:</p>
  <pre><code>LaunchConfig:
      Type: AWS::AutoScaling::LaunchConfiguration
      Metadata:
        AWS::CloudFormation::Init:
          configSets:
            service_configuration:
            - datadog_setup
          datadog_setup:
            files:
              /etc/datadog-agent/conf.d/mysql.d/conf.yaml:
                content: &quot;@file://./config/conf-${Env}.yaml&quot;
                mode: &quot;000644&quot;
                owner: &quot;root&quot;
                group: &quot;root&quot;
            commands:
              start_datadog:
                command: service datadog-agent start
  </code></pre>
  </li>
  </ol>
  <p>Any idea how to do this in a simple, generic and secure way?
  An example given would be appreciated.
  Thanks in advance.</p>