我想扩展实例 ec2 以获取从存储库中提取并存储在正确目录中的网页,以便 Nginx 正确提供服务。我写了 terraform 文件。
我制作的main.tf文件如下。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-east-1"
}
#vpc
resource "aws_vpc" "terraformVpc" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "vpc terraform made"
}
}
#subnet
resource "aws_subnet" "terraformSubnet" {
vpc_id = aws_vpc.terraformVpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "subnet1 terraform made"
}
}
#internet gateway
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.terraformVpc.id
tags = {
Name = "internetGateway terraform made"
}
}
#route table
resource "aws_route_table" "rt" {
vpc_id = aws_vpc.terraformVpc.id
tags = {
Name = "route table terraform made"
}
}
#route
resource "aws_route" "default_route" {
route_table_id = aws_route_table.rt.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
#route table association
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.terraformSubnet.id
route_table_id = aws_route_table.rt.id
}
#security group
resource "aws_security_group" "websg" {
name = "websg"
description = "terraform security group"
vpc_id = aws_vpc.terraformVpc.id
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "websg"
}
}
resource "aws_instance" "ec2" {
ami = "ami-080e1f13689e07408"
instance_type = "t2.micro"
subnet_id = aws_subnet.terraformSubnet.id
vpc_security_group_ids = [aws_security_group.websg.id]
associate_public_ip_address = true
key_name = "ec2instance"
user_data = templatefile("${path.module}/user_data.sh", {
instance_name = "MyEC2Instance"
})
provisioner "remote-exec" {
inline = [
"sudo apt-get update -y",
"sudo apt-get install -y git npm",
"git clone https://gitlab.com/sealy/simple-webapp.git",
"cd simple-webapp",
"npm install",
"npm run build",
"sudo mv dist/. /var/www/html/",
"sudo systemctl restart nginx"
]
}
tags = {
Name = "instance terraform made"
}
}
并且 user_data.sh 如下。
#!/bin/bash
echo "Welcome to ${instance_name}"
# # Update the package list
sudo apt-get update -y
# # Install Nginx
sudo apt-get install nginx -y
# # Start Nginx
sudo systemctl start nginx
# # Enable Nginx to start on boot
sudo systemctl enable nginx
从aws ec2角落,我可以看到实例创建成功。 当我通过公共 IP 地址连接实例时,我不需要基本的 nginx 页面。 当我通过公共 IP 地址时,我想要 https://gitlab.com/sealy/simple-webapp 这个构建产品。但它一直显示基本的 nginx 页面。 我应该在 main.tf 文件的配置部分(位于实例部分)中编辑什么?
问题似乎出在
npm run build
。那里没有可用的构建选项。如果您尝试加载一个简单的页面,请在 maint.tf 中使用以下 2 个命令,而不是 simple-webapp:
echo "<html><body><p><b>Welcome to page</b></p></body></html>" >> index.html
sudo mv index.html /var/www/html/
sudo systemctl restart nginx