I am deploying an EC2 instance to AWS using terraform. I am using user data section of EC2 to install apache.

This is my template.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

provider "aws" {
  region  = "eu-west-1"
  access_key = "xxxxxxxxx"
  secret_key = "xxxxxxxxx"
}

resource "aws_instance" "myinstance" {
  ami           = "ami-047bb4163c506cd98"
  instance_type = "t2.micro"
  tags = {
    Name = "My first terraform instance"
  }
  vpc_security_group_ids = [ "sg-0721b555cc402a3ad" ]
  user_data = "${file("install_apache.sh")}"
  key_name = "MyKey"
}

As you can see, I am running a shell script to install apache in the user_data section. This is my install_apache.sh file.

#!/bin/bash -xe
cd /tmp
yum update -y
yum install -y httpd24
echo "Hello from the EC2 instance." > /var/www/html/index.html
sudo -u root service httpd start

As you can see, I have assigned an existing security group to the instance. My security group white list the HTTP request on port 80 for inbound rules as follow.

enter image description here

Then I deploy the template running this command, "terraform apply".

Then I open the public IP address of the instance on the browser. It just keeps loading, loading and loading showing the blank screen. What is wrong with my code and how can I fix it?

1

There are 1 best solutions below

9
On

Your script is form Amazon Linux 1. For AL2 it should be:

#!/bin/bash -xe
cd /tmp
yum update -y
yum install -y httpd
echo "Hello from the EC2 instance $(hostname -f)." > /var/www/html/index.html
systemctl start httpd

I added $(hostname -f) as enhancement.