terramate-io / terramate

Terramate CLI is an open-source Infrastructure as Code (IaC) Orchestration and Code Generation tool for Terraform, OpenTofu and Terragrunt.
https://terramate.io
Mozilla Public License 2.0
3.28k stars 92 forks source link

[BUG] `terramate generate` doesn't honor the `--tags` option #1844

Open n-my opened 3 months ago

n-my commented 3 months ago

Describe the bug

To Reproduce

Create 2 stacks, only one with a tag

terramate create stacks/vpc --tags aws
terramate create stacks/vpc2

Add the code generate file stacks/main.tm.hcl with the content

generate_hcl "_generate_main.tf" {
  content {
    resource "aws_vpc" "main" {
      cidr_block = "10.0.0.0/16"
    }
  }
}

Run the generate command only on the 1st stack using the --tags option

terramate generate --tags aws

Expected behavior

I would expect the code generation to be applied only to the 1st stack and not to all. The help page of the terramate generate commands indicates that it supports the --tags=TAGS option to filter stacks by tags.

Log Output

The code generation runs for all stacks

Code generation report
Successes:
- /stacks/vpc
    [+] _generate_main.tf
- /stacks/vpc2
    [+] _generate_main.tf

Environment (please complete the following information):

bart-braidwell commented 2 months ago

It works opposite way, you need to make condition in your template to generate only on stacks with tag aws

generate_hcl "_generate_main.tf" {
  condition = tm_contains(terramate.stack.tags, "aws")

  content {
    resource "aws_vpc" "main" {
      cidr_block = "10.0.0.0/16"
    }
  }
}

then your terramate generate will work

soerenmartius commented 2 months ago

It works opposite way, you need to make condition in your template to generate only on stacks with tag aws

generate_hcl "_generate_main.tf" {
  condition = tm_contains(terramate.stack.tags, "aws")

  content {
    resource "aws_vpc" "main" {
      cidr_block = "10.0.0.0/16"
    }
  }
}

then your terramate generate will work

Thanks for answering this @bart-braidwell, I actually only saw this now. In addition to condition you can also use stack_filter such as repository_paths and project_paths.

This is pretty well documented in https://terramate.io/docs/cli/code-generation/generate-hcl

In addition to that, the code generation always run on the entire repository / Terramate project to prevent inconsistencies as there are plenty of factors that impact generated files such as globals, locals, etc. Partial code generation is not a good idea.