EVENT
EC2を作成していく
SOLUTION
前回の続き
EC2とは
AWSクラウド上の仮想サーバー
使用したリソース
- aws_security_group
対象リソースに対しての出入り口設定を行う
フォルダ構成
- /main.tf
resource "aws_instance" "main" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = [var.security_group_id]
key_name = var.key_pair_name
# パブリックサブネットに配置する場合
associate_public_ip_address = var.associate_public_ip
tags = {
name = "${var.project_name}-${var.environment}-ec2-instance"
environment = var.environment
}
}
- /outputs.tf
output "instance_id" {
description = "The ID of the EC2 instance."
value = aws_instance.main.id
}
output "private_ip" {
description = "The private IP address of the EC2 instance."
value = aws_instance.main.private_ip
}
output "public_ip" {
description = "The public IP address of the EC2 instance (if associated)."
value = aws_instance.main.public_ip
}
- /variables.tf
variable "project_name" {
description = "Project name tag."
type = string
}
variable "environment" {
description = "Deployment environment (e.g., dev, prd)."
type = string
}
variable "ami_id" {
description = "The AMI ID for the EC2 instance."
type = string
}
variable "instance_type" {
description = "The instance type for the EC2 instance."
type = string
}
variable "subnet_id" {
description = "The ID of the subnet to launch the EC2 instance in."
type = string
}
variable "security_group_id" {
description = "The ID of the security group to attach to the EC2 instance."
type = string
}
variable "key_pair_name" {
description = "The name of the EC2 Key Pair."
type = string
}
variable "associate_public_ip" {
description = "Whether to associate a public IP address with the instance."
type = bool
default = false
}
- ~/dev/main.tf
module "ec2" {
source = "../../modules/ec2"
project_name = var.project_name
environment = "dev"
ami_id = "ami-04158184f60ea8b5e"
instance_type = "t2.micro"
subnet_id = module.vpc.public_subnet_ids[0] # パブリックサブネットに配置
security_group_id = module.security_group.ec2_security_group_id
key_pair_name = "test-keypair"
associate_public_ip = true # パブリックIPを割り当てる
}
- ~/dev/outputs.tf
output "ec2_public_ip" {
value = module.ec2.public_ip
}
- 動作確認
コンソール確認は省いて、EC2-RDSへの接続確認をしました。