3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【AWS/Terraform】EC2でNginxサーバーを立ち上げる

Last updated at Posted at 2023-06-25

はじめに

この記事では、AWS上にEC2インスタンスを作成し、その上でNginxサーバーを立ち上げる方法を説明します。インフラストラクチャのコード化ツールであるTerraformを使用します。

環境

  • Terraform v1.0.0以上
  • AWSアカウント
  • AWS CLI設定済み(認証情報)

ディレクトリ構成

.
├── data.tf
├── main.tf
├── network.tf
├── nginx.tf
├── rds.tf
├── security_group.tf
├── src
│   ├── terraform-dev-keypair
│   └── terraform-dev-keypair.pub
├── terraform.tfstate
├── terraform.tfstate.backup
└── terraform.tfvars

Terraform設定ファイルの作成

VPCに関しては下記に記載しています。

セキュリティグループに関しては下記に記載しています。

data.tf
data "aws_prefix_list" "s3_pl" {
  name = "com.amazonaws.*.s3"
}

data "aws_ami" "web_server" {
  most_recent = true
  owners = ["self", "amazon"]
  filter {
    name = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
  filter {
    name = "root-device-type"
    values = ["ebs"]
  }
  filter {
    name = "virtualization-type"
    values = ["hvm"]
  }
}
nginx.tf
resource "aws_key_pair" "keypair" {
  key_name   = "my-keypair"
  public_key = file("./src/terraform-dev-keypair.pub")
  tags = {
    Name = "my-keypair"
  }
}

# Nginx EC2 instance
resource "aws_instance" "nginx" {
  ami                         = data.aws_ami.web_server.id
  instance_type               = "t2.micro"
  subnet_id                   = aws_subnet.public-subnet-elb-1a.id
  associate_public_ip_address = true
  vpc_security_group_ids      = [aws_security_group.dev_sg.id]

  key_name = aws_key_pair.keypair.key_name

  tags = {
    Name = "nginx"
  }

  user_data = <<-EOF
                #!/bin/bash
                sudo yum update -y
                sudo amazon-linux-extras install epel -y
                sudo yum install nginx -y
                sudo systemctl start nginx
                sudo systemctl enable nginx
              EOF
}

リソースの作成

terraform apply

これで、NginxがインストールされたEC2インスタンスが作成されます。
AWS Management Consoleから作成されたインスタンスを確認し、パブリックIPを取得してブラウザでアクセスるとデフォルトページが表示されます。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?