Saturday, May 18, 2024

Tutorial 03 | Terraform

Table of Contents

01
of 05
Introduction

In the previous post, we learned how to initialize the project directory and write the Terraform configuration file. In this lecture, we will learn about the life cycle of a resource in Terraform.

Today, we will use Terraform to create an S3 (AWS Simple Cloud Storage) on AWS to learn about the lifecycle of a resource.

02
of 05
Terraform functions in a lifecycle

All Terraform resource types are Implemented in a CRUD Interface. In this Interface, there will be functions Create(), Read(), Update(), and Delete(), and these functions will be executed if the right conditions are met. As for the data type of Terraform, Implement a Read Interface has only one function, which is Read().

Lifecycle of a resource in Terraform

Create() is called during resource creation, Read() is called during planning, Update() is called during resource update, and Delete() is called during resource deletion.

03
of 05
Hands-On

We will write the Terraform file to create S3 and discuss the above functions. Create a Workspace named s3, then create a file named main.tf with the following code:

provider "aws" {
  region = "us-west-2"
}

resource "aws_s3_bucket" "terraform-bucket" {
  bucket = "terraform-series-bucket"

  tags = {
    Name        = "Terraform Series"
  }
}

In the above file, we use the resource aws_s3_bucket. This is the resource used to create an S3 Bucket on AWS Cloud, in which the bucket field will be the name of our Bucket. After, we run the init command to let Terraform download the Provider to the current Workspace.

terraform init

Plan

As mentioned in the previous post, before we create resources, we should run the terraform plan first to see what resources will be built.

And besides showing us what resources will be created. If we already have a resource but change any value in the Terraform file, the plan will show us which resource will be updated again based on the State of the previously created resource.

And if we don’t change anything in the Terraform file, then when we run the plan command, it will show that no resources have been added or updated.

1. Read configuration files and State files – Terraform will first read your configuration files and the State files (if it exists) to get resource information.

2. It then determines what actions will be performed – Terraform performs calculations to determine which actions should be executed, be it Create(), Read(), Update(), Delete(), or do nothing (No-op).

3. Output.

Diagram showing the planning process

Create S3

Now we will run the apply statement to create S3 on AWS. When we run the apply command, it will have an additional confirmation step and force us to enter yes. If you want to skip the confirmation step, you can add the attribute - auto-approve.

terraform apply -auto-approve
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:

  # aws_s3_bucket.terraform-bucket will be created
  + resource "aws_s3_bucket" "terraform-bucket" {
  ...
  }

Plan: 1 to add, 0 to change, 0 to destroy.
aws_s3_bucket.terraform-bucket: Creating...
aws_s3_bucket.terraform-bucket: Still creating... [10s elapsed]
aws_s3_bucket.terraform-bucket: Creation complete after 15s [id=terraform-series-bucket]

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

When we finish running the apply command, Terraform will create a file named terraform.tfstate, click on it, and you will see the information on S3. Open the AWS Web Console, and you will see that our S3 Bucket has been created.

How did Terraform create this S3 Bucket? Then during the application process, Terraform will call the Create() function of the aws_s3_bucket resource.

The Create() function above contains the code to make the API call to AWS to create an S3 Bucket, so when Terraform calls this function, the S3 Bucket will be created, illustrated below.

No-op

Once we have created the resource and if we do not edit anything, then when we execute the plan command, Terraform will go through the No-op step. Terraform will first read our configuration file if we run the plan command. Next, if it can detect a State file, it reads the State file.

After reading the State file, Terraform will check whether the S3 Bucket exists in the State file. If so, Terraform will execute the Read() function of the aws_s3_bucket resource.

Read() contains the code to call the API to AWS and read the information of the current S3 Bucket, which it then compares with S3 in the State. If nothing changes, the Read() function will return nothing changed, and the terraform will take no action.

Update S3

In Terraform, there is no update command. We just need to edit the configuration file and rerun the apply command. Terraform will determine whether to update the resource or not. Now let us change the name of the S3 Bucket.

provider "aws" {
  region = "us-west-2"
}

resource "aws_s3_bucket" "terraform-bucket" {
  bucket = "terraform-series-bucket-update"

  tags = {
    Name        = "Terraform Series"
  }
}

Then we rerun the plan command.

terraform plan
aws_s3_bucket.terraform-bucket: Refreshing state... [id=terraform-series-bucket]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_s3_bucket.terraform-bucket must be replaced
-/+ resource "aws_s3_bucket" "terraform-bucket" {
      + acceleration_status         = (known after apply)
      ~ arn                         = "arn:aws:s3:::terraform-series-bucket" -> (known after apply)
      ...
    }

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

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you
run "terraform apply" now.

You will see that our S3 Bucket will be updated by Terraform by deleting and recreating. Why is that? Terraform will first delete the old S3 Bucket, then create a new S3 Bucket with a different name. Then the bucket field in aws_s3_bucket resource is a Force New property.

In Terraform, resources will have two types of properties: Force New and Normal Update:

Force New: resource will be deleted and recreated. Delete the old resource first and create a new one.

Normal Update: the resource is usually updated. No need to delete the old resource.

What type an attribute will depend on the Provider. Above, since we changed the Force New property of aws_s3_bucket, it will be deleted and recreated. Since deleting and recreating will cause many problems, we need to run the plan command to determine why our resource is like that. Remember to always run the plan first.

Since our S3 Bucket was created and has nothing, we just run terraform apply to get it updated as usual.

terraform apply -auto-approve
aws_s3_bucket.terraform-bucket: Refreshing state... [id=terraform-series-bucket]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

 # aws_s3_bucket.terraform-bucket must be replaced
-/+ resource "aws_s3_bucket" "terraform-bucket" {
     + acceleration_status         = (known after apply)
     ~ arn                         = "arn:aws:s3:::terraform-series-bucket" -> (known after apply)
     ...
   }

Plan: 1 to add, 0 to change, 1 to destroy.
aws_s3_bucket.terraform-bucket: Destroying... [id=terraform-series-bucket]
aws_s3_bucket.terraform-bucket: Destruction complete after 1s
aws_s3_bucket.terraform-bucket: Creating...
aws_s3_bucket.terraform-bucket: Still creating... [10s elapsed]
aws_s3_bucket.terraform-bucket: Creation complete after 15s [id=terraform-series-bucket-update]

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

Diagram showing the update process

Delete S3

We delete the resource with the destroy command. Like apply, we can skip the validation step by passing the -auto-approve attribute.

terraform destroy -auto-approve
aws_s3_bucket.terraform-bucket: Refreshing state... [id=terraform-series-bucket-update]

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

Terraform will perform the following actions:

 # aws_s3_bucket.terraform-bucket will be destroyed
 - resource "aws_s3_bucket" "terraform-bucket" {
     - acl                         = "private" -> null
     - arn                         = "arn:aws:s3:::terraform-series-bucket-update" -> null
     ...
   }

Plan: 0 to add, 0 to change, 1 to destroy.
aws_s3_bucket.terraform-bucket: Destroying... [id=terraform-series-bucket-update]
aws_s3_bucket.terraform-bucket: Destruction complete after 1s

Destroy complete! Resources: 1 destroyed.

When we run the destroy statement, it will read in our State file whether there is a resource. If so, it will execute the Delete() function of the aws_s3_bucket resource.

Diagram showing the delete process

After we run the destroy command, our Workspace will look like this:

.
├── main.tf
├── terraform.tfstate
└── terraform.tfstate.backup

We see an additional file named terraform.tfstate.backup. This file is mainly for us to review the previous State of the resources.

When we delete the entire configuration in the Terraform file and run the apply command, it is equivalent to running the destroy command.
We have finished talking about the life cycle of a resource in Terraform.

04
of 05
Resource Drift

Now we will talk about a common problem, what if someone changes the configuration of our resources outside of Terraform? How will Terraform handle that?

Resource Drift is a problem when our resource configuration is changed outside Terraform. For example, if someone uses the AWS Management Console to change the configuration of the resource we created with Terraform, we can reuse the model above and recreate S3.

Let’s go to the AWS Management Console and edit the tags field of the S3 Bucket from “Terraform Series” to “Terraform Series Drift”.

Terraform won’t automatically detect and update our Terraform file. And when we run the apply command, it will notice the change and update the tags field that we changed outside of Terraform to be the same as the tags we wrote in the configuration file.

You run the plan command first to see changes.

terraform plan
aws_s3_bucket.terraform-bucket: Refreshing state... [id=terraform-series-bucket-update]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the last "terraform apply":

  # aws_s3_bucket.terraform-bucket has been changed
  ~ resource "aws_s3_bucket" "terraform-bucket" {
        id                          = "terraform-series-bucket-update"
      ~ tags                        = {
          ~ "Name" = "Terraform Series" -> "Terraform Series Drift"
        }
      ~ tags_all                    = {
          ~ "Name" = "Terraform Series" -> "Terraform Series Drift"
        }
        # (9 unchanged attributes hidden)

        # (1 unchanged block hidden)
    }

...

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # aws_s3_bucket.terraform-bucket will be updated in-place
  ~ resource "aws_s3_bucket" "terraform-bucket" {
        id                          = "terraform-series-bucket-update"
      ~ tags                        = {
          ~ "Name" = "Terraform Series Drift" -> "Terraform Series"
        }
      ~ tags_all                    = {
          ~ "Name" = "Terraform Series Drift" -> "Terraform Series"
        }
        # (9 unchanged attributes hidden)

        # (1 unchanged block hidden)
    }

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

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you
run "terraform apply" now.

Now run the apply command, and we will see that the tags will be updated again.

terraform apply -auto-approve
...
Plan: 0 to add, 1 to change, 0 to destroy.
aws_s3_bucket.terraform-bucket: Modifying... [id=terraform-series-bucket-update]
aws_s3_bucket.terraform-bucket: Still modifying... [id=terraform-series-bucket-update, 10s elapsed]
aws_s3_bucket.terraform-bucket: Modifications complete after 13s [id=terraform-series-bucket-update]

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

05
of 05
Conclusion

So we have learned about the life cycle of a resource in Terraform. In the next lesson, we will learn about Functional Programming inside Terraform.

toicodemoingay

toicodemoingay

Hello, my name is Phan Minh Hung, and I am the founder of this website. Toi Code Moi Ngay = Everyday I Code (Vietnamese => English)

Next Post

Comments 13,206

  1. Sciess says:

    viagra government funded buy online viagra generic viagra online

  2. emaloGek says:

    sildenafil 50 mg otc viagra where to buy viagra

  3. PewsCete says:

    cialis medication tadalafil research chemical free sample cialis

  4. extelm says:

    ivermectin pills for dogs ivermectin 1 cream ivermectin for horses lice

  5. JamesBop says:

    darknet market list bitcoin dark web

  6. Richardprook says:

    deep web drug markets darkmarket 2023

  7. JamesBop says:

    dark web drug marketplace the dark internet

  8. Robertarbic says:

    dark web search engine darkmarket 2023

  9. StanleyRup says:

    drug markets dark web darknet drugs

  10. KevinScove says:

    dark web market links deep dark web

  11. BaaElows says:

    darknet market lists tor markets links

  12. Robertarbic says:

    drug markets dark web tor marketplace

    • Психическое здоровье включает в себя наше эмоциональное, психологическое и социальное благополучие. Это влияет на то, как мы думаем, чувствуем и действуем. Оно также помогает определить, как мы справляемся со стрессом, относимся к другим и делаем здоровый выбор.
      Психическое здоровье важно на каждом этапе жизни: с детства и подросткового возраста до взрослой жизни.ние) — специалист, занимающийся изучением проявлений, способов и форм организации психических явлений личности в различных областях человеческой деятельности для решения научно-исследовательских и прикладных задач, а также с целью оказания психологической помощи, поддержки и сопровождения.

    • psyxlolo says:

      Cibus, onus et virga asino — Ослу нужны пища, груз и кнут.
      http://batmanapollo.ru

  13. DevinKix says:

    dark web market links tor market url

  14. EverettWet says:

    darknet drug store dark markets

  15. HenryBusia says:

    dark web drug marketplace dark markets

  16. Scottvox says:

    darknet drug store tor markets

  17. EugeneBloto says:

    blackweb official website darknet market lists

  18. BaaElows says:

    darknet drug store tor markets

  19. StanleyRup says:

    darknet markets 2023 dark websites

    • mozgme says:

      Aequam memento rebus in arduis servare mentem — Помни, старайся сохранять присутствие духа в затруднительных обстоятельствах.
      http://batmanapollo.ru

  20. AlbertKax says:

    dark web search engines darkmarket 2023

  21. Robertframi says:

    dark web market links dark website

  22. Timothywhaks says:

    deep web drug store dark website

    • psylike says:

      Aequam memento rebus in arduis servare mentem — Помни, старайся сохранять присутствие духа в затруднительных обстоятельствах.
      http://batmanapollo.ru

  23. Arnoldshula says:

    darknet marketplace blackweb

  24. Ignaciomut says:

    dark web market links darknet links

  25. AlbertoRar says:

    dark web search engine dark websites

  26. Andrewges says:

    dark web drug marketplace drug markets dark web

  27. AllenTox says:

    dark web market list deep web search

  28. BaaElows says:

    deep web drug store tor marketplace

  29. RonaldOxirl says:

    dark web market links deep dark web

  30. JamesFesee says:

    how to access dark web deep web links

  31. HenryRig says:

    darknet search engine dark market url

  32. AlbertKax says:

    darknet marketplace tor darknet

  33. Davidham says:

    darknet search engine bitcoin dark web

  34. RandyBurnE says:

    dark web search engines dark web market list

  35. AllenTox says:

    dark market 2023 tor markets

  36. Wesleygax says:

    dark web market links deep web links

  37. WesleyDourb says:

    deep web drug markets dark market link

  38. JamesFesee says:

    blackweb official website dark web access

    • vizglike says:

      Aequam memento rebus in arduis servare mentem — Помни, старайся сохранять присутствие духа в затруднительных обстоятельствах.
      http://batmanapollo.ru

  39. HenryBusia says:

    blackweb official website dark market

  40. ElmerCew says:

    how to get on dark web darknet drug store

  41. Davidcex says:

    tor markets links darknet site

  42. EugeneBloto says:

    dark web search engines tor markets

  43. DavidImirm says:

    darknet market lists deep dark web

  44. AndrewVieta says:

    dark web market links tor markets 2023

  45. AllenTox says:

    darknet drug store deep dark web

  46. Richardprook says:

    deep web drug markets dark web site

  47. Charliecag says:

    how to access dark web dark web markets

  48. Davidcex says:

    dark web search engine the dark internet

  49. Timothywhaks says:

    darknet search engine darknet markets

  50. Ignaciomut says:

    how to access dark web dark web websites

  51. Darrenhor says:

    how to access dark web dark market 2023

  52. ElmerCew says:

    dark web market links darknet site

  53. AlbertoRar says:

    how to access dark web dark market

  54. AllenTox says:

    darknet marketplace dark website

  55. HenryBusia says:

    blackweb official website dark web search engine

  56. RonaldOxirl says:

    dark web drug marketplace free dark web

  57. DevinKix says:

    darknet markets 2023 darknet seiten

  58. DavidImirm says:

    darknet marketplace deep dark web

  59. JamesFesee says:

    drug markets dark web onion market

  60. AlbertoRar says:

    deep web drug markets bitcoin dark web

  61. JamesBop says:

    darknet marketplace dark net

  62. Billyoccuh says:

    dark web market links onion market

  63. RonaldDom says:

    dark web search engine tor markets links

  64. AndrewVieta says:

    how to get on dark web deep dark web

  65. ElmerCew says:

    dark web market links dark market link

  66. AlbertoRar says:

    deep web drug markets darknet sites

  67. HenryRig says:

    dark web sites links darknet market

  68. Willisvot says:

    dark web drug marketplace darkmarket link

  69. Davidham says:

    dark web market links darkmarket list

  70. HenryRig says:

    darknet drug market tor dark web

  71. StanleyRup says:

    how to access dark web darkmarket url

  72. Wesleygax says:

    deep web drug store darkmarket list

  73. Willisvot says:

    blackweb official website dark websites

  74. JamesBop says:

    dark web search engines darknet markets 2023

  75. JamesFesee says:

    darknet search engine dark market

  76. RonaldDom says:

    darknet marketplace dark website

  77. Ignaciomut says:

    how to get on dark web tor markets 2023

  78. HenryBusia says:

    darknet market links blackweb

  79. WilliamTraub says:

    dark web market list dark websites

  80. Arnoldshula says:

    how to get on dark web tor market url

  81. AlbertKax says:

    dark web drug marketplace dark web market links

  82. AlbertoRar says:

    dark web market links dark web market

  83. Davidham says:

    dark web drug marketplace darknet marketplace

  84. BaaElows says:

    darknet drug market dark market url

  85. RandyBurnE says:

    dark web drug marketplace darknet drugs

  86. KevinScove says:

    deep web drug markets deep web search

  87. DevinKix says:

    darknet search engine darknet marketplace

  88. Robertarbic says:

    how to get on dark web tor market links

  89. AlbertKax says:

    how to get on dark web tor dark web