We can set up a simple Apache web server on an EC2 instance at launch using EC2 user data as follows:
- Go to the EC2 dashboard and click on Instances from the left sidebar. Click on the Launch Instance button at the top of the page, select Amazon Linux 2 AMI, set Type to t2.micro, and click Next: Configure Instance Details.
- On the Configure Instance Details page, leave the Network, Subnet, and Auto-assign Public IP settings with their default values and scroll down to the Advanced Details section.
- In the User data textbox under the Advanced Details section, enter the following text:
#!/bin/bash
sudo su
yum update -y
yum install -y httpd
systemctl start httpd.service
systemctl enable httpd.service
The Advanced Details section should look as follows:
- Click Next: Add Storage, leave the defaults as is, and click Next: Add Tags.
- Add a tag with Key set to Name and Value set to UserDataDemo. Click Next: Configure Security Group.
- Create a new security group with HTTP rules for everyone, and then SSH from our local IP.
- Click on Review and Launch and follow the onscreen instructions to complete the EC2 launch.
- Run the instance's public DNS name or public IP from a browser. We should get the default Test Page response from the Apache server:
We can SSH into the EC2 machine and run the following commands in order to set up a custom index.html file instead of the default landing page:
sudo su
cd /var/www/html
echo "<html><h1>My Web Server</h1></html>" > index.html
If we go back to the browser and refresh the page after making the preceding change, we should see the following output:
We can also create the index.html file with the EC2 user data itself.