问题描述
我正在使用terraform将EC2实例部署到AWS。我正在使用EC2的用户数据部分来安装apache。
这是我的模板。
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"
}
如您所见,我正在运行一个shell脚本以在user_data部分中安装apache。这是我的install_apache.sh文件。
#!/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
如您所见,我已经为实例分配了一个现有的安全组。我的安全组在端口80上列出了针对入站规则的HTTP请求,如下所示。
然后我部署运行此命令的模板“ terraform apply”。
然后,我在浏览器上打开实例的公共IP地址。它只是保持加载状态,加载和加载显示空白屏幕。我的代码有什么问题,我该如何解决?
解决方法
您的脚本来自Amazon Linux1。对于AL2,它应该是:
#!/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
我添加了$(hostname -f)
作为增强功能。