如何使用 Terraform 添加或删除安全组的入口/出口规则? [英] How to append or delete the ingress/egress rule for a security group using Terraform?

查看:49
本文介绍了如何使用 Terraform 添加或删除安全组的入口/出口规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Terraform 中管理 AWS 安全组以编辑现有 SG 的规则?

Is there a way to manage AWS security Groups in Terraform to edit rules for an existing SG?

例如:如果我提供一个新实例,现有 SG 的入口规则会更新以允许新提供的实例.SG 也需要在实例终止时更新.

e.g: If I provision a new instance the ingress rules of an existing SG is updated to allow the newly provisioned instance. The SG also needs to update when an instance terminates.

如果 Terraform 没有直接支持,请随意建议其他常见做法.

Feel free to suggest other common practices if not directly supported via Terraform.

推荐答案

是的,您可以向现有安全组 (SG) 添加和删除单个规则.这可以分两步完成:

Yes, you can add and remove individual rules to existing security groups (SGs). This can be done in two steps:

  1. 使用 aws_security_group 获取现有 SG 的数据源:

data "aws_security_group" "selected" {
  id = <group-id-of-existing-sg>
}

  1. 创建 aws_security_group_rule 资源以添加新资源从步骤 1 向 SG 发送规则:
  1. Create aws_security_group_rule resource to add a new rule to the SG from step 1:

resource "aws_security_group_rule" "example" {
  type              = "ingress"
  from_port         = 0
  to_port           = 65535
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = data.aws_security_group.selected.id
}

如果您的实例是在与 SG 规则相同的 TF 文件中创建的,则在 terraform destroy 时,实例和规则都会被销毁.

If your instance is created in same TF file as the SG rule, upon terraform destroy both the instance and the rule will get destroyed.

这篇关于如何使用 Terraform 添加或删除安全组的入口/出口规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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