LoginSignup
31
14

More than 3 years have passed since last update.

Terraformで1つのセキュリティグループに複数のルールを設定する

Last updated at Posted at 2019-09-23

やりたいこと

下記画像のように、1つのセキュリティグループに対して2つ以上のルールを設定する。
これをTerraformでやりたい。
スクリーンショット 2019-09-23 21.27.32.png

例えば、Webサーバー用のセキュリティグループを作成し、80番ポートと443番ポートへのインバウンドを設定するなどといったことである。

Terraform実装

aws_security_groupを書く

まずは1つのセキュリティグループに対し、80番ポートへのインバウンドルールを追加してみよう。
下記のように、 aws_security_group の中に ingress を指定することで、セキュリティグループとインバウンドルールを作成できる。

security_group.tf
# web_serverというセキュリティグループを作成し、そこに80番ポートのインバウンドルールを追加する
resource "aws_security_group" "web_server_sg" {
  name        = "web_server"
  description = "Allow http and https traffic."
  vpc_id      = "xxxxx" # デフォルトvpcのID

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = [
      "0.0.0.0/0"
    ]
  }
}

さらに web_server セキュリティグループに対して、443番ポートへのインバウンドルールも追加してみよう。
上で書いた web_server_sg にもう一つ ingress を追加したら良いんじゃない?となるだろう。
下記のような感じ。

security_group.tf
resource "aws_security_group" "web_server_sg" {
  name        = "web_server"
  description = "Allow http and https traffic."
  vpc_id      = "xxxxx" # デフォルトvpcのID

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = [
      "0.0.0.0/0"
    ]
  }

  # このように、2つ目のingressを書きたい
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [
      "0.0.0.0/0"
    ]
  }
}

しかし、 このやり方だとエラーになってしまう
1つの aws_security_group の中に ingress は1つしか書けないのである。

aws_security_group_ruleを使おう

もちろん「Terraformを使うときには1つのセキュリティグループに対して1つのルールしか設定できない」という制約はなく、解決策はバッチリ用意されている。
aws_security_group_rule リソースを使おう。

今回の場合だと、下記のように書く。

security_group.tf
resource "aws_security_group" "web_server_sg" {
  name        = "web_server"
  description = "Allow http and https traffic."
  vpc_id      = "xxxxx" # デフォルトvpcのID
  # ここにingressを書かず、ルールはaws_security_group_ruleを使って定義する
}

# 80番ポート許可のインバウンドルール
resource "aws_security_group_rule" "inbound_http" {
  type        = "ingress"
  from_port   = 80
  to_port     = 80
  protocol    = "tcp"
  cidr_blocks = [
    "0.0.0.0/0"
  ]

  # ここでweb_serverセキュリティグループに紐付け
  security_group_id = "${aws_security_group.web_server_sg.id}"
}

# 443番ポート許可のインバウンドルール
resource "aws_security_group_rule" "inbound_https" {
  type        = "ingress"
  from_port   = 443
  to_port     = 443
  protocol    = "tcp"
  cidr_blocks = [
    "0.0.0.0/0"
  ]

  # ここでweb_serverセキュリティグループに紐付け
  security_group_id = "${aws_security_group.web_server_sg.id}"
}

このように aws_security_group_rule を使い、web_serverセキュリティグループに紐付けたいルールを2つ作成する。
それらのルールの中で「どのセキュリティグループに紐付けるか」を指定する。
もっと多くのインバウンドルールやアウトバウンドルールを作成したい場合は、同じように aws_security_group_rule を増やしていくだけである。

こうすることで、Terraformを使用し、1つのセキュリティグループに対して2つ以上のルールを設定することができる。

公式サイト

31
14
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
31
14