#TerraWeek Day 3

#TerraWeek Day 3

ยท

5 min read

Task 1:Create a Terraform configuration file to define a resource of AWS EC2 instance

create terraform.tf : In the context of infrastructure as code (IaC) and specifically using Terraform, a "terraform block" refers to a fundamental part of a Terraform configuration file (.tf). This block is typically used to define various settings and configurations for your Terraform project. The terraform block is usually placed at the beginning of a Terraform configuration file.

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "5.41.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

create variables.tf :The variables.tf file in a Terraform project is typically used to declare input variables. These variables serve as placeholders for values that can be passed into Terraform configurations from external sources, such as user inputs, environment variables, or values retrieved from other systems

variable "ami_id"{
     default="ami-080e1f13689e07408"
}

variable "instance_type"{
     default = "t2.micro"
}

variable "instance_name"{
     default = "example-server"
}

Here's a basic Terraform configuration file (main.tf) to define an AWS EC2 instance resource:

resource "aws_instance" "my_instance" {
  ami           = var.ami-id
  instance_type = var.instance_type
            tag = {
               Name = var.instance_name
           }
}

In this configuration:

  • We first configure the AWS provider to specify the region where the resources will be provisioned.

  • Then, we define an AWS EC2 instance resource using the aws_instance block. Within this block, we specify the AMI ID (ami) and instance type (instance_type) for the EC2 instance.

  • Additionally, we can provide optional configurations such as tags to further customize the instance.

Remember to replace placeholder values like AMI ID and region with your actual values. Also, ensure that you have appropriate AWS credentials configured either through environment variables or AWS shared credentials file (~/.aws/credentials).

Task 2:Check state files before running plan and apply commands & Use validate command to validate your .tf file for errors and provide the Output generated by each commands.

Validate configuration files, use terraform validate : Before applying changes, it's crucial to validate your Terraform configuration files for syntax errors and potential issues. You can use the terraform validate command for this purpose.

output :

This command checks the configuration files in the current directory for syntax errors and validates the configuration against provider requirements.

  • This output indicates that the Terraform configuration files in the current directory are valid and contain no syntax errors.

validating your Terraform configuration files before applying changes, you can ensure that your infrastructure changes are based on a consistent and error-free configuration.

Task 3:Add a provisioner to the configuration file to configure the resource after it is created and use Terraform commands to apply for changes and destroy to remove resources.

In Terraform, provisioners are used to perform actions on the local machine or a remote resource (like an EC2 instance) after the resource has been created or destroyed. They are typically used for tasks such as configuration management, initializing instances, or running scripts. Terraform provides several types of provisioners:

local-exec Provisioner:

  • The local-exec provisioner runs commands on the machine where Terraform is executed (i.e., your local machine). It is often used for tasks that do not require remote execution, such as running scripts or local tools.

resource "aws_instance" "my_instance" {
  ami           = var.ami_id
  instance_type = var.instance_type

            tags = {
              Name = var.instance_name
         }

          provisioner "local-exec" {
                         command = "echo ${self.public_ip} >> public_ips.txt"
                    }
}

remote-exec Provisioner:

  • The remote-exec provisioner runs commands on a remote resource, typically an EC2 instance or another compute resource that supports SSH or WinRM. It is commonly used for tasks like software installation or configuration on newly created instances.

      resource "aws_instance" "my_instance" {
        ami           = var.ami_id
        instance_type = var.instance_type
    
                  tags = {
    
                     Name = var.instance_name
                 }
                provisioner "remote-exec" {
                  inline = [
                    "echo 'Hello, Terraform!' > /tmp/terraform_hello.txt"
                  ]
            }
      }
    

    In this modified configuration:

    • We've added a provisioner to the aws_instance resource using the provisioner block. The remote-exec provisioner allows you to execute shell commands on the newly created EC2 instance.

      -->The provisioner is configured to execute a simple shell command (echo 'Hello, Terraform!' > /tmp/terraform_hello.txt) after the instance is created. This command writes a message to a file (/tmp/terraform_hello.txt) on the instance.

      • You can customize the provisioner and shell command as needed for your specific use case.

After adding the provisioner, you can use Terraform commands to apply changes and destroy resources:

file Provisioner:

  • The file provisioner is used to copy files or directories from the local machine to a remote resource. It's useful for transferring configuration files, scripts, or other resources to provisioned instances.
    provisioner "file" {
      source      = "local/path/to/file"
      destination = "/remote/path/on/instance"
    }

Apply Changes: To apply the changes and create the AWS EC2 instance with the provisioner, use the terraform apply command:

  • terraform apply

    Destroy Resources: To remove the created resources (in this case, the AWS EC2 instance), use the terraform destroy command:

Task 4:-Add lifecycle management configurations to the configuration file to control the creation, modification and deletion of the resource and use Terraform commands to apply the changes.

1.create_before_destroy = true ensures that Terraform creates a new instance before destroying the existing one when changes are made. This allows for zero-downtime deployments by minimizing the time when no instance exists.

2.prevent_destroy = false allows Terraform to destroy the instance during the terraform destroy command. By default, Terraform prevents accidental destruction of resources, but setting it to false enables the resource to be destroyed.

To apply changes and create or update the resource with the lifecycle management configurations, you can use the following command: terraform apply

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = var.instance_name
  }


   lifecycle {
    create_before_destroy = true
    prevent_destroy       = false

    ignore_changes = [
      instance_type,
      ami,
      tags
    ]
  }
}

run this terraform commands :

terraform init
terraform validate
terraform plan
terraform apply
terraform destory # after creation

After terraform apply command EC2 instance will be created.

To destroy the resources created by the Terraform configuration, you can use the terraform destroy

Happy learning!๐Ÿ˜ƒ

ย