Uncategorized,Cloud

Simplifying Infrastructure Management as Code on AWS with Terraform

Person programming with multiple screens displaying code, representing infrastructure automation with Terraform on AWS.

Content

Agility and scalability are cornerstones of any modern IT environment. In the cloud world, especially AWS, managing resources manually can become a bottleneck, leading to errors, inconsistencies and slowdowns. This is where the concept of Infrastructure as Code (IaC) comes in, and Terraform stands out as a key tool for solving these challenges.

In this article, I explore how Terraform simplifies the management of your AWS infrastructure, allowing you to define, provision and manage your resources in an efficient, repeatable and secure way.

The challenge of manually managing a cloud infrastructure

Managing constantly evolving cloud environments manually is unsustainable. It often results in:

  • Environment inconsistency: difficulty in ensuring that the development, homologation and production environments are identical.
  • Human error: manual configurations are prone to mistakes and forgetfulness.
  • Slow provisioning: significant delays in making new resources or entire environments available.
  • Lack of auditing and versioning: difficulty in tracing who did what and when, and in reverting changes.

What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is the practice of managing and provisioning technology infrastructure through code files, rather than manually. Basically, your infrastructure (servers, networks, databases) is treated as software.

The main benefits of IaC include:

  • Repeatability and consistency: ensures that environments are always provisioned in the same way.
  • Automation: eliminates manual tasks, speeding up provisioning and management.
  • Versioning: allows version control systems (such as Git) to be used to manage changes to the infrastructure.
  • Collaboration: facilitates teamwork in infrastructure management.

Because Terraform…

Among the various IaC tools, Hashicorp ‘s Terraform stands out:

  • Take a declarative approach: you describe the desired state of your infrastructure (what you want to exist), and Terraform takes care of planning and executing the actions needed to achieve that state.
  • Have an execution plan: before applying any changes, the command terraform plan command generates a detailed plan of all the actions that will be carried out. This allows for a complete review and the avoidance of unwanted surprises.
  • Modularity and reusability: Terraform encourages the creation of reusable modules. This means that you can package complex configurations and reuse them in different projects or environments, promoting standardization and efficiency.
  • Broad ecosystem: although my focus is on AWS, Terraform supports a wide range of providers (Azure, Google Cloud (GCP), Kubernetes, etc.), making it a versatile tool for multi-cloud or hybrid environments.

How to get started with Terraform on AWS (first steps)

See how simple it is to start using Terraform to provision basic resources on AWS.

Installation

First of all, you’ll need to install Terraform on your machine. To do this, go to the official documentation(here) so you can download the most up-to-date version and follow the correct step-by-step instructions for your system.

Note: for Windows users like me, a very simple way to install Terraform is via the Chocolatey package manager, using the command:

PS C:\Users\user> choco install terraform

Configuring AWS credentials

In order for Terraform to interact with your AWS account and create/manage resources, it needs access credentials. Follow the steps below to create them and add them to your machine.

Create IAM user and access credentials

Home screen of the AWS IAM panel, use the “Users” option in the console navigation to start configuring the credentials.

In the IAM Panel of your AWS account, create a new user (it is particularly important to have your own user set up for this interaction).

  • Go to Users in the console navigation.
  • On the users screen, click on the Create user button, and on the following screens
    :Polylang placeholder do not modify
  • Back on the user screen now, click on the name of your new user to access their details
    .Polylang placeholder do not modify

Configuring access credentials in the system

In order for Terraform to interact with your AWS account and create/manage resources, it needs access credentials. There are a few ways to configure this, but the most common are:

  • Environment variables: this is the simplest method for quick, local use. You set your access keys directly in the terminal:
export AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"
export AWS_DEFAULT_REGION="YOUR_REGION"
  • Shared Credentials File (~/.aws/credentials): this is the most recommended method for development machines. For those who use the AWS CLI, it is very familiar. Terraform, like the AWS CLI, will look for the credentials in this file
    .Polylang placeholder do not modify
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

For the default profile ([default]), Terraform will use these credentials automatically. You can create named profiles and specify which one to use in the provider.

For production environments or use on CI/CD servers/pipelines, the safest way is to configure an IAM Role for the EC2 instance (or other service) running Terraform. This way, credentials don’t need to be stored explicitly, as the instance assumes a profile with the necessary permissions.

Configuring the AWS provider in Terraform

Create a .tf file (e.g: main.tf) and define the AWS provider. If you used environment variables or the [default] profile in the credentials file, Terraform will find it automatically. Otherwise, you can specify the profile:

provider "aws" {
region = "us-east-1" # Or your preferred region
# profile = "your_aws_profile" # Only if you are using a profile named in ~/.aws/credentials
}

Provisioning a simple resource (EC2 Instance)

Within the same file, we’ll define a basic EC2 instance:

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

resource "aws_instance" "example_server" {
ami = "ami-0abcdef1234567890" # Use a valid AMI for your region
instance_type = "t2.micro"
tags = {
Name = "MyTerraformServer"
}
}

Note: replace ami-0abcdef1234567890 with a valid AMI for the AWS region you have chosen. You can find AMIs in the AWS console when trying to launch an instance.

What my file looks like:

Essential commands

terraform init: initializes the working directory, downloading the plugins from the AWS provider.

terraform plangenerates and displays an execution plan, detailing what Terraform will do (create, modify or destroy resources) without applying the changes.

terraform applyexecutes the actions defined in the plan, provisioning or modifying your infrastructure on AWS. Confirm with"yeswhen prompted.

terraform destroy: destroys all resources managed by your Terraform file. Use with extreme caution in production environments!

Using the command sequence above, you should get a result like the one in the image below.

After executing the command terraform applycommand, your new EC2 instance will be running.

Best Practices and Tips for Using Terraform on AWS

To maximize the benefits of Terraform and keep your infrastructure organized:

  • Modularization: divide your code into logical and reusable modules (e.g. one module for networks, another for servers, another for databases). This improves the organization, reusability and maintainability of the code.
  • State versioning (Terraform State): Terraform maintains a state file that maps its actual resources in the cloud. It is crucial to store this state in a secure, shared location, such as an S3 bucket, ideally with state locking (via DynamoDB) to avoid team conflicts.
  • Use variables and outputs: use variables to parameterize your code (e.g. instance size, environment name) and outputs to export important information (e.g. instance IPs). This makes your code more flexible and dynamic.
  • CI/CD integration: integrate Terraform into your Continuous Integration/Continuous Delivery (CI/CD) pipeline. This automates the process of validating, planning and applying changes to the infrastructure, guaranteeing consistency and agility in delivery.
  • Security and credential management: never store access credentials directly in the code. Use tools such as AWS Secrets Manager, HashiCorp Vault or environment variables to manage secrets securely.

Conclusion

Terraform is an indispensable tool in the arsenal of any DevOps Engineer or AWS Cloud Architect. By adopting Infrastructure as Code, you not only automate resource provisioning, but also gain in consistency, security, collaboration and, above all, agility.

Manually managing infrastructure is a risk your business can’t afford to take in today’s environment. With Terraform, you have the power to define, replicate and manage complex environments on AWS programmatically, freeing up time to focus on innovation and delivering value.

Share this content:

Leave a Reply

Your email address will not be published. Required fields are marked *

Logo Branca - aamaguelniski

Antonio Augusto | DevOps Engineer | AWS Cloud Specialist | DBA | Linux

Passionate about technology, DevOps professional, and AWS Cloud specialist. Dedicated to building solutions that simplify development and drive projects forward.

Let's Work Together
Let's Work Together
Let's Keep In Touch