Terraform language defines several meta-arguments, which can be used with any resource type to change the behavior of resources
depends_on
Used to set the precedence of resources being provisioned and can be set when one resource depends on another for its creation.
Terraform can implicitly determine the order of provision for resources but there may be some cases where it cannot determine the correct order
resource "aws_iam_role_policy" "example" {
policy = ""
role = ""
}
resource "aws_instance" "example" {
ami = ""
instance_type = ""
depends_on = [
aws_iam_role_policy.example,
]
}
count
When you are managing a pool of objects, like a fleet of Virtual Machine you can
use count
resource "aws_instance" "server" {
count = 4 # Create four similar EC2 instances
# count = length(var.subnet_ids)
ami = "ami-abc123"
instance_type = "t2.micro"
tags = {
Name = "Server ${count.index}"
}
}
foreach
Similar to count
for managing multiple related objects but you
can iterate over a map for more dynamic values
resource "azurerm_resource_group" "rg" {
for_each = {
us_group = "southcentralus"
eu_group = "francecentral"
}
name = each.key
location = each.value
}
When you execute your resource plan using terraform apply
, it will
perform one of the following to a resource:
+ create
)
- destroy
)
~ update in-place
)
-/+ destroy and the create replacement
)
Lifecycle block allows you to change what happens to a resource
create_before_destroy(bool)
prevent_destroy(bool)
ignore_changes(list)
resource "azurerm_resource_group" "example" {
lifecycle = {
create_before_destroy = true
}
}
provider "google" {
region = "us-central"
}
provider "google" {
alias = "europe"
region = "europe-west1"
}
resource "google_compute_instance" "example-us" {
provider = google
}
resource "google_compute_instance" "example-eu" {
provider = google.europe
}