Skip to main content

Command Palette

Search for a command to run...

Infrastructure as Code (IaC) vs API as Code

Updated
•12 min read•View as Markdown
Infrastructure as Code (IaC) vs API as Code
A

I'm Yasheela, an undergraduate with a deep interest in DevOps, and cloud technologies. Currently working on exciting projects on all things DevOps. I’m passionate about simplifying complex concepts and sharing practical insights. Through my Hashnode blog, I document my learning journey, from building scalable applications to mastering cloud services, with the goal of empowering others to grow their tech skills. Let's Learn Together !!

In today's world of cloud computing, many companies use a mix of cloud providers like AWS (Amazon Web Services), Azure, or Google Cloud. Each of these cloud services has its own ways to set up and manage resources. For example, AWS uses CloudFormation (CFT), and Azure has the Azure Resource Manager (ARM). It can get complicated if you need to learn many different tools for each provider. To solve this problem, Terraform was created by a company called HashiCorp.

Terraform ecosystem diagram

Terraform simplifies things by letting you use just one tool for managing resources across different cloud providers. In this blog post, we will explain Terraform and the idea behind Infrastructure as Code (IaC) in simple terms, and we'll cover some basic examples.


What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) means writing code to manage and automate your infrastructure. Instead of manually clicking around to create servers, databases, and other cloud resources, you write a script. This script tells your cloud provider what resources you need, and the provider will create them for you automatically.

Think of IaC like writing instructions for setting up your cloud resources, just like you would write a recipe for cooking. The code acts as the recipe, and when you "run" it, the cloud follows the instructions to prepare everything for you.


How to Set Up Terraform for AWS

To get Terraform working with AWS, you need to configure AWS credentials and follow some simple setup steps. Here’s how you can do it:

1. Install the AWS CLI (Command Line Interface)

First, make sure the AWS CLI is installed on your computer. If you don’t have it yet, you can download and install it from the AWS CLI download page. It’s an important tool that helps you interact with AWS services from your command line.

2. Create an AWS IAM User

You’ll need an IAM (Identity and Access Management) user to interact with AWS programmatically. Follow these steps to create one:

  • Log in to your AWS Management Console using an account with administrative permissions.

  • Go to the IAM service.

  • Click on "Users" on the left-hand side and then select "Add user."

  • Choose a username and select "Programmatic access" as the access type, then click "Next: Permissions."

  • Attach the required policies to this user. For basic EC2 operations, you can start with the "AmazonEC2FullAccess" policy. If you need access to other AWS services, attach additional policies as needed.

  • Review the details and create the user.

  • Important: Save the Access Key ID and Secret Access Key shown after user creation. You’ll need these later.

3. Configure AWS CLI with Your Credentials

Now, you’ll set up your AWS credentials using the AWS CLI. Open your terminal and run this command:

aws configure

You’ll be asked to enter:

  • Your AWS Access Key ID (obtained when you created the IAM user).

  • Your AWS Secret Access Key.

  • The default region (e.g., us-east-1).

  • The default output format (you can choose json).

AWS CLI configuration

After you complete these steps, your AWS CLI will be configured and ready to use.


Now that you have the AWS CLI set up, you can start using Terraform to manage your AWS resources.

Terraform Lifecycle

Terraform follows a specific lifecycle when managing your infrastructure. This lifecycle consists of several key steps, which help ensure that infrastructure is created, updated, or destroyed in a controlled way. Here's an overview of the Terraform lifecycle:

1. Write

The lifecycle begins with writing Terraform configuration files. These files, usually with a .tf extension, define the desired infrastructure state, including the providers, resources, and modules you want to use. You write the code to specify what your infrastructure should look like and how it should behave.

Showing all the Terraform configuration files required

2. Initialize (terraform init)

Once you have written the configuration, you need to initialize the Terraform environment using the terraform init command. This step:

  • Downloads and installs the necessary provider plugins (e.g., AWS, Azure).

  • Sets up the backend configuration if you're using a remote backend for storing state files.

  • Prepares the working directory for other Terraform commands.

Initialize terraform directory

3. Plan (terraform plan)

The terraform plan command allows you to preview the changes that will be made to your infrastructure. Terraform compares the current state (stored in the state file) with the desired state (as defined in your configuration). It then generates a plan that details what actions need to be taken, such as:

  • Creating new resources.

  • Updating existing resources.

  • Deleting resources that are no longer needed.

The plan step ensures you know what changes will occur before you apply them.

Terraform plan

4. Apply (terraform apply)

With the plan approved, the terraform apply command executes the changes. This step:

  • Creates, updates, or destroys resources as necessary to match the desired state.

  • Applies the changes incrementally, meaning only the differences between the current state and the desired state are acted upon.

  • Updates the state file to reflect the new state of your infrastructure after the changes.

Terraform apply command executed successfully.

5. Destroy (terraform destroy) (Optional)

If you need to remove the infrastructure, you can use the terraform destroy command. This command:

  • Deletes all resources defined in your configuration.

  • Updates the state file to reflect that the resources no longer exist.

  • Helps clean up infrastructure when it's no longer needed, avoiding unnecessary costs.


Summary of the Terraform Lifecycle

  1. Write: Define the infrastructure as code using .tf files.

  2. Initialize: Set up the environment and download the necessary providers.

  3. Plan: Preview the changes that will be made to the infrastructure.

  4. Apply: Execute the changes and update the state file.

  5. Destroy (Optional): Clean up and delete the resources when they are no longer needed.

Following this lifecycle ensures that changes to infrastructure are well-managed, predictable, and repeatable. It forms the core of Infrastructure as Code (IaC) principles, making it easy to version, collaborate, and automate infrastructure management.


Key Terms You Should Know

Think of these terms as building blocks to get comfortable with using Terraform for automating cloud infrastructure.

Showing all the Terraform configuration files required

1. Provider

A provider is like a bridge between Terraform and the cloud platform you want to work with. It knows how to communicate with a specific cloud, such as AWS, Azure, Google Cloud, or other services. In your Terraform code, you set up a provider to tell Terraform which platform you’re going to be using and how to interact with it.

2. Resource

A resource is an actual piece of infrastructure you want to create or manage, like a virtual machine, a database, a storage bucket, or a network. You define resources in your Terraform code, specifying the type and settings for each. Terraform then uses this information to create the resource on your chosen cloud provider.

3. Module

Think of a module as a pre-packaged set of Terraform code that you can reuse. Modules let you group related resources together into one unit, which you can then use across different projects or parts of your infrastructure. It’s like creating a template for common setups, such as a web server configuration. You can either create your own modules or use ones shared by the community in the Terraform Registry.

4. Configuration File

Terraform uses configuration files (usually with a .tf extension) to describe the desired setup of your infrastructure. These files include details like providers, resources, variables, and other settings. The main configuration file is often named main.tf, but you can split your configurations into multiple files to keep things organized.

5. Variable

Variables are placeholders in your Terraform code that allow you to input different values without changing the actual code. Think of them as blanks you fill in before running the script. Using variables helps make your code more flexible and reusable, since you can update values like server size or location without changing the entire script.

6. Output

Outputs are the results or values Terraform gives you after creating or updating your infrastructure. For example, you might have an output that shows the IP address of a new server. These outputs can be displayed in the terminal or used to pass information between different parts of your infrastructure.

7. State File

The state file (usually named terraform.tfstate) is how Terraform keeps track of what your infrastructure currently looks like. It records all the details about the resources that have been created, so Terraform knows what’s already in place and what changes need to be made. This file is important for accurate updates and maintenance.

8. Plan

A Terraform plan is like a blueprint of changes Terraform will make to your infrastructure. When you run terraform plan, it shows you what resources will be added, modified, or deleted, based on the changes in your code. It helps you preview the effects of your changes before actually applying them.

9. Apply

The terraform apply command is used to implement the changes defined in the plan. It’s like pressing the "go" button after you’ve reviewed the plan. This command makes the changes, whether that means creating, updating, or deleting resources according to the Terraform configuration.

Terraform apply

10. Workspace

Workspaces help you manage different environments, such as development, testing, and production. Each workspace has its own configuration and state, which keeps things separate and organized. This way, changes in one environment don’t affect another.

11. Remote Backend

A remote backend is a location where Terraform stores its state file outside your local machine, like in Amazon S3, Azure Blob Storage, or HashiCorp Terraform Cloud. Using a remote backend makes it easier to collaborate with others and keeps your state file more secure.


Why Terraform?

When companies use different cloud providers, it’s challenging to manage resources separately for each. Each cloud has its own way of doing things, which means you would have to learn multiple tools. Terraform solves this problem by letting you write a script in a single language, called HCL (HashiCorp Configuration Language). With Terraform, you can:

  1. Write code once and use it for any cloud provider.

  2. Automate the creation of cloud resources.

  3. Easily migrate from one cloud provider to another by changing just a few lines of code.

  4. Track changes to your infrastructure like you would track changes to software code.

How Does Terraform Work?

Three Stages of the Terraform Lifecycle

Terraform interacts with the cloud providers using something called API (Application Programming Interface). Let’s break this down:

  • API: It's a way for software programs to talk to each other. For example, if you want to get information about a website like google.com, you can use an API to request that information programmatically. You can think of it like sending a letter to Google asking for some details, and Google sends the response back.

  • Terraform Script: You write a Terraform script to describe the resources you want. This could be a server, a database, or a storage bucket. The script uses the API of the cloud provider to tell it what resources to create.

terraform config files

  • API Request: When you run the Terraform script, it sends an API request to the cloud provider. The provider then reads this request and creates the resources based on the instructions in the script.

How an API works

What is the Difference Between Using a UI and API?

  • UI (User Interface): Manually creating resources using a web dashboard or control panel. You click buttons and fill out forms to create what you need. This can be time-consuming if you have to create many resources.

  • API: Automating the creation of resources programmatically using code. Instead of manually clicking around, you run a script that uses the cloud provider's API to set up everything for you.

Terraform provider api call

The same applies to IaC (Infrastructure as Code) vs API as Code. When you use IaC, you're writing code to create and manage the infrastructure. With API as Code, you are focusing more on direct API requests to the cloud.


Setting Up Terraform for Beginners

To start using Terraform, follow these steps:

  1. Install Terraform:

  2. Write Your First Terraform File:

    • Create a new file called main.tf. This file will contain the code to create a simple resource, like a virtual machine.
  3. Example Terraform Script: Here's a simple example of a Terraform script to create a virtual machine in AWS:

     provider "aws" {
       region = "us-east-1"
     }
    
     resource "aws_instance" "example" {
       ami           = "ami-0c55b159cbfafe1f0"
       instance_type = "t2.micro"
    
       tags = {
         Name = "ExampleInstance"
       }
     }
    

    In this script:

    • We are telling Terraform to use AWS as the cloud provider.

    • We specify the region (us-east-1).

    • We define an AWS instance (virtual machine) with the given settings.

    • We provide a name tag for easy identification.

  4. Run Terraform Commands: Open your terminal and run these commands:

    • terraform init: This command initializes your working directory. It downloads the required plugins for your cloud provider.

    • terraform plan: This command shows you what Terraform is going to create or change.

    • terraform apply: This command applies the changes and creates the resources described in your main.tf file.

  5. Updating the Configuration: To update or change the resources, modify the script and run terraform apply again. If you want to switch from one cloud provider to another (e.g., AWS to Azure), you can update the provider details in the script.

Advantages of Using Terraform

  • Consistency: Ensures that your infrastructure is set up the same way every time.

  • Version Control: You can track changes to your infrastructure code.

  • Scalability: Easily create multiple resources by changing just a few lines in your script.

  • Cloud-Agnostic: Works with different cloud providers like AWS, Azure, and Google Cloud.


Conclusion

Terraform is a powerful tool for managing cloud infrastructure using code. It helps you avoid the hassle of learning multiple cloud-specific tools by providing a single language for defining resources. With Terraform, you can automate the setup of your infrastructure, making it easier to manage and scale.

Start small with Terraform, write simple scripts, and practice running them to understand how it works. The more you practice, the more comfortable you will become with IaC and automating cloud environments.

For more details, refer to the official Terraform documentation.

Happy Terraform’ing :)

Note: Images used are sourced from the internet.