Understand IT change management vs. configuration management Infrastructure as code benefits and DevOps use cases
Tip

Infrastructure as code examples for DevOps, cloud deployments

Administrators can use infrastructure as code to consistently manage a distributed set of resources. Follow these four examples to get started, and explore common IaC tool choices.

Virtualization and cloud services create a complex mix of IT infrastructure components. To manage these components effectively, IT staff must look beyond traditional administrative approaches driven by CLIs and shell scripts.

Borrow ideas from software development to oversee cloud-scale environments. Treat infrastructure resources and configuration parameters as programmable objects, and control them via code -- a concept known as infrastructure as code (IaC).

IaC uses software with a domain-specific language, interpreter, execution environment and external interfaces to build on traditional script-based management techniques. This enables developers to create sophisticated routines adaptable to the most complicated enterprise environments and applications.

IaC tools and benefits

There are many IaC products, including third-party tools such as Terraform, Ansible and Pulumi, as well as public cloud services such as AWS CloudFormation, Azure Resource Manager (ARM) and Google Cloud Deployment Manager. The right IaC product for an organization depends largely on its current, or planned, cloud architecture: Third-party options are best for multi-cloud deployments, while cloud provider-specific services are best for organizations that exclusively use that cloud provider's platform.

Regardless of the tool, there are many ways IaC can improve the speed, efficiency, consistency and security of IT operations. The following infrastructure as code examples illustrate how IT admins use IaC across various environments -- from multi-cloud and hybrid cloud deployments to DevOps pipelines. Each example includes sample templates and code from IaC vendor documentation.

1. Deploy cloud resources

The most popular use for IaC is to automate resource and application configuration and deployment on cloud environments, whether public clouds such as AWS and Azure or private systems running vSphere or Windows Server.

Admins can use IaC templates to repeatably create and configure cloud instances, and then install, configure and start an application. For example, CloudFormation can configure a static website using Amazon S3 and Route 53, where content is stored in S3 buckets. Here's the JSON code for a site's default homepage:

{
   "Parameters": {
        "RootDomainName": {
            "Description": "Domain name for your website (example.com)",
            "Type": "String"
        }
    },
    "Resources": {
        "RootBucket": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "BucketName" : {"Ref":"RootDomainName"},                
                "AccessControl": "PublicRead",
                "WebsiteConfiguration": {
                    "IndexDocument":"index.html",
                    "ErrorDocument":"404.html"
                }
            }
        },

Here's another infrastructure as code example that uses Google Cloud Deployment Manager with Jinja, a Python templating language, to deploy a Google Compute Engine instance:

- name: vm-template
  type: compute.v1.instance
  properties:
    zone: us-central1-a
    machineType: zones/us-central1-a/machineTypes/n1-standard-1
    disks:
    - deviceName: boot
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: projects/debian-cloud/global/images/family/debian-9
    networkInterfaces:
    - network: global/networks/default

Finally, here's a Terraform snippet to deploy an Amazon EC2 instance:

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}

2. Create cloud-agnostic resource templates

As demonstrated in the infrastructure as code example above, a cloud-agnostic IaC tool can create identically configured templates on multiple cloud platforms. For instance, below is Terraform code to create an ARM template that defines an Azure storage account and an Azure VM. Note that the Terraform provider keyword specifies "azurerm" instead of "aws," as in the previous Terraform example:

provider "azurerm" {
  version = "=1.28.0"
}

resource "azurerm_resource_group" "test" {
  name     = "production"
  location = "West US"
}

resource "azurerm_storage_account" "testsa" {
  name                     = "${var.storageAccountName}"
  resource_group_name      = "${azurerm_resource_group.testrg.name}"
  location                 = "${var.region}"
  account_tier             = "${var.tier}"
  account_replication_type = "${var.replicationType}"

}
# Create virtual machine
resource "azurerm_linux_virtual_machine" "myterraformvm" {
    name                  = "myVM"
    location              = "eastus"
    resource_group_name   = azurerm_resource_group.myterraformgroup.name
    network_interface_ids = [azurerm_network_interface.myterraformnic.id]
    size                  = "Standard_DS1_v2"

    os_disk {
        name              = "myOsDisk"
        caching           = "ReadWrite"
        storage_account_type = "Premium_LRS"
    }

3. Update applications and synchronize versions

Another popular infrastructure as code use case is to keep application versions or configuration files in sync across systems in a multi-cloud environment. The below example features Ansible, and shows the YAML code to ensure Apache servers are updated. Since Ansible has modules for most cloud platforms, this code snippet could be part of a larger Ansible playbook that creates a VM, installs a standard Linux image and configures Apache on multiple cloud services:

—-
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service:
      name: httpd
      state: started
  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted

4. Deploy virtual network and security policies

Setting up virtual networks -- or virtual private clouds -- is tedious and error-prone. IaC reduces this complexity, particularly in hybrid or multi-cloud environments.

Code is especially useful to replicate a network configuration for different projects, such as cloning a production network for test and development. Cloud-agnostic tools like Terraform let IT admins replicate the same configurations across various cloud providers.

The following example from HashiCorp illustrates this concept. Terraform code defines Amazon VPC parameters and instance types for a web application environment:

variable project {
  description = "Map of project names to configuration."
  type        = map
  default     = {
    client-webapp = {
      public_subnets_per_vpc  = 2,
      private_subnets_per_vpc = 2,
      instances_per_subnet    = 2,
      instance_type           = "t2.micro",
      environment             = "dev"
    },
    internal-webapp = {
      public_subnets_per_vpc  = 1,
      private_subnets_per_vpc = 1,
      instances_per_subnet    = 2,
      instance_type           = "t2.nano",
      environment             = "test"
    }
  }
}

To replicate these parameters for each project, use Terraform's for_each loop operator as follows. Likewise, use similar variable blocks to set the network security group and add features, such as a load balancer:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "2.44.0"
+
+ for_each = var.project

While the snippet above targets AWS, admins can add Google Cloud as a Terraform provider (see below), and replace the instance-type statements with a variable that is defined per provider. This means they could deploy the same network environments, using something like AWS_webapp_production and GCP_webapp_test statements in a Terraform command.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

provider "aws" {
  profile = "default"
  shared_credentials_file = "/Users/tf_user/.aws/creds"
  region  = "us-west-2"
}
provider "google" {
  credentials = file("account.json")
  project     = "my-project-id"
  region      = "us-central1"
}

IaC best practices

While the above infrastructure as code examples are fairly simple, IT teams can adapt IaC software for much more complicated scenarios, including to deploy and manage a container cluster.

Regardless of the specific infrastructure as code use case, organizations should:

  • View IaC products and code as a long-term commitment, and as part of an overall cloud strategy.
  • Include all stakeholders, such as cloud and network operations, security and DevOps teams, in IaC-related decisions to ensure staff agree to use the same tool.
  • Use their cloud provider's native IaC service, such as AWS CloudFormation, Google Cloud Deployment Manager or Azure Resource Manager, if they use only one cloud platform.
  • Opt for a cloud-neutral tool, such as Terraform or Ansible, if they have or plan to have a hybrid or multi-cloud environment.

Lastly, to successfully implement IaC, follow time-tested software development practices. For example, use GitHub as a primary repository for IaC code and modules, and track code changes with version control features. Embed documentation within the authoritative code text, since developers frequently neglect to update separate documentation files. Set up a non-disruptive IaC test and dev environment to thoroughly debug code without risks to production infrastructure.

Dig Deeper on Systems automation and orchestration

Search Software Quality
Search App Architecture
Cloud Computing
Search AWS
TheServerSide.com
Search Data Center
Close