在 terraform/aws/global/vpc/security_groups.tf 我有下面的代码来创建我的堡垒安全组,以及下面的 output.tf 文件。但是在 terraform/aws/layers/bastion/main.tf (代码也在下面)中,我引用了该安全组,因为我需要它的安全组 ID 来创建我的 EC2 实例,我遇到的问题是,而不是从已经由 /vpc/security_groups.tf 配置创建的现有安全组它尝试创建整个安全组并且运行显然失败,因为它已经存在。如何更改我的代码以获取现有 SG 的 ID?我不想在与我的实例相同的配置文件中创建我的 SG,我的一些安全组在不同资源之间共享。我正在使用 Terraform Cloud,VPC 有自己的工作区,
terraform/aws/global/vpc/security_groups.tf
provider "aws" {
region = "eu-west-1"
}
resource "aws_security_group" "bastion" {
name = "Bastion_Terraform"
description = "Bastion SSH access Terraform"
vpc_id = "vpc-12345"
ingress {
description = "Bastion SSH"
from_port = ##
to_port = ##
protocol = "##"
cidr_blocks = ["1.2.3.4/56"]
}
ingress {
description = "Bastion SSH"
from_port = ##
to_port = ##
protocol = "##"
cidr_blocks = ["1.2.3.4/0"]
}
egress {
description = "Access to "
from_port = ##
to_port = ##
protocol = "tcp"
security_groups = ["sg-12345"]
}
egress {
description = "Access to ##"
from_port = ##
to_port = ##
protocol = "tcp"
security_groups = ["sg-12345"]
}
tags = {
Name = "Bastion Terraform"
}
}
terraform/aws/global/vpc/outputs.tf
output "bastion-sg" {
value = aws_security_group.bastion.id
}
terraform/aws/layers/bastion/main.tf
provider "aws" {
region = var.region
}
module "vpc" {
source = "../../global/vpc"
}
module "ec2-instance" {
source = "terraform-aws-modules/ec2-instance/aws"
name = "bastion"
instance_count = 1
ami = var.image_id
instance_type = var.instance_type
vpc_security_group_ids = ["${module.vpc.bastion-sg}"]
subnet_id = var.subnet
iam_instance_profile = var.iam_role
tags = {
Layer = "Bastion"
}
}