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

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

Problem Description:

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 "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"]


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

Solution – 1

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.

Solution – 2

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

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.