Infrastructure As Code on AWS With Terraform
Overview :
AWS is a popular cloud computing platform that offers a wide range of services for building and managing cloud-based applications. Terraform is an open-source tool that enables you to define and provision infrastructure as code. When used together, AWS and Terraform allow for the easy deployment and management of complex infrastructure.
What is Infrastructure as code?
Infrastructure as Code (IaC) is a software engineering practice that involves managing and provisioning infrastructure through machine-readable files, rather than manually configuring servers and infrastructure components. The code for the infrastructure can be version-controlled, tested, and shared across teams, making it easier to manage infrastructure changes and reduce the risk of errors.
Using IaC, you can define your infrastructure in a declarative manner using a domain-specific language (DSL), such as Terraform. This allows you to easily provision and manage your infrastructure resources in a repeatable and scalable way.
IaC has become increasingly popular in recent years due to the rise of cloud computing and the need for infrastructure to be more flexible and scalable. By using IaC tools such as Terraform, you can reduce the time and effort required to deploy infrastructure and ensure that it is always in the desired state.
In summary, Infrastructure as Code is a practice of managing and provisioning infrastructure through code. By using IaC tools like Terraform, you can easily create, manage, and version-control your infrastructure, making it more flexible, scalable, and easier to manage.
How does Infrastructure as Code work?
Infrastructure-as-code (IaC) is an approach to managing IT infrastructure using machine-readable definition files instead of manual processes. The core idea of IaC is to treat your infrastructure like software by defining it in code, which can be version-controlled, tested, and deployed in a repeatable and automated way.
When you use IaC, you write code that describes the desired state of your infrastructure. This code is typically written in a domain-specific language (DSL) or configuration languages, such as Terraform, Ansible, Chef, Puppet, or CloudFormation. The code defines the resources, configuration, and relationships between them, and can be used to create, modify, or delete infrastructure resources.
IaC tools provide a set of features to manage infrastructure resources, such as creating, modifying, and deleting resources, managing dependencies, performing rolling updates, and managing drift. They also provide integration with version control systems and continuous integration/continuous deployment (CI/CD) pipelines.
Overall, IaC helps you manage infrastructure in a more automated, scalable, and predictable way, reducing errors, improving agility, and speeding up deployment times.
What is the Imperative and Declarative approach?
The imperative approach to IaC involves specifying the exact sequence of steps that are required to provision and configure infrastructure resources. In other words, you define the exact actions that need to be taken to create, configure, and deploy your infrastructure. This approach is similar to writing a script or a set of instructions( Like script files, and CLI tools you using).
On the other hand, the declarative approach to IaC involves describing the desired state of your infrastructure, rather than the specific steps required to achieve that state. In this approach, you define the desired configuration of your infrastructure resources, and the IaC tool, such as Terraform, determines the sequence of steps needed to achieve that state( It can understand existence).
In summary, the imperative approach involves specifying the exact steps required to provision and configure infrastructure resources, while the declarative approach involves defining the desired state of your infrastructure and letting the IaC tool determine the necessary steps to achieve that state. The declarative approach is generally considered more efficient and reliable and is the approach used by tools like Terraform.
What is the Mutable and Immutable approach?
The mutable approach involves making changes to existing infrastructure resources in place. This means that the infrastructure resources are modified and updated with new configurations without creating new resources or destroying and recreating them. This approach is commonly used in traditional on-premise IT infrastructure management, where it is often easier to modify existing servers or network devices rather than replace them.
The immutable approach, on the other hand, involves creating entirely new infrastructure resources to replace the existing ones, rather than modifying them in place. In this approach, any change to the infrastructure results in the creation of a new set of resources, and the old ones are destroyed. This approach is commonly used in cloud-based environments, where resources are designed to be disposable and easily reproducible.
Using the immutable approach with IaC can offer several benefits, such as:
- Consistency: Immutable infrastructure ensures that all resources are created from the same configuration and are consistent in terms of software and application versions.
- Reproducibility: Since infrastructure resources are disposable and easily reproducible, they can be replaced quickly and efficiently in the event of a failure or issue.
- Security: Immutable infrastructure is less susceptible to security threats since any changes or modifications are made to a new set of resources, rather than to existing ones that may already be compromised.
- Scalability: Immutable infrastructure can be easily scaled up or down by creating new sets of resources, rather than modifying existing ones.
What is Terraform?
Terraform is an open-source infrastructure-as-code (IaC) tool that allows you to define, manage, and automate your cloud infrastructure in a declarative way. It enables you to create, modify, and destroy cloud resources such as virtual machines, networks, and storage using a simple configuration language. Terraform supports various cloud platforms such as AWS, Azure, Google Cloud, and many others. With Terraform, you can manage your infrastructure in a consistent and repeatable manner, making it easier to deploy and maintain your applications.
Using Terraform, you can create, modify, and delete infrastructure resources on AWS. This process is known as provisioning. You can also use Terraform to manage infrastructure as code by version controlling the HCL files in a code repository. To use Terraform with AWS, you need to first create an AWS account and configure the AWS CLI on your machine. Once you have done this, you can start creating Terraform files that define your infrastructure.
Terraform uses a concept called providers to interact with various cloud platforms. To interact with AWS, you need to specify the AWS provider and provide your AWS credentials. Once you have done this, you can start defining your infrastructure resources. In your Terraform files, you define the desired state of your infrastructure. Terraform then compares the desired state with the current state of your infrastructure and determines the necessary changes to make your infrastructure match the desired state. One of the key benefits of using Terraform with AWS is the ability to manage your infrastructure in a scalable and repeatable way. With Terraform, you can easily create and manage infrastructure across multiple AWS regions and accounts.
In summary, using Terraform to provision and manage infrastructure on AWS offers a number of benefits. It allows you to define and manage infrastructure as code, version control your infrastructure, and scale your infrastructure across multiple regions and accounts.
Works With Terraform
I’m going to show how we are going to work with Terraform and AWS in the Windows operating system. Here’s a step-by-step guide on how to install Terraform and connect it to your AWS account:
Prerequisites
Before you get started, you will need the following:
- An AWS account with administrator access.
- A Windows computer.
- Administrative privileges on your computer.
Installing Terraform
To install Terraform on Windows, follow these steps:
- Download the Terraform ZIP archive from the official website: https://www.terraform.io/downloads.html
2. Extract the ZIP archive to a directory on your computer. You can use a tool like 7-Zip or Windows Explorer to extract the archive.
3. Open the Start menu and search for “Environment Variables”.
4. Click “Edit the system environment variables”.
5. Click “Environment Variables”.
6. Under “System Variables”, click “New”.
7. Enter “TERRAFORM_HOME” for the variable name.
8. Enter the path to the directory where you extracted Terraform as the variable value. For example, if you extracted Terraform to C:\Program Files\Terraform
, you would enter C:\Program Files\Terraform
.
9. Click “OK” to close the Environment Variables window.
10. Open a new command prompt and run the following command to verify that Terraform is installed:
terraform version
Output:
Connecting to AWS
To connect your AWS account to Terraform, follow these steps:
- For the best practice, you need to create a new IAM user for AWS. Open the AWS Management Console and navigate to the IAM service.
2. Click “Users” in the left sidebar.
3. Click “Add user”.
4. Enter a name for the user, such as “terraform-user”.
5. Select “Programmatic access” as the access type.
6. Click “Next: Permissions”.
7. Click “Attach existing policies directly”.
8. Search for “AdministratorAccess” and select it.
9. Click “Next: Tags”.
10. Click “Next: Review”.
11. Review the user details and click “Create user”.
12. Save the access key and secret key that are displayed. You will need these later.
Now you are successfully set up terraform environment and AWS cloud environment. Now look at basic terraform commands ( I’ll discuss these commands deeply in my next articles )
Basic Terraform Commands:
- terraform init
The terraform init
command is used to initialize a new or existing Terraform configuration. This command downloads the required provider plugins and sets up the backend for storing state.
2. terraform plan
The terraform plan
command is used to create an execution plan for the Terraform configuration. This command shows what resources Terraform will create, modify, or delete when applied.
3. terraform apply
The terraform apply
command is used to apply the Terraform configuration and create or modify resources in the target environment.
4. terraform destroy
The terraform destroy
command is used to destroy all resources created by the Terraform configuration. This command should be used with caution, as it can permanently delete resources.
5. terraform validate
The terraform validate
command is used to check the syntax and validity of the Terraform configuration. This command can be used to catch errors in the configuration before running terraform plan
or terraform apply
.
6. terraform refresh
The terraform refresh
command is used to update the state of the Terraform configuration to match the real-world resources. This command can be used to refresh the state after resources have been created or modified outside of Terraform.
7. terraform state
The terraform state
command is used to manage the state of the Terraform configuration. This command can be used to view, modify, or migrate the state.
8. terraform output
The terraform output
command is used to display the output values of the Terraform configuration. This command can be used to obtain values from the configuration for use in other tools or scripts.
9. terraform import
The terraform import
command is used to import existing resources into the Terraform state. This command can be used to manage existing resources with Terraform.
LAB: Creating AWS EC2 instance using Terraform
Steps:
- Create a new directory for your Terraform code and navigate to it in the terminal.
- Create a new file named
main.tf
and add the following code:
provider "aws" {
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
region = "us-east-1"
}
resource "aws_key_pair" "example" {
key_name = "example-key"
public_key = file("~/.ssh/id_rsa.pub")
}
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c71c99"
instance_type = "t2.micro"
key_name = aws_key_pair.example.key_name
tags = {
Name = "Example Instance"
}
}
This code defines an AWS provider and creates an EC2 instance with the following settings:
- The Amazon Machine Image (AMI) ID is set to the latest Amazon Linux 2 image available in the N.Verginia region.
- The instance type is set to t2.micro.
- The key pair is set to
example-key
, which is created in the next step. - The instance is tagged with the name “Example Instance”.
2. Save the file and run the following command to initialize the Terraform working directory:
terraform init
This will download and install the necessary plugins for the AWS provider.
3. Run the ‘terraform plan’ command
terraform plan
This will show you the changes that Terraform will make to your AWS resources based on your main.tf
file.
4. If everything looks good, run the following command to apply the changes:
terraform apply
This will create the EC2 instance and the key pair.
5. After the instance is created, you can log in to it using SSH. Run the following command to get the public IP address of the instance:
terraform show | grep public_ip
This will show you the public IP address of the instance.
7. Use the following command to SSH into the instance:
ssh -i ~/.ssh/example-key.pem ec2-user@PUBLIC_IP_ADDRESS
ssh -i ~/.ssh/example-key.pem ec2-user@PUBLIC_IP_ADDRESS. You can now modify the main.tf
file to create additional resources and run the terraform apply
command to update your infrastructure.
You can learn to terraform more things using this reference link https://learn.hashicorp.com/
Thanks for reading! Let’s see you in the next article. Don’t forget to follow me via medium and leave a 👏.