Mastering Resource Management: An In-depth Guide to Tagging in Terraform

In Terraform, you can't directly apply resources based on tags, as terraform apply is designed to enforce the configurations as defined in your Terraform files. However, you can structure your configurations and workflows to achieve a similar outcome. Here are some methods to consider:

1. Organizing Resources by Modules and Workspaces

Modules

You can use modules to group related resources together. Then, in your root configuration, you can include or exclude these modules as required.

module "tagged_resources" {
  source = "./modules/tagged_resources"
  ...
}

By commenting out or including the module in your configuration, you can determine which resources are applied.

Workspaces

Another approach is to use different workspaces for different sets of resources.

terraform workspace new mytag

Switch between workspaces:

terraform workspace select mytag

Then, in your configuration, you can use the terraform.workspace interpolation:

resource "aws_instance" "example" {
  count = terraform.workspace == "mytag" ? 1 : 0
  ...
}

2. Using Conditional Creation with count or for_each

You can conditionally create resources based on input variables which can mimic tags.

variable "apply_resource" {
  description = "Flag to apply resource"
  type        = bool
  default     = false
}

resource "aws_instance" "example" {
  count = var.apply_resource ? 1 : 0
  ...
}

Invoke terraform apply with:

terraform apply -var="apply_resource=true"

3. Dynamically Loading Configuration Files

A more advanced (and trickier) approach involves dynamically loading Terraform configurations based on a set criterion, like tags. This would likely involve external scripts that process your requirements and adjust which Terraform files are loaded during a terraform apply.

4. Using a Tool like Terragrunt

Terragrunt is a thin wrapper for Terraform that provides extra tools for keeping configurations DRY, working with multiple Terraform modules, and managing remote state, among other utilities. By using Terragrunt, you can organize your resources and apply them more granularly based on conditions.

Important Note:

Remember to always run terraform plan before terraform apply to ensure you're aware of the changes Terraform will make to your infrastructure. This is crucial when you're conditionally applying resources to prevent any unintended modifications.