TerraformとCloudFormationを使用してセキュリティグループ間のトラフィックを許可する方法

# はじめに
この記事では、TerraformとCloudFormationを使用して、AWSのセキュリティグループ間でトラフィックを許可する方法を紹介します。具体的には、Application Load Balancer (ALB)、EC2インスタンス、およびRDSインスタンスの3つの異なるリソースに対するセキュリティグループを作成し、それらの間で適切なトラフィックを許可します。

# コードの概要
以下は、3つの異なるセキュリティグループ（ALB、EC2、RDS）とそれらのセキュリティグループ間のトラフィックを許可するためのルールを定義したコードです。主な要点は以下の通りです。
- 各セキュリティグループは指定されたVPC内に作成されます。
- ALBセキュリティグループはすべてのIPからポート80のトラフィックを許可します。
- EC2セキュリティグループはセルフインバウンド（同じセキュリティグループからのトラフィック）とALBセキュリティグループからのポート80のトラフィックを許可します。
- RDSセキュリティグループはセルフインバウンド（同じセキュリティグループからのトラフィック）とEC2セキュリティグループからのポート5432のトラフィックを許可します。

## Terraform

```terraform:variables.tf

variable "vpc_id" {
  description = "VPC ID where the security group will be created"
  type        = string
  default     = "vpc-0123456789abcdef0"  # Placeholder VPC ID, replace with your actual VPC ID
}

variable "alb_sg_name" {
  description = "Name of the security group for the ALB"
  type        = string
  default     = "alb_sg"
}

variable "rds_sg_name" {
  description = "Name of the security group for the rds"
  type        = string
  default     = "rds_sg"
}

variable "ec2_sg_name" {
  description = "Name of the security group for the EC2"
  type        = string
  default     = "ec2_sg"
}

```

```terraform:main.tf

#alb security group 
resource "aws_security_group" "alb_sg" {
  name        = var.alb_sg_name
  description = "Security group for ALB created by Terraform"
  vpc_id      = var.vpc_id

  tags = {
    Name = "alb_sg"
  }
}

resource "aws_vpc_security_group_ingress_rule" "alb_sg_ingress" {
  security_group_id = aws_security_group.alb_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 80 # Change to the appropriate range if needed
  to_port           = 80
  protocol          = "tcp"
}

resource "aws_vpc_security_group_egress_rule" "alb_sg_egress" {
  security_group_id = aws_security_group.alb_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 0
  to_port           = 0
  protocol          = "-1" # Allow inbound traffic from the same security group (self-ingress)
}



#ec2 security group 

resource "aws_security_group" "ec2_sg" {
  name        = var.ec2_sg_name
  description = "Security group for EC2 created by Terraform"
  vpc_id      = var.vpc_id

  tags = {
    Name = "ec2_sg"
  }
}

resource "aws_vpc_security_group_ingress_rule" "ec2_sg_ingress_all" {
  security_group_id = aws_security_group.ec2_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 0
  to_port           = 0
  protocol          = "-1"
}

resource "aws_vpc_security_group_ingress_rule" "ec2_sg_ingress_alb" {
  security_group_id     = aws_security_group.ec2_sg.id  
  security_group_source = aws_security_group.alb_sg.id  # Allow inbound traffic from ALB security group
  from_port             = 80                            # Change to the appropriate range if needed
  to_port               = 80
  protocol              = "tcp"
}

resource "aws_vpc_security_group_egress_rule" "ec2_sg_egress_all" {
  security_group_id = aws_security_group.ec2_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 0
  to_port           = 0
  protocol          = "-1" # Allow inbound traffic from the same security group (self-ingress)
}



#rds security group 
resource "aws_security_group" "rds_sg" {
  name        = var.rds_sg_name
  description = "Security group for rds created by Terraform"
  vpc_id      = var.vpc_id

  tags = {
    Name = "rds_sg"
  }
}

resource "aws_vpc_security_group_ingress_rule" "rds_sg_ingress_all" {
  security_group_id = aws_security_group.rds_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 0
  to_port           = 0
  protocol          = "-1"
}

resource "aws_vpc_security_group_ingress_rule" "rds_sg_ingress_alb" {
  security_group_id     = aws_security_group.rds_sg.id
  security_group_source = aws_security_group.ec2_sg.id # Allow inbound traffic from EC2 security group
  from_port             = 5432 # Change to the appropriate range if needed
  to_port               = 5432
  protocol              = "tcp"
}

resource "aws_vpc_security_group_egress_rule" "rds_sg_egress_all" {
  security_group_id = aws_security_group.rds_sg.id
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 0
  to_port           = 0
  protocol          = "-1" # Allow inbound traffic from the same security group (self-ingress)
}

```

```terraform:outputs.tf

output "alb_sg_id" {
  description = "ID of the created security group"
  value       = aws_security_group.alb_sg.id
}

output "alb_sg_name" {
  description = "Name of the created security group"
  value       = aws_security_group.alb_sg.name
}


output "ec2_sg_id" {
  description = "ID of the created security group"
  value       = aws_security_group.ec2_sg.id
}

output "ec2_sg_name" {
  description = "Name of the created security group"
  value       = aws_security_group.ec2_sg.name
}

output "rds_sg_id" {
  description = "ID of the created security group"
  value       = aws_security_group.rds_sg.id
}

output "rds_sg_name" {
  description = "Name of the created security group"
  value       = aws_security_group.rds_sg.name
}

```

## CloudFormation

```yaml:sgcfn.yaml

AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  VpcId:
    Type: String
    Description: VPC ID where the security group will be created
    Default: "vpc-0123456789abcdef0"  # Placeholder VPC ID, replace with your actual VPC ID

Resources:
  # ALB Security Group
  AlbSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: alb_sg
      Description: Security group for ALB created by CloudFormation
      VpcId: !Ref VpcId
      Tags:
        - Key: Name
          Value: alb_sg

  AlbSecurityGroupIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref AlbSecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 80
      ToPort: 80
      IpProtocol: tcp

  AlbSecurityGroupEgress:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref AlbSecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 0
      ToPort: 0
      IpProtocol: "-1"  # Allow inbound traffic from the same security group (self-ingress)

  # EC2 Security Group
  Ec2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: ec2_sg
      Description: Security group for EC2 created by CloudFormation
      VpcId: !Ref VpcId
      Tags:
        - Key: Name
          Value: ec2_sg

  Ec2SecurityGroupIngressAll:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref Ec2SecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 0
      ToPort: 0
      IpProtocol: "-1"

  Ec2SecurityGroupIngressAlb:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref Ec2SecurityGroup
      SourceSecurityGroupId: !GetAtt AlbSecurityGroup.GroupId
      FromPort: 80
      ToPort: 80
      IpProtocol: tcp

  Ec2SecurityGroupEgressAll:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref Ec2SecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 0
      ToPort: 0
      IpProtocol: "-1"  # Allow inbound traffic from the same security group (self-ingress)

  # RDS Security Group
  RdsSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: rds_sg
      Description: Security group for RDS created by CloudFormation
      VpcId: !Ref VpcId
      Tags:
        - Key: Name
          Value: rds_sg

  RdsSecurityGroupIngressAll:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref RdsSecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 0
      ToPort: 0
      IpProtocol: "-1"

  RdsSecurityGroupIngressEc2:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref RdsSecurityGroup
      SourceSecurityGroupId: !GetAtt Ec2SecurityGroup.GroupId
      FromPort: 5432
      ToPort: 5432
      IpProtocol: tcp

  RdsSecurityGroupEgressAll:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref RdsSecurityGroup
      CidrIp: 0.0.0.0/0
      FromPort: 0
      ToPort: 0
      IpProtocol: "-1"  # Allow inbound traffic from the same security group (self-ingress)

Outputs:
  AlbSecurityGroupId:
    Description: ID of the created security group
    Value: !GetAtt AlbSecurityGroup.GroupId

  AlbSecurityGroupName:
    Description: Name of the created security group
    Value: !GetAtt AlbSecurityGroup.GroupName

  Ec2SecurityGroupId:
    Description: ID of the created security group
    Value: !GetAtt Ec2SecurityGroup.GroupId

  Ec2SecurityGroupName:
    Description: Name of the created security group
    Value: !GetAtt Ec2SecurityGroup.GroupName

  RdsSecurityGroupId:
    Description: ID of the created security group
    Value: !GetAtt RdsSecurityGroup.GroupId

  RdsSecurityGroupName:
    Description: Name of the created security group
    Value: !GetAtt RdsSecurityGroup.GroupName


```


## まとめ
この記事では、TerraformとCloudFormationを使用して、AWSのセキュリティグループを効果的に作成し、それらのセキュリティグループ間でトラフィックを許可する方法を解説しました。必要に応じて変更や追加を行い、自分の環境に合わせてください。これにより、アプリケーションのセキュリティを強化