Day 60 - Terraform🔥

Day 60 - Terraform🔥

·

9 min read

Hello Learners, you guys are doing every task by creating an ec2 instance (mostly). Today let’s automate this process . How to do it ? Well Terraform is the solution .

What is Terraform?

Terraform is an infrastructure as code (IaC) tool that allows you to create, manage, and update infrastructure resources such as virtual machines, networks, and storage in a repeatable, scalable, and automated way.

Task 1:

Refer this link for terraform installation:https://phoenixnap.com/kb/how-to-install-terraform

Task 2: Answer below questions

Why we use terraform?

Use cases:

History of Terraform:

First of all, Terraform is software developed by the US company HashiCorp, which in turn was founded in 2012 by Mitchell Hashimoto. Other products you might already know from HashiCorp are Consul, Vault, or Waypoint.

The first version of Terraform was released in July 2014 and after seven years of development, version 1.0 was finally released. Similar to several other HashiCorp products, Terraform’s source code is freely available under an open-source license.

Automatic and Declarative Configuration

Terraform lets developers define the desired state of your infrastructure by code, which means that you first describe in one or several files what the desired infrastructure should look like, i.e. how many servers you need, which storage should be used, how the load balancer should be configured should and so on, and then let Terraform decide independently how and in which steps this infrastructure should be built.

Terraform determines how to achieve the desired state of the infrastructure by first comparing the current state with the desired state.

For instance: Image you have already applied a Terraform configuration which created an EC2 instance on AWS. Later, you decide you want to change the instance class and the volume size. of this EC2 instance. Then you do this by code. Terraform then will not set up a new EC2 server, but only changes the instance class of the affected EC2 instance.

This makes the configuration of infrastructures much, much easier because then you no longer have to manually deal with the question of which system is currently on which status, Terraform knows all of this you have set up the system and infrastructure by Terraform. As I said, it is simple enough to define the desired status in code and Terraform takes care of it take care of the rest.

Cloud Provider

Terraform must of course be able to communicate with the API of the corresponding cloud provider such as AWS and Microsoft Azure. There are a whole range of integrated providers and also numerous providers that are contributed by the community. But services such as Github or Bitbucket are also among the providers that are compatible with Terraform.

As a result, Terraform theoretically allows you to configure all the services that provide infrastructure for an organization’s IT.

Automatic Testing

But the coolest thing about Terraform is that you can also use Terraform for software testing since Terraform is executed as a script. Terraform makes it very easy to build test environments, which are then removed once the tests have been completed.

State Management

For Terraform to be able to carry out the desired actions, Terraform must of course know the current status. For this reason, Terraform keeps a protocol internally, which is first compared with the status of the infrastructure in the event of changes to then know which changes have to be made. However, if Terraform detects a discrepancy between the protocol and the current state of the infrastructure, errors may occur, which then will be pointed out to you.

Also, Terraform needs to store this protocol somewhere. Since Terraform can be run both locally and in the Terraform Cloud, it makes sense to save the Terraform State (i.e. the protocol) in the Terraform Cloud. This is better than just saving this state locally because then you can work better in a team.

Infrastructure as Code (IaC):

HashiCorp itself describes Terraform as a freely available Infrastructure-as-Code software. The basic idea is that infrastructure can be defined and configured by software.

For instance, imagine that you have to create different servers, load balancers, VPCs, etc. in the AWS Console and possibly change them again and again. Instead of handling this manually by logging into the AWS Console, you just do it in code. If you need to copy a server, then you just increase the count of your servers inside your Terraform code.

What is Resource?

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:

Resource declarations can include a number of advanced features, but only a small subset are required for initial use. More advanced syntax features, such as single resource declarations that produce multiple similar remote objects, are described later in this page.

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

A resource block declares a resource of a given type ("aws_instance") with a given local name ("web"). The name is used to refer to this resource from elsewhere in the same Terraform module, but has no significance outside of the scope of a module.

The resource type and name together serve as an identifier for a given resource and so must be unique within a module.

Within the block body (between { and }) are the configuration arguments for the resource itself. Most arguments in this section depend on the resource type, and indeed in this example both ami and instance_type are arguments defined specifically for the aws_instance resource type.

Note: Resource names must start with a letter or underscore, and may contain only letters, digits, underscores, and dashes.

  • What is Provider?

Terraform Providers are essentially plugins that Terraform installs to interact with the remote systems i.e. Azure/AWS/Google Cloud/ VMware and a lot of other vendors devices.

Each Terraform Provider that is used in your Terraform script will allow for the creation of certain set of resources. Once a provider has been defined in your code, terraform will automatically go to Terraform public registry and install the required provider during initialization. If you haven’t used any Terraform provider within your script you won’t be able to manage or create any infrastructure. You can define more than one provider in your Terraform code.

If you are working with Terraform modules, then you need to declare the Terraform providers in your root module while the child modules inherit the provider configuration from the root module.
Terraform providers follow their own release cadence and version number.

Terraform Providers: Registry

The complete Terraform Provider registry can be accessed at the following link
https://registry.terraform.io/browse/providers.

Whats is State file in terraform? What’s the importance of it ?

  • Terraform is a stateful application. This means that it keeps track of everything it builds in your cloud environments so that if you need to change something or delete something later, Terraform will know what it built, and it can go back and make those changes for you.

    That state is stored in what a state file.

    Terraform records information about what infrastructure it created in a Terraform state file. By default, when you run Terraform in the folder /foo/bar, it will create the file /foo/bar/terraform.tfstate.

    This file contains a custom JSON format that records a mapping from the Terraform resources in your templates to the representation of those resources in the real world.

    For example, let’s say your Terraform template contained the following:

    resource "aws_instance" "example" {

    ami = "ami-0c55b159cbfafe1f0"

    instance_type = "t2.micro"

    }

    After running terraform apply, the terraform.tfstate file will look something like this:

    The benefits of using a Terraform state

    Idempotence

    Whenever a Terraform configuration is applied, Terraform checks if there is an actual change made. Only the resources that are changed will be updated.

    Deducing dependencies

    Terraform maintains a list of dependencies in the state file so that it can properly deal with dependencies that no longer exist in the current configuration.

    Performance

    Terraform can be told to skip the refresh even when a configuration change is made. Only a particular resource can be refreshed without triggering a full refresh of the state, hence imporving performance.

    Collaboration

    State keeps track of the version of an applied configuration, and it's stored in a remote, shared location. So collaboration is easily done without overwriting.

    Auditing

    Invalid access can be identified by enabling logging.

    Safer storage

    Storing state on the remote server helps prevent sensitive information. 

    What is Desired and Current State?

Terraform’s responsibility is to create/update/destroy infrastructure resources to match the desired state as described in the configuration.

Desired State:

For example: If our desired state is as below

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

This should result in an AWS EC2 t2.medium instance.

The code you saw above is the desired state that we want.

Current State:

The current state is the actual state of a resource that is deployed.

For example: If our desired state is as below

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

our desired state is t2.medium instance but let’s say the current instance running is t2.micro. So it means our desired state and the current state is not matching.

Try it out

Let’s first deploy a t2.medium ec2 instance using the below code.

provider "aws" {
    region = "us-west-2"
    access_key = "<access_key>"
    secret_key = "<secret_key>"
}resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.micro"
}

This will deploy a AWS EC2 t2.micro instance.

Now let’s modify the instance_type to t2.medium

provider "aws" {
    region = "us-west-2"
    access_key = "<access_key>"
    secret_key = "<secret_key>"
}resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

run the terraform plan

Terraform will detect the changes between the desired state (t2.medium) and the current state (t2.micro)

# aws_instance.myec2 will be updated in-place
  ~ resource "aws_instance" "myec2" {
        id                                   = "i-0a84f30f5656d7800"
      ~ instance_type                        = "t2.micro" -> "t2.medium"
        tags                                 = {
            "Name" = "terraform"
        }
        # (28 unchanged attributes hidden)# (6 unchanged blocks hidden)
    }Plan: 0 to add, 1 to change, 0 to destroy.

As we can see terraform has detected the change.

Remember, terraform tries to ensure that the deployed infra is based on the desired state. If there is a difference between the two, terraform plan will show the necessary changes required to achieve the desired state.

Let’s do the terraform apply

This will update the instance type to t2.micro

Hope this clarifies what the desired state and current state is and how the terraform handles the difference between them.

We Hope this tasks will help you understand how to write a basic Terraform configuration file and basic commands on Terraform.

Don’t forget to post in on LinkedIn. Happy Learning:)

Happy Learning :)

linkdin---https://www.linkedin.com/in/gajanan-barure-7351a4140

Happy Learning :)

Thank you for reading!! Hope you find this helpful.

#day60#90daysofdevops#devopscommunity#

Shubham Londhe

Â