How to loop on index

Hello everybody,

I’m a newbie and I need some help.

I want to loop on index to create or not some ecs resources on aws.

My module like this :

resource "aws_ecs_service" "this" {
  for_each = var.ecs_cluster_definitions.ecs_service
  name	= each.value.name
  cluster	= aws_ecs_cluster.ecs_cluster.arn
  platform_version = each.value.platform_version
  task_definition = each.value.task_definition
  ...
}

My main.tf on the principal code like this :

module "ecs" {
  source = "********"
  for_each = {
   for ecs_cluster_configuration in local.ecs_cluster_configuration:
    ecs_cluster_configuration.ecs_cluster_definition.ecs_cluster_name => 
    ecs_cluster_configuration
   }
   ecs_cluster_definitions = each.value.ecs_cluster_definition
  ....

Remark : ecs_cluster_definitions is a variable with type any

My local.tf like this :

ecs_cluster_configuration = [
    {
      ecs_cluster_definition = {
        ecs_cluster_name = "ecs-cluster-${local.nameattr3}"
        ecs_cluster_description = "ECS ${var.apps} ${var.Environment} ${var.Sub_Environment} 
       ${var.Domain}"
	  ecs_service = {
            "service1" = {
              name = "ecs-container-${var.Sub_Environment}-${var.apps}- 
              service1-${var.Domain}"
              platform_version = "LATEST"
              ....
             },
              "service2" = {
               ....
             },
              "service3" = {
               ....
             },
         }
    }
  }
]

My goal is to not create service2 for example if var.create_service value is false but create service1 and service3 if var.create_service is true.

If I understand “service1”, “service2” and “service3” are index. So I want to loop on this index to create or not the service

I test some code but it’s not resolve my issue.

Can you help me please ?

Thanks

Hi,

Do you think is it possible to have a condition to create or not resource “service2” ?

Thanks for your help

use the “count” property in resource and set the condition like “true ? 1:0” modify the conditions according to required logic.
**when count=0 resource will be skiped.