11. Meta-Arguments

depends_on

  • If two resources depend on each other (but not on each others data), depends_on specifies that dependency to enforce ordering


count

  • allows for creation of multiple resources/modules from a single block

  • usefil when multiple necessary resources are nearly identical

  • example is 4 ec2 instances with tag name as ${count.index}


for_each

  • allows for creation of multiple resources/modules from single block

  • allows more control to customize each resource than count

locals {
  subnet_ids = toset([
    "subnet-123",
	  "subnet-456",
  ])
}

resource "aws_instance" "server" {
  for_each = local.subnet_ids

  ami = "aaa1"
  instance_type = "t2.micro"
  subnet_id = each.key

  tags = {
    Name = "Server ${each.key}"
  }
}

lifecycle

  • set of meta atguments to control terraform behaviour for specific resources

  • create_before_destroy can help with zero downtime deployments

  • ignore_changes prevents terraform from trying to revert metadata being set elsewhere

  • prevent_destroy causes terraform to reject any plan which would destroy the resource

resource "aws_instance" "server" {
  ami = "aaa1"
  instance_type = "t2.micro"

	lifecycle {
	  create_before_destroy = true
	  ignore_changes = [
	    # Some resources have metadata
		  # modified automatically outside
		  # of Terraform
		  tags
	  ]
	}
}

Last updated