2

Please may I have some advice on when to use these settings appropriately? userdata, metadata and cloud-init directives all seem to accomplish the same goal.

Following the AWS documentation, when using userdata I can set up a lamp server in this manner.

#!/bin/bash
yum update -y
amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
yum install -y httpd mariadb-server
systemctl start httpd
systemctl enable httpd
usermod -a -G apache ec2-user
chown -R ec2-user:apache /var/www
chmod 2775 /var/www
find /var/www -type d -exec chmod 2775 {} \;
find /var/www -type f -exec chmod 0664 {} \;
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php

Nice and dandy however I can also use cloud-init directives which for me already looks much cleaner.

#cloud-config
repo_update: true
repo_upgrade: all

packages:
 - httpd
 - mariadb-server

runcmd:
 - [ sh, -c, "amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2" ]
 - systemctl start httpd
 - sudo systemctl enable httpd
 - [ sh, -c, "usermod -a -G apache ec2-user" ]
 - [ sh, -c, "chown -R ec2-user:apache /var/www" ]
 - chmod 2775 /var/www
 - [ find, /var/www, -type, d, -exec, chmod, 2775, {}, \; ]
 - [ find, /var/www, -type, f, -exec, chmod, 0664, {}, \; ]
 - [ sh, -c, 'echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php' ]

Then we have Metadata values in Cloudformation which, to be honest seem more long-winded than cloud-init directives. It goes something like

UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource AmazonLinuxInstance --region ${AWS::Region}
            systemctl start httpd
Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              httpd: []
              mariadb-server: []
              php: []
              php-mysql: []
      Tags:
        - Key: Project
          Value: Autoscale

What are appropriate scenarios to use each of these?

1 Answers1

0

In my view, the main reason you would consider using cfn-init and associated metadata is when you couple it with cfn-hup.

One problem with UserData is that its updates a template do not lead to updates in your instances. This can be problematic if you for example, want to change some config setup of your httpd in your UserData.

The above issue can be overcome when you use cfn-init and cfn-hup. And for many, the ability to update the metadata, and subsequently, the processes on the instance is a major advantage over UserData.

Marcin
  • 215,873
  • 14
  • 235
  • 294