bashamazon-web-servicesamazon-ec2terraformuser-data

Why is userdata not working in my Terraform code?


I am working with Terraform and trying to execute bash script using user date. Below is my code:

    resource "aws_instance" "web_server" {
  ami           = var.centos
  instance_type = var.instance-type
  subnet_id     = aws_subnet.private.id
  private_ip    = var.web-private-ip
  associate_public_ip_address = true

  user_data = <<-EOF
          #!/bin/bash 
          yum install httpd -y
          echo "hello world" > /var/www/html/index.html
          yum update -y
          systemctl start httpd
          firewall-cmd --zone=public --permanent --add-service=http
          firewall-cmd --zone=public --permanent --add-service=https
          firewall-cmd --reload
          EOF
}

However, when I navigate to the public IP I do not see the "hello world" message and also do not get a response fron the server. Is there something I am missing here? I've tried going straight through the aws console and user data is unsuccesful there to.


Solution

  • I verified your user data on my centos instance and your script is correct. However, the issue is probably because of two things:

    1. subnet_id = aws_subnet.private.id this suggest that you've placed your instance in a private subnet. To connect to your instance form internet, it must be in public subnet

    2. there is no vpc_security_group_ids specified, which leads to using a default SG from the VPC, which has internet traffic blocked by default.

    Also I'm not sure what do you want to do with private_ip = var.web-private-ip. Its confusing.