January 14, 2024

What is Infrastructure as Code (IaC)? Best Practices, Tools, Examples & Why Every Organization Should Be Using It

Infrastructure Automation
DevOps

Infrastructure as code (IaC) is the act of writing infrastructure configurations as code so they can be understood, repeated, and enforced with less manual effort. IaC is also a powerful way to convert tribal knowledge into technical knowledge. It’s a far-reaching and essential part of managing infrastructure at scale, with benefits that have expanded to platform engineering, security and compliance, network administration, and so much more. 

In this blog, we’ll explore the definition of infrastructure as code, as well as up-to-date use cases and benefits for organizations today. 

Back to top

What is Infrastructure as Code (IaC)?

Infrastructure as code (IaC) is the practice of describing infrastructure in code — just like software. Infrastructure as code enables organizations to automate tasks and processes that would otherwise be done manually, like managing infrastructure and provisioning resources.

Infrastructure as code (IaC) means turning configurations for various infrastructure components — like operating system configuration, application configurations, server configurations, VM configurations, IT security configurations, and storage configurations — into repeatable code.

With IaC, you can...

  • Version control your infrastructure
  • Automate common tasks (like installs, patches, and rollbacks)
  • Deploy infrastructure faster and more reliably

Treating infrastructure as if it were code lets you adopt powerful practices that have been used by software developers for years, and with great success — practices that include version control, peer review, automated testing, release tagging, release promotion, and continuous delivery.

Back to top

How Does Infrastructure as Code Work?

Infrastructure as code collects information like configurations, resource dependencies, resource properties, instructions, access, and contains it in a structured fashion where version control can be used to enable review, testing, and deployment automation.

The older methods of infrastructure management — manual processes and documentation, brittle single-purpose scripts, and graphical user interface-based tools — each had their uses in the past.

Today, though, with the perpetual need to scale infrastructure, adoption of ephemeral infrastructure, and greater application system complexity, new ways of keeping things under control are needed. 

👀 Want to see how IaC can help you ensure compliance (and security) at scale? Check out our white paper on How Automation Helps You Harden Your Systems & Achieve Compliance >>

Consider resource provisioning and allocation. Where it used to take weeks or months to allocate a server, it can be done in a minute or two using innovative practices like virtualization and self-service cloud infrastructure. But the wide adoption of new tools and techniques has shifted the bottleneck from just allocating servers to configuring them. 

To address these challenges at modern scale, you need new methods of collaborating, delivering, and gaining situational awareness. 

Back to top

A Simple Example of Infrastructure as Code

Since this might all seem a bit abstract, let's put a fine point on infrastructure as code with a quick example.

Imagine you need to set up a new web server to handle a rise in traffic. Here's what that simple process might look like if you're doing it without infrastructure as code and how that stacks up to the same process WITH IaC:

Step

Without IaC

With IaC

Identify the requirements of the new server

Consult with the team to confirm that the current load exceeds the server's capacity and that a new server is required.

Consult with the team to confirm that the current load exceeds the server's capacity and that a new server is required.

Propose a change which satisfies the requirements

Create a plan to manually add a new web server with specs and configurations similar to the existing fleet.

Define the new web server in the infrastructure code.

Manually set up the new server

  • Order new server hardware (or provision a new VM).
  • Install the OS.
  • Configure software on the web server.
  • Configure security policies and network settings.

Push the new configuration to the version control system (e.g., Perforce).

Test the server

  • Manually set up a production-like staging environment.
  • Deploy the web server to the staging environment.
  • Run load tests and functional tests on the server.
  • Deploy the configuration code to a staging environment.
  • Run load tests and functional tests on the server.

Manually set up the web server in a production environment

  • Install the OS.
  • Configure software on the web server.
  • Configure security policies and network settings.
  • Update the load balancer to accommodate the new server.
  • Monitor the newly deployed web server to make sure it integrates and doesn't interrupt dependencies in existing infrastructure.

Use an IaC tool to apply the same configurations from the staging environment to production.

Manually document the new state of the infrastructure

  • Keep a spreadsheet updated with configuration information and health status of all servers, including the new web server.
  • Check that spreadsheet regularly and update metrics as needed.

Query the infrastructure for automatic state files with up-to-date information on infrastructure components.

Manually keep track of changes to infrastructure configurations

  • Use a ticketing system to document change proposals, approvals, and executions.
  • Manually update logs with each change.

Use version control to maintain a history of changes, including who proposed, approved, and applied them.

Back to top

Who Uses Infrastructure as Code?

Infrastructure as code isn't limited to a single team — its many benefits have become cross-functional to roles that require a shared language to work together. As concepts like DevOps have expanded into other areas of the business (to their benefit!), organizations have found more ways to put shared code to work in places like compliance and security. 

So, who uses infrastructure as code today? 

Here are just a few examples of the kinds of roles that could put IaC to work, and how they might use it: 

Role

How They Use Infrastructure as Code

System Administrators / Engineers

Automate server and application provisioning, configuration, and maintenance  

Cloud Administrators / Engineers

Manage and deploy cloud resources 

Network Administrators / Engineers

Define and provision network infrastructure in a repeatable way  

DevOps Engineers

Integrate infrastructure provisioning and configuration into CI/CD pipelines  

Application Developers

Spin up local development environments  

Site Reliability Engineers

Ensure infrastructure reliability and consistency 

Security Engineers

Enforce security best practices and compliance requirements through code-base infrastructure management 

Platform Engineers

Build and maintain scalable self-service platforms for developers and other teams 

To understand why more teams are using infrastructure as code, it’s important to understand the benefits of IaC, and how it’s used to solve specific problems. 

infrastructure as code iac
Back to top

The Benefits of Infrastructure as Code

Infrastructure as code (IaC) provides consistency, standardization, automation, change management, security, and scalability to IT infrastructure. Normally, infrastructure management can be time-consuming and expensive. IaC increases the frequency and reliability of infrastructure deployments.

There's one huge reason infrastructure as code is important: It exchanges tribal knowledge for technical expertise.

Let me explain what that means.

A single group can build, share, and solve problems within an organization — and that’s great! But what happens when that group leaves, changes roles, or disbands? All of that critical shared knowledge is gone — and anyone trying to troubleshoot will run into duplicate work and wasted effort. 

Infrastructure as code provides immutable truth with work that is documented, shared, and clear. It will work for the teams that developed the code and long into the future once that team is gone. Replacing tribal knowledge means that infrastructure as code becomes another technical component of the environment — which offers far reaching benefits, as we will explore. 

Self-Documentation

Infrastructure as code eliminates the need for separate documentation and provides a single source of truth. Infrastructure as code describes the infrastructure’s configuration, components, and relationships – and when changes have been made to any of those, these changes are reflected in the code. 

This method of self-documentation helps teams stay on top of version control history. It also makes it easier to review previous configurations and better understand the reasoning behind any changes. With meaningful code structure and naming, self-documentation can help break down complex infrastructure into more manageable pieces, which improve readability and understanding. 

CI/CD 

Infrastructure as code benefits the continuous integration and continuous delivery (CI/CD) pipeline by enabling consistent integrations and faster deployments. The ability to automate deployments can help you roll out code across infrastructure of any size, with less manual intervention and fewer errors.

Version Control 

Code is portable, reusable, and can be managed with version control. Changes to infrastructure as code are committed to version control, where they can be tested, collaborated on, and approved (merged) by peers. 

Once the change to IaC has been accepted, it can be automatically deployed to thousands of systems just as easily as to a single system. The version control system also provides an audit history. Using a continuous integration/continuous delivery system (see above), these steps can be codified into a continuous delivery pipeline. The result of using infrastructure as code with version control is a workflow that promotes collaboration, dramatically shortens feedback loops, reduces deployment risk, and keeps a continuous history of who did what. 

Auditability and Compliance 

Beyond just scalability, there are reasons that organizations would see the benefit of infrastructure as code in the long run — auditability is a powerful reason. A clear record of infrastructure changes means that time is saved when troubleshooting is required, which is extremely helpful for compliance and auditing purposes. 

Infrastructure as code gives you confidence in your compliance, with the ability to prove compliance to auditors. 

When compliance becomes code, it can be easily enforced and scanned for any issues. If there is a conflict between your system configurations and the desired end state, these issues can be remediated automatically by default. 

When code can be reproduced, testing, debugging, and disaster recovery are also part of the benefits of infrastructure as code. For any organization, no matter how complex, there are going to be risks associated with managing infrastructure across different users, devices, and for different needs. You might not be able to foresee these issues, but you can implement a repeatable way to handle issues that appear. IaC acts as both the fire alarm and a fire extinguisher for situations like these. 

Scale and Agility 

Previous methods of IT management won't work if you're trying to address modern scale and agility requirements. Graphical tools can make it difficult to share pieces of configuration with other teams, do peer review on proposed changes, view historical changes, and roll back to a previous set of configurations. And scripts are equally unsuitable for modern scale and agility. They're brittle, unmaintainable, are sprawled throughout teams and individuals, and are rarely portable between environments. 

Defining your infrastructure as code solves these problems because code is portable, reusable, shareable, testable, and introspectable. And in case we haven't said it clearly enough, manual changes are just terrible — period. 

Day 0, Day 1, and Day 2 Operations 

The entire software development lifecycle benefits from the consistency and repeatability of infrastructure as code. Here’s how: 

  • On Day 0, infrastructure as code helps ensure consistency across the entire rollout, from version control to node classification, before the rollout even begins. 
  • On Day 1, all stages of the deployment can be automated through infrastructure as code to ensure that you’re getting consistent, repeatable results. 
  • On Day 2, your goal should be to have a single codebase that can continue to manage your server environments. In that way, infrastructure as code can support your consistent rollout schedule for updates, changes, and more. 
Back to top

Different Types of Infrastructure as Code 

There are two different approaches for infrastructure as code: declarative and imperative.

Declarative IaC 

Declarative infrastructure as code uses a DSL such as Puppet to define the desired state of your system. It keeps track of the state of your system objects, even the resources that you’ll need, and makes configurations to achieve your desired state. 

Imperative IaC 

Imperative infrastructure as code requires specific (exact) steps in a scripting language that are needed to configure your infrastructure and make changes. This can provide more control over the process but can also add complexity at scale.

Want to know more about the different kinds of IaC? Check out free on-demand courses from Puppet to dive deeper.

TAKE PE101   TAKE PE201

Infrastructure as Code (IaC) vs. Infrastructure as a Service (IaaS)

Infrastructure as code (IaC) and infrastructure as a service (IaaS) are two different things. The main difference is that IaC turns infrastructure configurations into lines of code so they can be managed automatically. IaaS offers on-demand virtual computing resources via the internet (like servers, networking, and storage). 

You can think of IaC as the set of instructions for provisioning and configuring IT resources and services – just turned into code, so you can automate, repeat, and manage them easily. Examples of IaC include Puppet, Terraform, and Chef

On the other hand, IaaS provides point-in-time configurations. It gives you resources and services you need to run your application code when instantiated, with all the necessary configurations built in. Examples of IaaS include Amazon AWS, Microsoft Azure, and Google Cloud Platform.

Back to top

Infrastructure as Code Tools

Infrastructure as code tools include a broad range of software, including tools for configuration management, orchestration, provisioning, version control, secrets management, monitoring tools, and more.

Infrastructure as code tools can be used to automate the creation, deployment, and management of infrastructure resources. Here's a list of IaC tools and the tasks they can perform:

IaC Tool Type

Use Cases

Examples

Configuration Management Tools

  • Automates provisioning and/or configuration of servers.

  • Puppet: Enforces desired state on servers with agent-based configuration management.

  • Chef: Uses Ruby DSL for complex configurations.

  • Ansible: Uses YAML playbooks for agentless automation of infrastructure configurations.

Orchestration

  • Coordinates multiple services or resources into complex workflows.

  • Manages dependencies between resources.

  • Bolt: Lightweight orchestration tool for automating ad hoc tasks and complex workflows across systems.

  • Kubernetes: Manages containerized applications.

  • Terraform: Manages cloud and on-prem resources.

  • AWS CloudFormation: Orchestrates AWS resources.

Provisioning

  • Automates the creation of infrastructure resources.

  • Efficiently manages the lifecycle of resources.

  • Terraform: Multi-cloud infrastructure as code.

  • Pulumi: Code-based cloud infrastructure management.

  • CloudFormation: AWS-native provisioning.

Immutable Infrastructure

  • Promotes the creation of immutable server images.

  • Enhances reliability and security by reducing configuration drift.

  • Docker: Containerization for consistent environments.

  • Packer: Builds machine images for multiple platforms.

  • Kubernetes: Manages immutable containerized apps.

Version Control Systems (VCS)

  • Manages changes to infrastructure configurations over time.

  • Facilitates collaboration and rollbacks.

  • Perforce Helix Core: Enterprise-grade VCS known for high performance with large assets, and strong security and compliance features.

  • GitHub: Popular VCS with extensive integration options.

Secrets Management

  • Securely stores and manages sensitive data like passwords, tokens, and API keys.

  • Ensures secure access to sensitive data across environments.

  • HashiCorp Vault: Comprehensive secret management.

  • AWS Secrets Manager: Manages secrets in AWS.

Container Management

  • Manages containers and their orchestration at scale.

  • Enables microservices architecture.

  • Docker: Leading container platform.

  • Kubernetes: Orchestrates containers in clusters.

  • OpenShift: Kubernetes-based container management platform.

Monitoring and Compliance

  • Ensures infrastructure adheres to policies and monitors its state.

  • Automates auditing and reporting.

  • Puppet Enterprise: Contains Security Compliance Management, which assesses configurations for compliance and generates automated reports.

  • Splunk: Enterprise platform for searching, monitoring, and analyzing machine-generated data.

  • Datadog: Cloud-scale monitoring.

  • Prometheus: Open-source systems monitoring.

Back to top

Infrastructure as Code Use Cases

Lists are great, but what does it actually look like in practice? Tasks that can be automated by an IaC tool include: 

  • Deploying applications 
  • Managing storage 
  • Scaling infrastructure 
  • Disaster recovery 
  • Configuring networks 
  • Creating and provisioning servers 

IaC Example: Infrastructure as Code in Action

To give you an even more concrete idea of how IaC works, here's an imaginary scenario in which an organization uses infrastructure as code to deploy a web application.

  1. Infrastructure as Code Development

    First, the organization needs to define the desired configurations of the relevant components. That includes the web servers, app servers, and databases.

    In this case, they write Puppet scripts (which we call modules) to ensure all servers will be configured with the right software, patches, and dependencies before anything gets provisioned. Then they commit those code changes to a repository (Perforce Helix Core, Git, etc.).

  2. CI/CD

    The team's continuous integration/continuous delivery (CI/CD) pipeline uses Terraform to provision infrastructure, with Puppet applying consistent configurations. They use Puppet Bolt used to execute one-off deployment tasks or apply Puppet manifests.

  3. Deployment

    Next, the organization builds Docker containers and pushes them to a container registry. Kubernetes deploys and manages these containers across the previously provisioned infrastructure.

  4. Configuration Management

    Puppet uses the infrastructure code developed in step 1 and applies it across all those new resources. This part of IaC is sometimes called configuration as code. That includes standing up web servers, application servers, and databases with the right operating systems, software, security patches, user privileges, services, and more. 

    Using Puppet agent-based automation for configuration management lets the organization secure infrastructure better than with agentless automation tools like Ansible. Because they chose Puppet, those configurations will be enforced every 30 minutes until they make a change to the IaC code — then Puppet will enforce the new desired state of their infrastructure.

  5. Monitoring

    Puppet can report on system state to tools like Splunk, Datadog, and Prometheus, providing insights into the performance and security of applications and infrastructure maintained by Puppet.

    Puppet also gives the team a high degree of enterprise observability into their managed components, which agentless automation can't ensure at scale.

Back to top

Infrastructure as Code: Best Practices for Using IaC

Infrastructure as code best practices include using version control to track and manage changes; breaking infrastructure code down into modules for reusability; separating infrastructure code from application code; instituting role-based access control; automating testing (CI/CD); and regularly reviewing infrastructure code for performance and security.

With a range of infrastructure as code tools, each with their own specialty and capabilities, it's important to consider what your organization needs. How often are you rolling out applications or updates? How many servers do you have, and how many end users are you reaching?

If you're not currently using infrastructure as code, you'll want to ask yourself: 

  • How important is security to your org? Infrastructure as code can provide a clear record of all changes made within your infrastructure — ultimately helping to identify and mitigate security risks. 
  • How complicated is your current infrastructure? Infrastructure as code can help wrangle all different components by tracking and managing everything in one place. 
  • How often does your infrastructure change? Automating provisioning and configuration is a great way to save time and effort, especially if you change infrastructure frequently. 
  • Who will be managing your infrastructure? No matter how your teams are structured, the common language around infrastructure as code can encourage collaboration. 

Why Your IaC Language Matters

To align everyone in IT, it’s important to establish a common language for everyone to use when contributing to and managing infrastructure.

Depending on the IaC tools you choose, you can write infrastructure as code in a number of languages, including Python, Go, JavaScript, JSON, and YAML. Some IaC solutions use their own unique coding language, like Terraform’s Hashicorp Configuration Language (HCL) and Puppet’s Declarative State Language (DSL), which is based in Ruby.

With a common language, everyone can propose infrastructure improvements, collaborate on infrastructure implementations, and read the code itself to understand how any part of the infrastructure is being managed. (You may have seen the term "executable documentation" for infrastructure code. That's because the code itself enforces the documented infrastructure policies.)

When choosing your infrastructure code language, there are important factors you should consider. Since you want everyone aligning with a common language, the language needs to have a low learning curve, be declarative, be idempotent, and holistically manage the infrastructure as a single source of truth. Let’s break that down. 

1. Easy Adoption 

It’s important to consider the strengths and skill levels of everyone who contributes to the infrastructure. Are they all software developers with degrees in computer science? Probably not. At the same time, do not underestimate their capabilities, nor their experience in writing some form of code. Ask your DBA to show you their PL/SQL queries — that should convince you your DBA really does know how to write code. Or ask to see your Windows administrator’s batch files or login scripts. Almost anyone in IT can pick up an infrastructure language, provided it is well-designed, purpose-built, and comes with a prescription for how it should be used. 

2. Idempotence 

Idempotence is defined as the property of an action always having the same result. An example in mathematics is taking the absolute value of a number and continuing to apply the absolute value to the result. No matter how many times you perform that operation, the result is always the same. 

An example of idempotence in IT is the rm -f command from Unix. No matter the beginning state, the result is always the removal of the target. 

Idempotence is a critical component to successfully using infrastructure as code. The more your code is idempotent, the more it can handle any condition, and always do the correct thing. 

3. Holistic Modeling 

As more and more of your IT team contributes to the infrastructure code, you need to know your IaC tools can scale to potentially hundreds of contributors across a plethora of teams. Where are all the different places the infrastructure code can live? How many different pieces of code manage the same system? What happens when two contributors write code that manages the same configuration differently? 

With holistic modeling, all the infrastructure code is combined to a single central source of truth that identifies how each piece of infrastructure code relates to every other piece. Because the relationships between all the pieces of code are understood, common mistakes are caught (such as two contributors trying to manage the same configuration differently), and problems are averted. 

Back to top

Get Started with Puppet's Infrastructure as Code 

Puppet was born from the combination of software development and operations, with infrastructure as code is at the center of it all. With infrastructure as code, Puppet allows you to scale your infrastructure automation with your organization's IT needs, meaning you can do more provisioning, deliver apps faster, stay in compliance, and build more resilient infrastructure with code – and get the same result every time.

Infrastructure as code can ultimately make your organization more responsive, collaborative, faster, and more innovative. Puppet can help you reach your goals using infrastructure as code for your specific organizational needs. Even better, you can see how Puppet works within your infrastructure with a free trial: 

START MY PUPPET TRIAL 

This blog was originally published on February 9, 2017, and has since been updated for accuracy and relevance.

Back to top