Open In App

Terraform Resources

Last Updated : 17 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Terraform, created by HashiCorp, is an open-source tool for infrastructure as code (IaC). Through code, it empowers you to declaratively define, oversee, and provision infrastructure resources. This uniform workflow allows you to efficiently generate, modify, and remove infrastructure elements, whether on diverse cloud platforms or within on-premises setups. It facilitates the definition, management, and provisioning of infrastructure resources using code in a declarative manner. To know how to set up Terraform On Linux and Windows Machine.

Terraform Syntax

Terraform employs its dedicated domain-specific language known as HashiCorp Configuration Language (HCL) to establish infrastructure resources and configurations. HCL is crafted to find an equilibrium between human-friendly readability and machine-friendly interpretability. Provided below is a synopsis of the syntax utilized within Terraform. To know more about terraform blocks refer to Different Types of Blocks in Terraform.

Resource Block

Resource blocks delineate singular infrastructure resources. For the AWS EC2 instance.

resource “aws_instance” “example” {

ami = “ami-0c55b159cbfafe1f0”

instance_type = “t2.micro”

}

A block has a type (resource in this example). Each block type defines how many labels must follow the type keyword. The resource block type expects two labels, which are aws_instance and example in the example above. A particular block type may have any number of required labels, or it may require none as with the nested network_interface block type. You can apply the above code to make the provision by using the terraform apply command.

Variables Block

Variables grant the ability for parameterization and re-usability in your setups. They can be outlined as input variables or output values.

variable “variable_name” {

description = “Description of the variable”

default = “default_value”

}

Data Blocks

Data blocks retrieve information from external origins or existing resources for utilization in your configurations.

data “aws_ami” “example” {

most_recent = true

owners = [“self”]

}

Incorporating these constructs, Terraform embraces HCL as a tool for crafting both human-readable and machine-processable infrastructure code.From above code we are going to create Amazon machine image (AMI).

Terraform Providers

The Terraform ecosystem allows you to engage with a variety of cloud platforms, services, and technologies, and terraform providers are essential parts of that ecosystem. By acting as plugins, providers increase terraform capacity to manage resources in certain contexts. Each provider is associated with a certain infrastructure service, system, or cloud provider. Terraform configurations must declare which providers they require so that Terraform can install and use them. Additionally, some providers require configuration (like endpoint URLs or cloud regions) before they can be used.

  • Plugin-Based Structure: terraform framework operates on a foundation of plugins. Providers play the role of linking with the APIs and services of their corresponding platforms.
  • Resource Diversity: Providers encompass an extensive spectrum of resources that Terraform can oversee, including virtual machines, databases, networks, storage, and more.
  • Configuring Providers: To utilize a provider, you configure it within your Terraform configuration file. This usually entails detailing authentication particulars, region specifications, or provider-specific settings.
  • Unified Compatibility: Terraform providers furnish the ability to manage resources consistently across various cloud providers and on-premises setups, employing a uniform syntax.

Representative Providers: Noteworthy providers comprise:

  • AWS (Amazon Web Services)
  • Azure (Microsoft Azure)
  • GCP (Google Cloud Platform)

Terraform Modules

Modules are containers for multiple resources that are used together. A module consists of a collection of .tf and/or .tf.json files kept together in a directory. Modules are the main way to package and reuse resource configurations with Terraform. Terraform modules constitute a foundational idea that improves the structure, re-usability, and manageability of your infrastructure code. These modules enable you to encapsulate a collection of resources, configurations, and logic within a self-contained entity.

Inputs and Outputs: Modules accept inputs, allowing you to customize their behaviour for different use cases. Likewise, modules produce outputs, which can be used by other parts of your configuration or other modules. This helps in connecting different parts of your infrastructure.

Module Sources: Modules can be sourced from local paths, Git repositories, or module registries. This provides flexibility in how you manage and distribute your modules. To Know more about terraform modules refer to Modules Block in Terraform

Example: Creating a Module

# module example_module/main.tf

variable “instance_type” {

description = “Type of the instance”

}

resource “aws_instance” “example” {

ami = “ami-0c55b159cbfafe1f0”

instance_type = var.instance_type

}

output “instance_id” {

value = aws_instance.example.id

}

Terraform Best Practices

Use Remote State: It’s ok to use the local state when experimenting, but use a remote shared state location for anything above that point. Having a single remote backend for your state is considered one of the first best practices you should adopt when working in a team. Pick one that supports state locking to avoid.

  • Code Organization: Arrange your codebase in a coherent manner, segmenting resources and modules into categorized directories. This enhances both the ease of comprehension and the manageability of your code.
  • Modular Approach: Partition your infrastructure into reusable modules. This promotes the reuse of code, enforces uniformity, and simplifies problem-solving.
  • Uniform Naming: Employ descriptive and uniform naming standards for resources, modules, variables, and outputs. This fosters comprehensibility across your codebase.
  • Parameterization with Variables: Embrace variables to accommodate customizable values, and employ outputs to disseminate data between modules or configurations.
  • Comments and Documentation: Add comments to clarify your code’s intent. Include high-level documentation explaining the purpose and design decisions.
  • Immutable Infrastructure: Leverage immutable infrastructure principles by avoiding in-place updates. Instead, create new resources and update references.
  • Dependency Management: Use terraform’s dependency management to specify resource relationships explicitly. This helps in the correct order of creation and updates.

Terraform Examples

Of course, here are several Terraform examples that illustrate various facets of configuring infrastructure.

Creating an AWS EC2 Instance:

terraform {

required_providers {

aws = {

source = “hashicorp/aws”

version = “~> 4.16”

}

}

required_version = “>= 1.2.0”

}

provider “aws” {

region = “us-west-2”

}

resource “aws_instance” “app_server” {

ami = “ami-830c94e3”

instance_type = “t2.micro”

tags = {

Name = “ExampleAppServerInstance”

}

}

Creating an AWS S3 Bucket in AWS

resource “aws_s3_bucket” “example” {

bucket = “my-unique-bucket-name”

acl = “private”

}

Summing up, Terraform emerges as a versatile and potent instrument in the realm of infrastructure as code (IaC). Its proficiency in delineating, overseeing, and provisioning resources through code heralds a transformative era in the orchestration of contemporary infrastructures. Embracing a declarative syntax, Terraform streamlines the intricacies of establishing and upholding infrastructure across a wide spectrum of cloud providers and on-premises landscapes.

FAQs On Terraform Resources

1. What Is Terraform Module Vs Resource?

Terraform modules is an collection of resources and resource is an single unit which can be managed by the terraform.

2. What Is An Example Of A Terraform Data Resource?

A Terraform data resource is a resource that does not create or modify any infrastructure. It simply retrieves information about existing infrastructure.

3. What Is Terraform Resource Lifecycle?

A set of rules that Terraform uses to determine how to create, update, and delete resources.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads