简体   繁体   English

Terraform - 为安全组迭代并创建入口规则

[英]Terraform - Iterate and create Ingress Rules for a Security Group

I've been writing reusable modules for an AWS infrastructure.我一直在为 AWS 基础设施编写可重用的模块。 In creating a security group, my approach is to create a generic module for a security group and provide a list of ports in the control code.在创建安全组时,我的方法是为安全组创建一个通用模块并在控制代码中提供端口列表。 However, when using count it creates a security group each for every port.但是,当使用count它会为每个端口创建一个安全组。 Is there a way around this to iterate a specific part like in this scenario?有没有办法像在这种情况下那样迭代特定部分?

SG Module SG模块

resource "aws_security_group" "this" {
  name        = var.sg_name
  description = var.description
  vpc_id      = var.vpc_id

  count = min(length(var.ingress_ports))
  ingress {
    from_port   = var.ingress_ports[count.index]
    to_port     = var.ingress_ports[count.index]
    protocol    = "tcp"
    cidr_blocks = ["10.0.0.0/8"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
}

Control Code控制代码

module "qliksense_sg" {
  source = "modules/aws-sg"

  sg_name = "My-SG"
  description = "A security group"
  vpc_id = module.vpc.vpc_id

  ingress_ports = ["80", "443"]
}

To do this in Terraform 0.12 you can use dynamic blocks .要在 Terraform 0.12 中做到这一点,您可以使用dynamic In fact, the example given in that documentation link is for adding ingress rules over a list of ports:事实上,该文档链接中给出的示例用于在端口列表上添加入口规则:

resource "aws_security_group" "example" {
  name = "example" # can use expressions here

  dynamic "ingress" {
    for_each = var.service_ports
    content {
      from_port = ingress.value
      to_port   = ingress.value
      protocol  = "tcp"
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Terraform:成功创建资源(aws_security_group),但它采用来自所有给定安全组的入口/出口规则 - Terraform: create resource(aws_security_group) successfully but it takes ingress/egress rules from all given security groups 撤销所有 AWS 安全组入口规则 - Revoke all AWS security group ingress rules 云形成安全组未创建入口规则 - Cloud formation security group is not creating ingress rules Terraform for 循环生成安全组规则 - Terraform for loop to generate security group rules Terraform 创建的安全组没有规则 - Security group created by Terraform has no rules 撤销所有安全组入口规则(与源安全组) - Revoke all security group ingress rules (with source security groups) Terraform:ingress_with_source_security_group_id 与 computed_ingress_with_source_security_group_id - Terraform: ingress_with_source_security_group_id vs. computed_ingress_with_source_security_group_id 我应该如何使用 terraform 在入口安全组中定义范围? - How should I define ranges in ingress security group using terraform? 如何使用 append 或删除安全组的入口/出口规则 Terraform? - How to append or delete the ingress/egress rule for a security group using Terraform? aws ec2 revoke-security-group-ingress 不删除规则 - aws ec2 revoke-security-group-ingress not deleting rules
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM