0
0

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 3 years have passed since last update.

[Terraform] cidrsubnetを使ったときの参照

Posted at

はじめに

cidrsubnetを使ってsubnetを作ったときにどのように参照するかいつも忘れるのでメモ。

  • インデックスを使う参照
  • listにする参照

サブネットの記載

vpcのCIDRブロックからAZ数だけ/24で取ってくる記載。
AWSの場合はコピペでいけると思う。(きっと)

data "aws_availability_zones" "available" {}

resource "aws_subnet" "private" {
  count             = var.az_count
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]
  vpc_id            = aws_vpc.main.id
}

参照方法

aws_security_groupのcidr_blocksでいつも迷うので、サンプル記載する。

インデックスを使う参照

数分だけベタ書き。これでは変更されたとき気づけないので微妙。

resource "aws_security_group" "rds-sg" {
  name        = "mysql-rds-sg"
  description = "MySQL security group"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "tcp"
+   cidr_blocks = [aws_subnet.private[0].cidr_block,aws_subnet.private[1].cidr_block]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "example-rds-sg"
  }
}

listにする参照

これをいつも忘れる。

resource "aws_security_group" "rds-sg" {
  name        = "mysql-rds-sg"
  description = "MySQL security group"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "tcp"
+   cidr_blocks = [ for cb in aws_subnet.private[*].cidr_block : cb ]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "example-rds-sg"
  }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?