Amazon-Web-Services

如何使用 terraform 預定義 AWS 安全組 ID

  • November 26, 2019

此腳本適用於創建 EC2 實例:

provider "aws" {
 access_key = "ACCESS_KEY"
 secret_key = "SECRET-KEY"
 region     = "us-east-2"
}

resource "aws_instance" "web" {
 count = 3
 ami           = "ami-001as38b07206d4ceaf"
 instance_type = "t2.micro"
 key_name   = "labkey"
 vpc_security_group_ids = [ "sg-341233f1856" ]
}

現在我正在嘗試創建一個安全組。該腳本工作正常,但是我在創建安全組時找不到如何預定義“vpc_security_group_ids”

resource "aws_security_group" "Testlab_VPC_Security_Group" {
 vpc_id       = aws_vpc.Testlab_VPC.id
 name         = "Testlab VPC Security Group"
 description  = "Testlab VPC Security Group"
 ingress {
   cidr_blocks = var.ingressCIDRblock
   from_port   = 22
   to_port     = 22
   protocol    = "tcp"
 }
 ingress {
   cidr_blocks = var.ingressCIDRblock
   from_port   = 80
   to_port     = 80
   protocol    = "tcp"
 }
 egress {
   from_port   = 0
   to_port     = 0
   protocol    = "-1"
   cidr_blocks = ["0.0.0.0/0"]
 }
tags = {
  Name = "Testlab VPC Security Group"
  Description = "Testlab VPC Security Group"
}
}

我希望能夠結合這兩個腳本。

是否有另一種方法可以使用我缺少的 terraform 添加安全性?

試試這個

resource "aws_instance" "web" {
 count = 3
 ami           = "ami-001as38b07206d4ceaf"
 instance_type = "t2.micro"
 key_name   = "labkey"
 vpc_security_group_ids = [ aws_security_group.Testlab_VPC_Security_Group.id ]
}

因為這個表達式指的是安全組,Terraform 可以自動推斷必須首先創建安全組。

引用自:https://serverfault.com/questions/993377