DevOps

Tuesday, 16 July 2019

Terraform Installation in and creating AWS EC2 Instance


Install wget and unzip

[root@ip-ec2-instance centos]# yum install wget
[root@ip-ec2-instance centos]# yum install unzip

Download Terraform binary from terraform.io 

[root@ip-ec2-instance centos]# wget https://releases.hashicorp.com/terraform/0.12.4/terraform_0.12.4_linux_amd64.zip
--2019-07-16 07:36:28--  https://releases.hashicorp.com/terraform/0.12.4/terraform_0.12.4_linux_amd64.zip
Resolving releases.hashicorp.com (releases.hashicorp.com)... 151.101.153.183, 2a04:4e42:24::439
Connecting to releases.hashicorp.com (releases.hashicorp.com)|151.101.153.183|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16039674 (15M) [application/zip]
Saving to: ‘terraform_0.12.4_linux_amd64.zip’

100%[================================================================================================>] 16,039,674  58.1MB/s   in 0.3s

2019-07-16 07:36:28 (58.1 MB/s) - ‘terraform_0.12.4_linux_amd64.zip’ saved [16039674/16039674]

Unzip Terraform binary to /usr/local/bin 

[root@ip-ec2-instance centos]# unzip terraform_0.12.4_linux_amd64.zip -d /usr/local/bin
Archive:  terraform_0.12.4_linux_amd64.zip
  inflating: /usr/local/bin/terraform

Export path to $PATH

[root@ip-ec2-instance ~]# export PATH=$PATH:/usr/local/bin
[root@ip-ec2-instance ~]# echo $PATH
/sbin:/bin:/usr/sbin:/usr/bin:/root/usr/local/bin:/usr/local/bin

Run terraform command and test

[root@ip-ec2-instance ~]# terraform
Usage: terraform [-version] [-help] <command> [args]

Create a dir and a .tf file with below code

[root@ip-ec2-instance ~]# mkdir terraform
[root@ip-ec2-instance ~]# cd terraform/
[root@ip-ec2-instance terraform]# vi launch_instance.tf

provider "aws" {
        access_key = "XXXXXXX"
        secret_key = "XXXXXXXXXXXXXXXX"
        region = "ap-south-1"
}

resource "aws_instance" "example" {
        ami = "ami-02e60be79e78fef21"
        instance_type = "t2.micro"
        key_name = "key-name"
        tags = {
         Name = "test-instance"
        }
}

AWS access_key and secret_key can also be configured with aws configure command.

In  .aws/credentials file

[terraform]
aws_access_key_id = xxxxxxxxxxxxxxxxxxx
aws_secret_access_key = xxx/xxxxxxxxxxxxx/xxxx
provider "aws" {
  region                  = "eu-west-2"
  shared_credentials_file = "/home/USER/.aws/credentials"
  profile                 = "terraform"
}

Run terraform init to initalize the backend

[root@ip-ec2-instance terraform]# terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (terraform-providers/aws) 2.19.0...

Run terraform plan 

[root@ip-ec2-instance terraform]# terraform plan

Run Terraform apply

[root@ip-ec2-instance terraform]# terraform apply

No comments:

Post a Comment