Beginner Setup AWS EC2 with Terraform scripts

Beginner Setup AWS EC2 with Terraform scripts

1.Generate Access keys (access key ID and secret access key) in AWS account

Terraform installed on your Desktop/Laptop needs to communicate with AWS and to make this communication terraform needs to be authenticated.

For authentication, we need to generate Access Keys (access key ID and secret access key). These access keys can be used for making - programmatic calls to AWS from the AWS CLI, Tools for PowerShell, AWS SDKs, or direct AWS API calls.

  1. Goto My Security Credentials

AWS security credentials

  1. On Your Security Credentials page click on Access keys (access key ID and secret access key)

AWS access key create new access key

  1. Click on Create New Access key

  2. Copy the Access Key ID and Secret Access Key (Note:- You can view the Secret Access Key only once, so make sure to copy it.)

AWS access key id and secret access key generated

2. Create your first Terraform infrastructure (main.tf)

Before we start writing terraform script, the first thing to learn over here is - "You need to save your configuration with .tf extension"

As Terraform is developed by HashiCorp, so we use HCL for writing the terraform scripts.

We will start by creating an empty main.tf file.

2.1 Provider

The first line of code in which we are going to write is provider.

We need to tell terraform which cloud provider we are going to connect .e.g - AWS, Google, or Azure

As this article is focused on AWS, so we are going to mention AWS as our provider.

Here is the basic syntax for the provider

1 resource "<PROVIDER>_<TYPE>" "<NAME>" {
2   [CONFIG ]
3 }

YAML

  1. "PROVIDER _ TYPE" - aws, google

  2. "NAME" - You can define your name.

This is how our final main.tf will look like for AWS -

1 provider "aws" {
2  region     = "eu-central-1"
3  access_key = "XXXXXXXXXXXXXXXXXXXX"
4  secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
5 }

YAML

Note: You can copy access_key and secret_key fromStep-2

2.2 resource - "aws_instance"

Now after defining the provider, next we are going define is resource.

So what do you mean by resource?

Resource - It is something that we are going to provision/start on AWS.

Now for this article, we are going to provision EC2 instance on AWS.

But before we provision the EC2 instance, we need to gather few points -

  1. ami = you need to tell Terraform which AMI(Amazon Machine Image) you are going to use. Is it going to be Ubuntu, CentOS or something else

  2. instance_type = Also based on your need you have to choose the instance_type and it can be t2.nano, t2.micro, t2. small etc.

2.3 How to find ami (Amazon Machine Image)

  1. To find the correct ami you need to Goto: Services -> EC2

AWS services EC2

  1. In the left Navigation you will find Images -> AMIs

AWS AMIs option in the left navigation

  1. On the search menu click on public images and then type Ubuntu.

AWS access key id and secret access key generated

  1. Copy the AMI ID from the search result.

AWS access key id and secret access key generated

2.4 How to find correct instance_type

You can find the correct ìnstance_type` by visiting this page.

Since I am looking for a very basic instance_type not production level instance, so I choose t2.micro

Here is the aws_instance configuration -

1 resource "aws_instance" "ec2_example" {
2    ami = "ami-0767046d1677be5a0"  
3    instance_type = "t2.micro" 
4    tags = {
5        Name = "Terraform EC2"
6    }
7 }

BASH

3. terraform commands

Alright, now we have completed all the pre-requisites for provisioning our first ec2 instance on the AWS.

3.1 terraform plan

The first command which we are going to run is -

1 terraform init

BASH OUTPUT OF ABOVE COMMAND

 1 Initializing the backend...
 2
 3 Initializing provider plugins...
 4 Reusing the previous version of hashicorp/aws from the dependency lock file
 5 Installing hashicorp/aws v3.32.0...
 6 Installed hashicorp/aws v3.32.0 (signed by HashiCorp)
 7
 8 Terraform has been successfully initialized!
 9
10 You may now begin working with Terraform. Try running "terraform plan" to see
11 any changes that are required for your infrastructure. All Terraform commands
12 should now work.
13
14 If you ever set or change modules or backend configuration for Terraform,
15 rerun this command to reinitialize your working directory. If you forget, other
16 commands will detect it and remind you to do so if necessary

BASH

The terraform init command is responsible for downloading all the dependencies which are required for the provider AWS.

Once you issue the terraform init command it will download all the provider's dependencies on your local machine.

3.2 terraform plan

This command will help you to understand how many resources you are gonna add or delete.

Here is the command -

1 terraform plan

BASH OUTPUT OF ABOVE COMMAND

 1 An execution plan has been generated and is shown below.
 2 Resource actions are indicated with the following symbols:
 3  + create
 4
 5 Terraform will perform the following actions:
 6
 7  # aws_instance.ec2_example will be created
 8  + resource "aws_instance" "ec2_example" {
 9      + ami                          = "ami-0767046d1677be5a0"
10      + arn                          = (known after apply)
11      + associate_public_ip_address  = (known after apply)
12      + availability_zone            = (known after apply)
13      + cpu_core_count               = (known after apply)
14      + cpu_threads_per_core         = (known after apply)
15      + get_password_data            = false
16      + host_id                      = (known after apply)
17      + id                           = (known after apply)
18      + instance_state               = (known after apply)
19      + instance_type                = "t2.micro"
20      + ipv6_address_count           = (known after apply)
21      + ipv6_addresses               = (known after apply)
22      + key_name                     = (known after apply)
23      + outpost_arn                  = (known after apply)
24      + password_data                = (known after apply)
25      + placement_group              = (known after apply)
26      + primary_network_interface_id = (known after apply)
27      + private_dns                  = (known after apply)
28      + private_ip                   = (known after apply)
29      + public_dns                   = (known after apply)
30      + public_ip                    = (known after apply)
31      + secondary_private_ips        = (known after apply)
32      + security_groups              = (known after apply)
33      + source_dest_check            = true
34      + subnet_id                    = (known after apply)
35      + tags                         = {
36          + "Name" = "Terraform EC2"
37        }
38      + tenancy                      = (known after apply)
39      + vpc_security_group_ids       = (known after apply)
40
41      + ebs_block_device {
42          + delete_on_termination = (known after apply)
43          + device_name           = (known after apply)
44          + encrypted             = (known after apply)
45          + iops                  = (known after apply)
46          + kms_key_id            = (known after apply)
47          + snapshot_id           = (known after apply)
48          + tags                  = (known after apply)
49          + throughput            = (known after apply)
50          + volume_id             = (known after apply)
51          + volume_size           = (known after apply)
52          + volume_type           = (known after apply)
53        }
54
55      + enclave_options {
56          + enabled = (known after apply)
57        }
58
59      + ephemeral_block_device {
60          + device_name  = (known after apply)
61          + no_device    = (known after apply)
62          + virtual_name = (known after apply)
63        }
64
65      + metadata_options {
66          + http_endpoint               = (known after apply)
67          + http_put_response_hop_limit = (known after apply)
68          + http_tokens                 = (known after apply)
69        }
70
71      + network_interface {
72          + delete_on_termination = (known after apply)
73          + device_index          = (known after apply)
74          + network_interface_id  = (known after apply)
75        }
76
77      + root_block_device {
78          + delete_on_termination = (known after apply)
79          + device_name           = (known after apply)
80          + encrypted             = (known after apply)
81          + iops                  = (known after apply)
82          + kms_key_id            = (known after apply)
83          + tags                  = (known after apply)
84          + throughput            = (known after apply)
85          + volume_id             = (known after apply)
86          + volume_size           = (known after apply)
87          + volume_type           = (known after apply)
88        }
89    }
90
91 Plan: 1 to add, 0 to change, 0 to destroy.
92
93 ------------------------------------------------------------------------
94
95 Note: You didn't specify an "-out" parameter to save this plan, so Terraform
96 can't guarantee that exactly these actions will be performed if
97 "terraform apply" is subsequently run.

...

BASH

As you can see the output of terraform plan, at the end it will show all the resources added and deleted.

(Note:- This command is not going to provision start your t2.micro instance)

3.3 terraform apply

This command will do some real stuff on AWS. Once you will issue this command, it will be going to connect to AWS and then finally going to provision AWS instance.

Here is the command -

1 terraform apply

BASH

 1 Plan: 1 to add, 0 to change, 0 to destroy.
 2
 3 Do you want to perform these actions?
 4  Terraform will perform the actions described above.
 5  Only 'yes' will be accepted to approve.
 6
 7  Enter a value: yes
 8
 9 aws_instance.ec2_example: Creating...
10 aws_instance.ec2_example: Still creating... [10s elapsed]
11 aws_instance.ec2_example: Still creating... [20s elapsed]
12 aws_instance.ec2_example: Still creating... [30s elapsed]
13 aws_instance.ec2_example: Creation complete after 33s [id=i-0a948ac635a2010f1]
14
15 Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

BASH

As you can see the log output has created t2.micro instance.

3.4 Verify the EC2 setup

Let's verify the setup by going back to AWS console.

Goto -> Services -> EC2 you should see 1 instance running.

AWS ec2 running instance

AWS ec2 running instance with more details

You can also see the Tag name - Terraform EC2 which we mentioned in the terraform script.

3.5 terraform destroy

Now we have seen how to write your terraform script and how to provision your EC2 instance.

Let see how to remove or delete everything from AWS.

We are going to use the command -

1 terraform destroy

BASH

 1 Plan: 0 to add, 0 to change, 1 to destroy.
 2
 3 Do you want to destroy all resources?
 4  Terraform will destroy all your managed infrastructure, as shown above.
 5  There is no undo. Only 'yes' will be accepted to confirm.
 6
 7  Enter a value: yes
 8
 9 aws_instance.ec2_example: Destroying... [id=i-0a948ac635a2010f1]
10 aws_instance.ec2_example: Still destroying... [id=i-0a948ac635a2010f1, 10s elapsed]
11 aws_instance.ec2_example: Still destroying... [id=i-0a948ac635a2010f1, 20s elapsed]
12 aws_instance.ec2_example: Still destroying... [id=i-0a948ac635a2010f1, 30s elapsed]
13 aws_instance.ec2_example: Still destroying... [id=i-0a948ac635a2010f1, 40s elapsed]
14 aws_instance.ec2_example: Destruction complete after 40s
15
16 Destroy complete! Resources: 1 destroyed.

BASH

It will remove all the running EC2 Instances.

Like ❤️ if you love my Blog and Thanks for coming Here