Terraform Basic Resource Creation

LinuxBeginner
Practice Now

Introduction

Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp. It allows you to define and provide data center infrastructure using a declarative configuration language. This means you describe your desired infrastructure in configuration files, and Terraform will figure out how to create, update, or delete resources to match that state.

The core Terraform workflow consists of three main stages:

  1. Write: Author infrastructure as code.
  2. Plan: Preview changes before applying them.
  3. Apply: Provision and manage your infrastructure.

In this lab, you will walk through this entire workflow by creating a very simple resource: a local file. Using the local provider is an excellent way to learn Terraform's mechanics without needing credentials for a cloud provider. You will define a file, plan its creation, apply the changes, and verify the result.

Define a local_file resource in main.tf

In this step, you will begin by defining a resource in your Terraform configuration file. All Terraform configurations are written in files ending with the .tf extension. The main configuration file is commonly named main.tf.

A resource block is the primary syntax for declaring an infrastructure object. It defines a resource of a given type (e.g., local_file) with a given local name (e.g., example). The combination of the type and name must be unique within a module.

First, open the main.tf file in your ~/project directory using the nano text editor.

nano main.tf

Now, add the following code to the file. This defines a resource of type local_file and gives it the local name example. For now, the resource block is empty.

resource "local_file" "example" {
}

After adding the code, save the file and exit nano by pressing Ctrl+X, then Y, and finally Enter.

Specify filename and content in resource block

In this step, you will add arguments to the resource block to specify the properties of the file you want to create. Arguments are the key-value pairs inside a resource block that define its configuration. For a local_file resource, the two most important arguments are filename and content.

  • filename: The path to the file that will be created.
  • content: The content to be written into the file.

Open the main.tf file again with nano.

nano main.tf

Modify the local_file resource block to include the filename and content arguments as shown below.

resource "local_file" "example" {
  content  = "Hello, Terraform!"
  filename = "${path.module}/hello.txt"
}

Here, we are telling Terraform to create a file named hello.txt in the current project directory. The ${path.module} is a special Terraform expression that resolves to the path of the current module, which in this case is ~/project. The file's content will be the string "Hello, Terraform!".

Save the file and exit nano by pressing Ctrl+X, Y, and Enter.

Initialize Terraform and Preview Changes

In this step, you will first initialize your Terraform project and then run the terraform plan command to create an execution plan.

Before you can plan any changes, you must initialize the project. The terraform init command scans your configuration, downloads the required providers (in this case, for local_file), and sets up the backend.

In your terminal, first run terraform init:

terraform init

After initialization is successful, run terraform plan. This command is a crucial part of the Terraform workflow as it provides a "dry run" of the changes. It shows you what Terraform will do to your infrastructure without actually making any changes. This allows you to review and verify the intended actions before they are applied.

terraform plan

Terraform will read your configuration file and compare it to the current state of your infrastructure (which is currently empty). It will then display a plan of action. You should see output similar to the following, indicating that one resource is going to be created.

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  ## local_file.example will be created
  + resource "local_file" "example" {
      + content              = "Hello, Terraform!"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./hello.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

The + symbol next to resource "local_file" "example" signifies that this resource will be created. The output details all the attributes that will be set on the new file.

Run terraform apply to create the resource

In this step, you will apply the changes using the terraform apply command to actually create the file. This command executes the actions proposed in the terraform plan output.

By default, terraform apply will show you the plan again and ask for interactive confirmation before proceeding. To make it non-interactive, which is useful for labs and automation, you can use the -auto-approve flag.

Run the following command in your terminal:

terraform apply -auto-approve

Terraform will now execute the plan. The output will first show the plan again, followed by the progress of the application. Once completed, you will see a confirmation message.

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  ## local_file.example will be created
  + resource "local_file" "example" {
      + content              = "Hello, Terraform!"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./hello.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
local_file.example: Creating...
local_file.example: Creation complete after 0s [id=42086c02e03bf671ddf621ed9922f52f2c7a605c]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The message "Apply complete!" confirms that Terraform has successfully created the resource as defined in your configuration.

Verify created file exists in filesystem

In this final step, you will verify that Terraform has successfully created the file on your local filesystem as specified. Since you used the local_file resource, the result is a tangible file in your project directory.

First, use the ls command to list the files in the current directory. You should now see hello.txt alongside your Terraform configuration file.

ls

Expected output:

hello.txt  main.tf  terraform.tfstate

Next, use the cat command to display the contents of the newly created hello.txt file.

cat hello.txt

You should see the content you defined in main.tf.

Hello, Terraform!

This confirms that your Terraform configuration was successfully applied and the resource was created exactly as you defined it in your code.

Summary

Congratulations! You have successfully completed your first Terraform project.

In this lab, you learned the fundamental workflow of Terraform:

  1. Write: You defined a local_file resource in a main.tf configuration file.
  2. Plan: You used terraform plan to preview the creation of the file without making any changes.
  3. Apply: You used terraform apply to execute the plan and create the file on your local filesystem.

This simple example of creating a local file demonstrates the core power of Infrastructure as Code. You declared the desired state of a resource in a configuration file, and Terraform handled the logic to achieve that state. The same principles apply when managing more complex infrastructure, such as virtual machines, networks, and databases in the cloud.