简体   繁体   中英

dynamic variable-values-in-terraform-for-aws-security-groups

Hi am working terraform code where am creating eks cluster and rds with security group for rds ad cluster also in rds security group am using dynamic method create ingress in that some using cidr some of security group am able to create cidr am stuck at security groupa

variable.tf
variable "ingress_rules" {
  default     = {
    "indian vpn ingress rule" = {
      "description" = "India  CIDR"
      "from_port"   = "1521"
      "to_port"     = "1521"
      "protocol"    = "tcp"
      "cidr_blocks" = ["192.34.890.0/24"]
    },
   "eks node ingress rule" = {
      "description" = "EKS Nodes SG"
      "from_port"   = "1521"
      "to_port"     = "1521"
      "protocol"    = "tcp"
      "security_groups" = ["module.eks.worker_security_group_id"]
    }

mani.tf

esource "aws_security_group" "rds_sg" {
    name    = "${var.cluster_name}-rds-sg"
    vpc_id  = var.vpc_id
    
    dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      description      = lookup(ingress.value, "description", null)
      from_port        = lookup(ingress.value, "from_port", null)
      to_port          = lookup(ingress.value, "to_port", null)
      protocol         = lookup(ingress.value, "protocol", null)
      cidr_blocks      = lookup(ingress.value, "cidr_blocks", null)
      security_groups  = lookup(ingress.value, "security_groups", null)
    }
  }

How to define ["module.eks.worker_security_group_id"] in varibale tf my eks module define in main.tf

You can't do that. TF does not support dynamic variables. The only thing you can do is to use locals instead. In local variables you can use dynamic content.

I think there is a misunderstanding on the differences between input variables and local variables here.

input variables, can have a default value if not value is provided but they must be static.

local variables can be dynamic.

So, for your case, since the "ingress_rules" has already been defined and it is not going to change, but it must be build dynamically, it would be better to build it inside the "locals" block.

locals {
  ingress_rules = {
    ***
    ***
  }
}

To access it, use local.ingress_rules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM