Working with user data

Last time we created enough infrastructure to create a public ec2 server then manually installed Apache and set up some simple web pages on it.

We can automate the set up of our EC2 instances by using user data, which lets us define Bash scripts that will be run when the instance is created. Create a new text file userdata.txt

#!/bin/bash

yum update -y
yum install httpd php -y
service httpd start
chkconfig httpd on
echo "Hello From" > /var/www/html/index.html
curl http://169.254.169.254/latest/meta-data/instance-id >> /var/www/html/index.html
echo "Healthy" > /var/www/html/healthcheck.html
echo '<?php echo file_get_contents("http://www.apache.org/licenses/LICENSE-2.0.txt"); ?>' > /var/www/html/outbound.php

The #!/bin/bash indicates the command that will interpret the script. First we update the instance, then install Apache and php. The Apache service is started, then configured to start at boot time. Next, 3 files are created which will be useful going forward. An index file that displays the instance id using the meta data endpoint, a simple health check and a php script that fetches and displays the Apache license.

Now we just need to change our EC2 resource to include the user data: ec2.tf

resource "aws_instance" "server" {
  ami                    = "ami-0bdb1d6c15a40392c"
  instance_type          = "t2.micro"
  vpc_security_group_ids = ["${aws_security_group.demo_sg.id}"]
  key_name               = "pete-eu-west-1"
  subnet_id              = "${aws_subnet.public_subnet_a.id}"
  user_data              = "${file("userdata.txt")}"

  tags {
    Name = "Web Server"
  }
}

Now if you recreate the infrastructure you should be able to access 3 pages, the index page should tell you the instance id, /healthcheck.html will display a simple message and /outbound.php should show the Apache license.

Now we’ve got everything fully automated, next time we’ll look at security groups.