svg
Post Image
By Daniel Tanque20 de Novembro, 2023In Sem categoria

Terraform Basics: Resources

Terraform is an open-source infrastructure as code (IaC) tool developed by HashiCorp. It enables users to define and provision infrastructure in a declarative and version-controlled manner. The primary goal of Terraform is to simplify the process of managing and orchestrating infrastructure components across various cloud providers, on-premises environments, and even third-party services.

In this article you will learn the basics of Terrafor, what ware providers, resources and the main workflow.

Providers

In Terraform, providers are plugins that serve as the bridge between Terraform and various infrastructure platforms or services. A provider is responsible for understanding the API interactions and resource lifecycle of a specific platform, allowing Terraform to manage resources in that environment. Providers enable Terraform to support a wide range of infrastructure, including public cloud services, private cloud environments, on-premises data centers, and even third-party services.

There are 3 tiers of providers: Official (maintained by terraform), Verified (owned by a third party company) and Community (made by members of the community).

When we need to set a component to the infrastructure you have to use a .tf file. A good practice is to define a main.tf file in which we set our resources.

Resources

A resource is a logical and representational unit that corresponds to an infrastructure object or component, such as a compute instance, a storage bucket, a virtual network, or any other manageable entity provided by a specific infrastructure platform. Resources are the building blocks of Terraform configurations, and they are declared within the configuration files to define the desired state of the infrastructure.

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

This is an example of a resource definition in HCL format. The block name is resource; the resource type is aws_instance; the resource name is example. The inside the the { } are arguments.

Workflow

  1. Write the config file
  2. Run: terraform init
  3. Run: terraform plan
  4. Run: terraform apply

Init, initializes and sees all providers need to download; Plan check if the syntax it’s correct and display what will happen; Apply runs the code and applies the changes.

To update you have to run again “terraform apply” and first the object is deleted and then recreated with the new changes.

To delete a resource you can run “terraform destroy”.

To hide sensitive content from the execution plan you can add “local_sensitive_file”. The local_sensitive_file resource in Terraform is used to manage sensitive files on the local filesystem. It allows you to create, read, and update files that contain sensitive data, such as passwords, encryption keys, and other confidential information. The resource is part of the hashicorp/local provider, which provides a number of resources for managing local files and directories.

resource "local_sensitive_file" "example" {
    content = "This is a secret password."
    filename = "/home/user/.password"
}

Best Practices

There’s a common standard on having some files used to ensure better configuration systematized.

main.tf -> for resource definition
variables.tf -> for variables definition
outputs.tf -> for accessing output variables
provider.tf -> for provider definition

There can be multiple provides, for example:

resource "random_pet" "my_pet"{
prefix = "Mrs"
separator = "."
length = "1"
}

Here the provider is “random”, resource type is “pet”.

Resources Dependecies

In Terraform, dependencies between resources are crucial to ensure that resources are created, updated, or destroyed in the correct order. Terraform can manage these dependencies in two ways: explicit and implicit.

Explicit Resource Dependencies:

  • depends_on Attribute:
    • Terraform provides an explicit way to define dependencies between resources using the depends_on attribute. This attribute allows you to specify a list of resources that the current resource depends on, ensuring that Terraform manages them in the specified order.
    • While depends_on can be helpful, it’s generally recommended to use it sparingly. Explicit dependencies can make the configuration less predictable and hinder Terraform’s ability to parallelize operations.
resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  depends_on = [aws_security_group.allow_http]
}

resource "aws_security_group" "allow_http" {
  // ...
}

Implicit Resource Dependencies:

  1. Resource References:
    • Terraform automatically establishes dependencies based on resource references in the configuration. When one resource references another in its attributes or arguments, Terraform implicitly understands the dependency between them.
    • For example, if a virtual machine depends on a security group, Terraform will naturally ensure that the security group is created or updated before the virtual machine.
resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  vpc_security_group_ids = [aws_security_group.allow_http.id]
}

resource "aws_security_group" "allow_http" {
  // ...
}

Terraform Graph:

  • Terraform internally builds a dependency graph based on the configuration, which represents the relationships between resources. This graph is used to determine the correct order of resource operations during the apply phase.
  • The order is determined by analyzing which resources depend on others, and Terraform uses this information to create an execution plan.

Best Practices:

  • Leveraging Implicit Dependencies:
    • In most cases, leveraging implicit dependencies by referencing resources in the configuration is sufficient. Terraform is designed to understand these relationships and manage resources accordingly.
  • Minimize depends_on Usage:
    • Explicit dependencies through depends_on can be useful in specific scenarios, but it’s generally recommended to minimize their usage. Terraform’s implicit dependencies often provide a more maintainable and predictable configuration.

Terraform State

Terraform state is a crucial concept in Terraform that represents the current state of your infrastructure. It contains information about the resources Terraform manages, their attributes, and the relationships between them. The state file is in JSON format and includes details such as resource IDs, metadata, and other relevant information.

Here are key points about Terraform state:

  1. State File:
    • When you run terraform apply, Terraform creates or updates resources and records the information in a state file. By default, this file is named terraform.tfstate or terraform.tfstate.d/<workspace>.tfstate if you are using workspaces.
    • The state file is critical for Terraform to understand the existing state of infrastructure and to plan and apply changes.
  2. Location:
    • The state file can be stored locally or remotely, depending on your configuration. Storing it remotely is often recommended for collaboration and to ensure that the state is not lost.
  3. Remote Backends:
    • Terraform supports various remote backends, such as Amazon S3, Azure Storage, and HashiCorp Consul, which allow you to store and share the state file securely. This helps in collaborative environments and provides better state management.
  4. Locking:
    • Terraform uses a state file lock to prevent concurrent modifications. This is crucial when multiple team members are working on the same infrastructure to avoid conflicts.
  5. Sensitive Data:
    • The state file may contain sensitive information, such as passwords or private keys. While Terraform attempts to encrypt this data, it’s crucial to treat the state file securely and, in some cases, use features like sensitive to mark sensitive values.

svgTerraform: HCL
svg
svgTerraform: Variables

Leave a reply