簡體   English   中英

如何在 terraform 中為安全組創建模塊

[英]How to create module for security group in terraform

我有這個資源來制作安全組並有幾個進入規則。

這些文件位於“security-group”文件夾中,因為我必須為它創建一個模塊。

主文件

resource "aws_security_group" "main" {
   name   = var.sg_name

   dynamic "ingress" {
       for_each = local.ingress_rules

       content {
           description = ingress.value.description
           from_port   = ingress.value.port
           to_port     = ingress.value.port
           protocol    = "tcp"
           cidr_blocks = ["0.0.0.0/0"]
       }
   }
}

變量.tf

locals {
   ingress_rules = [{
       port        = 443
       description = "Port 443"
   },
   {
       port        = 80
       description = "Port 80"
   }]
}

現在在 modules/security-group/ 文件夾之外,我有 main.tf 文件,我想在其中調用該模塊來創建安全組。

module "security_group" {
 source = "./modules/security-group"

   dynamic "ingress" {
       for_each = local.ingress_rules

       content {
           description = ingress.value.description
           from_port   = ingress.value.port
           to_port     = ingress.value.port
           protocol    = "tcp"
           cidr_blocks = ["0.0.0.0/0"]
       }
   }
}

│ Error: Unsupported block type
│
│   on main.tf line 29, in module "security_group":
│   29:         dynamic "ingress" {
│
│ Blocks of type "dynamic" are not expected here.
╵

我還能如何調用這個模塊來創建規則和其他必要的東西? 提前謝謝了

模塊沒有動態塊。 您必須將規則作為常規變量傳遞給模塊,而不是本地值:

variable "ingress_rules" {
  default = [{
       from_port   = 443
       to_port     = 443
       description = "Port 443"
   },
   {
       from_port   = 80
       to_port     = 80
       description = "Port 80"
   }]
}

resource "aws_security_group" "main" {
   name   = var.sg_name

   dynamic "ingress" {
       for_each = var.ingress_rules

       content {
           description = ingress.value.description
           from_port   = ingress.value.from_port   
           to_port     = ingress.value.to_port     
           protocol    = "tcp"
           cidr_blocks = ["0.0.0.0/0"]
       }
   }
}

然后在父文件夾中:

module "security_group" {
 source = "./modules/security-group"

 ingress_rules =    [
       {
           description =  "description"
           from_port   = 20
           to_port     = 20
           protocol    = "tcp"
           cidr_blocks = ["0.0.0.0/0"]
     }
   ] 
}

您必須修復所有這些屬性名稱 您不能只混合使用portto_port

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM