1
votes

I'm trying to write a Terraform module for AWS Security Groups with the dynamic block, but I'm having this error:

│ 
│   on main.tf line 17, in module "security_group":
│   17:     ingress = {
│ 
│ The argument "ingress" was already set at main.tf:8,5-12. Each argument may be set only once.

I've followed the documentation but I'm still having the error I'm using Terraform 0.15.1 and AWS provider version 3.38.0

Here is my code

./modules/security_group/main.tf

resource "aws_security_group" "main" {
   .......

  dynamic "ingress" {
    for_each = var.ingress
    content {
      description      = ingress.value["description"]
      from_port        = ingress.value["from_port"]
      to_port          = ingress.value["to_port"]
      protocol         = ingress.value["protocol"]
      cidr_blocks      = ingress.value["cidr_blocks"]
      ipv6_cidr_blocks = ingress.value["ipv6_cidr_blocks"]
    }
  
  }
  .......

}

./modules/security_group/variables.tf

variable "ingress" {
  description = ""
  type        = object({
    description = string
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
    ipv6_cidr_blocks = list(string)
  })
  default     = {
    description      = ""
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = []
    ipv6_cidr_blocks = []
  }
}

./main.tf

module "security_group" {
    source = "./modules/security_group"

    name        = "${var.project}-sg"
    description = "security group testing"
    vpc_id      = "my-vpc"
    ingress = {
        description = ""
        from_port = 22
        to_port   = 22
        protocol  = "tcp"
        cidr_blocks = []
        ipv6_cidr_blocks = []
    }
    ingress = {
        description = ""
        from_port = 80
        to_port   = 80
        protocol  = "tcp"
        cidr_blocks = []
        ipv6_cidr_blocks = []
    }

}
1

1 Answers

1
votes

You have ingress arguments. I think you want to have one as a list:

variable "ingress" {
  description = ""
  type        = list(object({
    description = string
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
    ipv6_cidr_blocks = list(string)
  }))
  default     = [{
    description      = ""
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = []
    ipv6_cidr_blocks = []
  }
}]


module "security_group" {
    source = "./modules/security_group"

    name        = "${var.project}-sg"
    description = "security group testing"
    vpc_id      = "my-vpc"
    ingress = [{
        description = ""
        from_port = 22
        to_port   = 22
        protocol  = "tcp"
        cidr_blocks = []
        ipv6_cidr_blocks = []
       }, {
        description = ""
        from_port = 80
        to_port   = 80
        protocol  = "tcp"
        cidr_blocks = []
        ipv6_cidr_blocks = []
    }]

}