如何创建一个AWS安全组并在不同的.tf文件中使用它? [英] How do I create a AWS security group and use it in different .tf files?

查看:217
本文介绍了如何创建一个AWS安全组并在不同的.tf文件中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,如果我使用terraform/aws/layers/bastion/main.tf创建EC2实例,我知道我也可以在该堡垒实例的同一main.tf文件中创建一个安全组.使用,但是如果我想创建可以在其他文件中使用的安全组怎么办?

As the title says, if I'm using terraform/aws/layers/bastion/main.tf to create an EC2 instance, I know I can also create a security group within this same main.tf file for the bastion instance to use, but what if I wanted to create a security group that can be used in a different file?

例如,如果terraform/aws/layers/worker/main.tf需要使用与bastion/main.tf相同的安全组,我将如何处理?

For example, if terraform/aws/layers/worker/main.tf needed to use the same security group as bastion/main.tf how would I go about this?

bastion/main.tf

provider "aws" {
    region = var.region
}

resource "aws_instance" "bastion" {
  name                   = "bastion"
  ami                    = var.image_id
  instance_type          = var.instance_type
  vpc_security_group_ids = [aws_security_group.bastion.id]
  subnet_id              = var.subnet
  iam_instance_profile   = "aws-example-ec2-role"

  tags = {
    Layer = "Bastion"
  }
}

resource "aws_security_group" "bastion_from_ssh" {
  name        = "Bastion"
  description = "Bastion example group"
  vpc_id      = "vpc-12345"
}

resource "aws_security_group_rule" "allow_ssh" {
  from_port   = ##
  to_port     = ##
  protocol    = "##"
  description = "Bastion SSH"
  cidr_blocks = ["1.2.3.4/5"]
}

resource "aws_security_group_rule" "bastion_to_db" {
  from_port                = ##
  to_port                  = ##
  protocol                 = "##"
  description              = "Access to default server security group"
  source_security_group_id = "sg-12345"
}

推荐答案

您可以使用模块"将共享资源分组在一起,然后从您的.tf文件中调用它们.

You can use "modules" to group together shared resources and then call them from your .tf file.

如果可行,另一种替代方法是在生成所需安全组的.tf文件中,输出其所需属性(例如ID).使用S3后端存储此堆栈的tfstate.现在,在需要此安全组的其他堆栈中,使用tfstate作为数据来获取该安全组的ID.

Another alternative is, if feasible, in .tf file where required Security Group is generated, output its required attributes such as ID. Use S3 backend to store the tfstate of this stack. Now, in other stacks where this Security Group is required, use the tfstate as Data to fetch the ID of that Security Group.

这篇关于如何创建一个AWS安全组并在不同的.tf文件中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆