Skip to content

Terraform Resources

What are Terraform Resources?

Resources are the most important element in the Terraform language. Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records.

Resource Syntax

A resource block declares a resource of a given type ("aws_instance" in this example) with a given local name ("web"):

resource "aws_instance" "web" {
  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
}

Resource Types

Resource types are defined by providers. Some common resource types include:

  • aws_instance (AWS EC2 instance)
  • azurerm_virtual_machine (Azure VM)
  • google_compute_instance (Google Cloud VM)
  • docker_container (Docker container)

Resource Arguments

Each resource type has its own set of arguments. These are defined by the provider and can be found in the provider's documentation.

Resource Dependencies

Terraform automatically handles dependencies between resources. You can also explicitly define dependencies using the depends_on meta-argument:

resource "aws_instance" "web" {
  # ...

  depends_on = [aws_s3_bucket.example]
}

Resource Lifecycle

Use the lifecycle block to configure how Terraform should handle resource creation, updates, and deletion:

resource "aws_instance" "web" {
  # ...

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = true
    ignore_changes        = [tags]
  }
}

Importing Existing Resources

You can import existing infrastructure into Terraform using the terraform import command:

terraform import aws_instance.web i-1234567890abcdef0

Remember to refer to the specific provider's documentation for detailed information about each resource type and its arguments.