Terraform Scripts

Creating and attaching Security Group, IAM Role and Policy to an EC2 instance using Terraform Scripts

--

Authors: Rajat Kulkarni, Niraj Satpute

What is Terraform and why is it required?

Terraform is our tool of choice to manage the entire life cycle of infrastructure using infrastructure as code (IaC). That means declaring infrastructure components in configuration files that are then used by Terraform to provision, adjust and tear down infrastructure in various cloud providers.

IaC tools allow you to manage infrastructure with configuration files rather than through a graphical user interface. It also allows you to build, change, and manage your infrastructure in a safe, consistent and repeatable way by defining resource configurations that you can version, reuse, and share.

Using Terraform has several advantages over manually managing your infrastructure:

  • It can manage infrastructure on multiple cloud platforms
  • The human-readable configuration language helps you write infrastructure code quickly
  • Terraform’s state allows you to track resource changes throughout your deployments

Standardize your deployment workflow

You can compose resources from different providers into reusable Terraform configurations called modules and manage them with a consistent language and workflow. Providers define individual units of infrastructure, for example compute instances or private networks, as resources.

To deploy infrastructure with Terraform:

  • Scope — Identify the infrastructure for your project
  • Author — Write the configuration for your infrastructure
  • Initialize — Install the plugins Terraform needs to manage the infrastructure
  • Plan — Preview the changes Terraform will make to match your configuration
  • Apply — Make the planned changes

Prerequisites:

To follow this tutorial, you will need —

  • The Terraform CLI (0.14.9+) installed
  • The AWS CLI installed
  • An AWS account
  • AWS credentials
  • AWS Ec2 key-pair

Let’s have a quick overview of the above mentioned.

Amazon Web Services (AWS):

AWS is the world’s most comprehensive and broadly adopted cloud platform, offering over 200 fully featured services from data centers globally. Millions of customers — including the fastest-growing startups, largest enterprises, and leading government agencies — are using AWS to lower costs, become more agile, and innovate faster.

Amazon Simple Storage Service (Amazon S3):

Amazon S3 is an object storage service that offers industry-leading scalability, data availability, security, and performance. This means customers of all sizes and industries can use it to store and protect any amount of data for a range of use cases, such as data lakes, websites, mobile applications, backup and restore, archive, enterprise applications, IoT devices, and big data analytics.

In this practical experiment of integrating EC2 instance with S3 services using terraform, we have attached S3 create bucket and delete bucket services with EC2 instance.

Amazon Elastic Compute Cloud (Amazon EC2):

Amazon EC2 is a web service that provides secure, resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers. Amazon EC2’s simple web service interface allows you to obtain and configure capacity with minimal friction. It provides you with complete control of your computing resources and lets you run on Amazon’s proven computing environment.

An Amazon EC2 instance is a virtual server in Amazon’s Elastic Compute Cloud (EC2) for running applications on the Amazon Web Services (AWS) infrastructure.

AWS Identity and Access Management(IAM):

IAM is a web service that helps us to securely control access to AWS resources for users. We use IAM to control who can use our AWS resources and what resources they can use and in what ways (Authorization).

  • Role — An IAM role is an IAM entity that defines set of permissions for making AWS service requests. IAM roles are not associated with a specific users or groups instead, trusted entities assume roles such as IAM users, applications or AWS service such as EC2.Roles are like users but actually assigned to applications.
  • Policy — A policy is an object in AWS that, when associated with an entity or resource, defines their permissions. AWS evaluates these policies when a principal, such as a user, makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents.

Security Groups:

A security group acts as a virtual firewall for your EC2 instances to control incoming and outgoing traffic. Inbound rules control the incoming traffic to your instance and outbound rules control the outgoing traffic from your instance. If you don’t specify a security group, Amazon EC2 uses the default security group.

Now that we are all caught up with the basics and setup, lets have a hand-on experience. You can find the github project of this here.

EXECUTION

The flow of implementation starts with creating an AWS IAM Role.

  1. Configuration for creating an IAM role is given below

This is where the IAM role creation will be done.

  • This assume_role_policy parameter is a must to be given within the resource block. There are other optional parameters as well, such as name, version and path etc.
  • The resource block above constructs a resource of the stated TYPE (i.e. the initial parameter aws_iam_role) and NAME (i.e. the second parameter EC2S3TF1)
  • jsonencode encodes a given value to a string using JSON syntax. The JSON encoding is defined in RFC 7159
  • The Effect element is required and specifies whether the statement results in an allow or an explicit deny
  • AWS AssumeRole allows user to grant temporary credentials with additional privileges to different users as needed, following the principle of least privilege. To configure AssumeRole access, user must define an IAM role that specifies the privileges that it grants and which entities can assume it.

2. Creating an AWS IAM policy using Terraform:

The Terraform script

  • EC2S3policy1 is a policy name defined for EC2 instance that is being created. Name, role, policy, version, statement are the other optional parameters for creating an AWS policy for any resource
  • EC2S3TF1 is a role name that is defined along with the EC2S3policy1 for the EC2 instance that is being created
  • Within the Action block the services that user wants to provide for the particular resource (EC2 instance) are specified i.e. EC2 instance connect , S3 create and delete bucket etc.
  • In the key-pair value for Resource, [* ]has been used because when user works with multiple resources, user might find it useful to manage them as a group rather than move from one AWS service to another for each task
  • User can provide an optional identifier, Sid (statement ID) for the policy statement. User can assign a Sid value to each statement in a statement array

3. Creating Security Groups using Terraform :

The Terraform script

  • Inbound Rules — These rules are used to control the inbound traffic or also known as ingress. Outbound Rules — These rules are used to control the outbound traffic or also known as egress
  • When user creates a VPC, user must specify a range of IPv4 addresses for the VPC in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0. 0.0/16 . This is the primary “CIDR block” user VPC.

Here in the above script CIDR blocks are specified as “0.0.0.0/0” meaning that it is available anywhere

  • from_port(Required) — Start port (or ICMP type number if protocol is icmp or icmpv6)
  • to_port (Required) — End range port (or ICMP code if protocol is icmp)

4 . Creating an EC2 instance using Terraform

Terraform Script

  • Initially user has to give AWS credentials for configuration in the terraform script as shown above provider aws
  • Here ec201 is a name of the instance being created. User must specify an AMI based on region. In the above script T2.micro instance type used because it is available for free. This instance is being attached to security group named TerraformEc2_security1. The key-name (user defined) ec2instance must be created before using AWS console
  • The aws_default_vpc resource allows you to manage a region’s default VPC but Terraform cannot destroy it. Removing this resource from your configuration will remove it from your statefile and management, but will not destroy the VPC. You can resume managing the VPC via the AWS Console
  • Availability_zone (Required) — The AZ where the EBS volume will exist.
  • Size(Optional) — The size of the drive in GiBs
  • Tags(Optional) — A map of tags to assign to the resource. If configured with a provider default_tags configuration block present, tags with matching keys will overwrite those defined at the provider-level

Terraform Commands :

The following commands should be executed from the terminal in the respective order within the directory where Terraform Configuration files are saved-

  • Initializing a new or an existing Terraform configuration
  • Generate and show an execution plan from the resources we’re trying to provision. After executing this command you will get a prompt

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.

  • So after applying “terraform plan” command user has to execute the below command, where state of the plan is stored in terraform file called config.terraform
  • The “terraform apply” command execute the actions proposed in a Terraform plan

In the screenshot below, we can see that there is an existing‘ec2’ instance and a new instance(-) is initialized after preforming above steps.

Conclusion :

Terraform is an open source tool that helps teams manage infrastructure in an efficient, automated and reusable manner. It has a simple modular syntax and supports multi-cloud infrastructure configuration. In simple words we can say that Terraform configuration files acts as an interface and you can create resources as per the requirements directly through terminal, which gives you an extra layer of governance and control. Enterprises can use Terraform in their DevOps methodology to construct, modify, manage and deliver infrastructure at a faster pace with less manual intervention.

If you have reached this far, thank you for reading this blog, I hope you found it useful 😃 . Give us a Follow for more content on technology, productivity, work habits and more!

--

--