LoginSignup
10
1

More than 1 year has passed since last update.

Terraformでセキュリティグループを設定してEC2にhttp接続する

Posted at

はじめに

Terraformの勉強を始めたので備忘録を兼ねて行ったことを投稿しようと思います。
これは前回の投稿の続きです。
前回の投稿ではTerraformでIAMを設定してEC2にセッションマネージャー経由で接続しました。
今回はhttp接続できるようにセキュリティグループをTerraformで設定します。
※EC2にはセッションマネージャー経由で接続できるので、予めnginxをインストールして起動しておきます

Terraformでセキュリティグループの定義を行う

http接続用のセキュリティグループを定義

http接続できるようにセキュリティグループを定義します。

securitygroup.tf
resource "aws_security_group" "test" {
  name = "tf_test"

  tags = {
    Name = "tf_test"
  }
}

resource "aws_security_group_rule" "ingress_http" {
  type              = "ingress"
  from_port         = 80
  to_port           = 80
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.test.id
}

resource "aws_security_group_rule" "egress_all" {
  type              = "egress"
  from_port         = 0
  to_port           = 0
  protocol          = "all"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.test.id
}

EC2に定義したセキュリティグループを設定

前回作成したec2.tfに定義したセキュリティグループを追加してhttp接続を許可します。

ec2.tf
resource "aws_instance" "test" {
  ami           = "ami-0404778e217f54308"
  instance_type = "t3.micro"

  iam_instance_profile = aws_iam_instance_profile.test.name

  # 以下を追加
  vpc_security_group_ids = [
    aws_security_group.test.id
  ]

  tags = {
    Name = "tf_test"
  }
}

Terraformで定義したセキュリティグループを追加してEC2を作成

Terraformのplan applyを実行

前回と同様、terraformのplan applyを実行して、AWS上にリソースを作成します。

terraform plan
terraform apply

http接続を行う

問題なければ、EC2のパブリックIPをもとにhttp接続するとnginxのページが表示されます。

作成したリソースの削除

前回と同様、terraformのdestroyを実行して、AWS上のリソースを削除します。

terraform destroy

さいごに

今回は作成したEC2にhttp接続する為のセキュリティグループの定義を行いました。
まだまだ実運用するにはいろんな設定が足りないですが、最低限、作成したEC2にhttp接続ができるところまではTerraformで実現できるようになりました。
この調子でTerraformで少しずつ設定できるAWSサービスを増やしていこうと思います。

10
1
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
10
1