Terraform AWS-EC2 보안 그룹

Dec 29 2020

나는 Terraform에 대해 더 많이 배우려고 매우 바쁘지만 해결 방법 / 수정 방법에 대한 단서가없는 한 가지 문제가 있습니다.

문제는 다음과 같습니다. 스크립트에서 en EIP와 같은 몇 가지 측면과 모듈의 보안 그룹이있는 ec2 인스턴스 (AWS)를 생성하고 있는데 모두 정상적으로 작동합니다. 하지만 보안 그룹을 머신에 연결하는 방법을 알 수 없습니다. 이제 생성되고 있습니다.

코드는 다음과 같습니다.

data "aws_ami" "latest" {
  most_recent = true
  owners = [ "self"] 

    filter {
      name = "name"
      values = [ lookup(var.default_ami, var.ami) ]
    }
}

module "aws_security_group" {
  source = "./modules/services/Security groups/"
  server_port = 443
}

resource "aws_instance" "test-ec2deployment" {
  ami                           = data.aws_ami.latest.id
  instance_type                 = var.instance_type
  subnet_id                     = var.subnet_id
  availability_zone             = var.availability_zone
  associate_public_ip_address   = var.public_ip
  
  root_block_device {
    volume_type                 = "gp2"
    volume_size                 = 60
    delete_on_termination       = true
  }
  
   tags = {
    Name                        = "Testserver2viaTerraform"
  }
}

resource "aws_eip" "ip" {
  instance = aws_instance.test-ec2deployment.id
}

resource "aws_eip" "example" {
  vpc = true
}

위는 기본 파일이며 다음 모듈을로드하고 있습니다.

resource "aws_security_group" "my-webserver" {
  name        = "webserver"
  description = "Allow HTTP from Anywhere"
  vpc_id      = "vpc-"
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
  tags = {
    Name = "my-webserver"
    Site = "my-web-site"
  }
}

마지막 단계는 보안 그룹을 컴퓨터에 연결하는 것이지만 다시 한 번 그 방법에 대한 단서가 없습니다. 여러 문서를 읽고 Google을 시도했지만 답변을 찾을 수 없거나 답변이 작동하지 않습니다. 그러니 여러분이 저를 더 도울 수 있기를 바랍니다.

시간 내 주셔서 감사합니다.

답변

3 AsriBadlah Dec 29 2020 at 21:05

aws_security_group 모듈에서 ./modules/services/Security groups // main.tf에 다음을 추가하여 보안 그룹 ID를 출력해야합니다.

output "securitygroup_id" {
  value = aws_security_group.my-webserver.id
}

그런 다음 기본 tf 파일에서 다음과 같이 보안 그룹을 인스턴스에 연결합니다.

resource "aws_network_interface_sg_attachment" "sg_attachment" {
  security_group_id    = module.aws_security_group.securitygroup_id
  network_interface_id = aws_instance.test-ec2deployment.primary_network_interface_id
}