IT 3110 : DevOps Automation

Terraform 3

How terraform applies a configuration

  • Create (if exists in config but not in infrastructure)
  • Destroy (if resources no longer exist in the configuration)
  • Update in-place (if resource has change in config)
  • Destroy and re-create (if they cannot be updated in place, i.e. changing ec2 instance type

Configuration Meta-argument

  • depends_on
    • Explicitly specifying a dependency is only necessary when a resource or module relies on some other resource's behavior but doesn't access any of that resource's data in its arguments.
    • must be a list of references to other resources or child modules in the same calling module

Configuration Meta-argument

  • count
    • use count if your instances are almost identical

    • Cannot use count and for_each for a given resource

      resource "aws_instance" "server" {
        count = 4 # create four similar EC2 instances
      
        ami           = "ami-a1b2c3d4"
        instance_type = "t2.micro"
      
        tags = {
          Name = "Server ${count.index}"
        }
      }
      

Configuration Meta-argument

  • for_each
    • Use if some args need distinct values that cannot be derived from an integer.

For_each example

    resource "azurerm_resource_group" "rg" {
      for_each = {
        a_group = "eastus"
        another_group = "westus2"
      }
      name     = each.key
      location = each.value
    }

Input variables

  • allow aspects of the module to be customized without altering the module's own source code, and allowing modules to be shared between different configurations.
  • kind of like function arguments
  • Can also validate vars (i.e. see if they are in a certain range)
  • refer to variable with var.name

Input variables

    variable "image_id" {
      type        = string
      description = "The id of the machine image (AMI) to use for the server."
    }

Input variables

    variable "mytype" {
      type = string
      description = "The type of instance to create"
    }
    
    resource "aws_instance" "example" {
      ami           = "ami-0817d428a6fb68645"
      instance_type = var.mytype
    }

Input variables

The previous example will prompt for the variable value at runtime. You can also:

  • pass in variable at command line like terraform apply -var="mytype=t2.micro"
  • put them in a .tfvars file. and terraform apply -var-file="foo.tfvars"
    • in the file you just assign the variables like: mytype="t2.micro"
  • also can pass in as ENV var like export TF_VAR_mytype=t2.micro

Output values

  • Only rendered when tf applies your plan.

  • Are like a function return values

      output "instance_ip_addr" {
        value = aws_instance.server.private_ip
      }
    

Terraform Cloud

https://app.terraform.io/app/getting-started/example

  • Copy correct variables over to the cloud.