KEMBAR78
Infrastructure-as-Code (IaC) using Terraform | PPTX
INFRASTRUCTUR
E-AS-CODE (IAC)
USING TERRAFORM (BEGINNER
EDITION)
Adin Ermie
Cloud Solution Architect
(Azure Apps & Infra)
Microsoft
AGENDA
 Benefits of Infrastructure-as-Code (IaC)
 What is Terraform and why do people love it?
 Terraform basics
 Commands, workflow, resource creation, file structure
 Azure Resource Manager (ARM) vs Terraform
 Best practices
 Resources for learning and certification
BENEFITS OF INFRASTRUCTURE-AS-CODE (IAC)
 Reproducible environments
 Automation – CI/CD
 Trackable – GitHub
 Language - HCL
 Workflow
 Providers
 Apply same configuration across
clouds
WHAT IS TERRAFORM?
 A templating language
created by HashiCorp called
HashiCorp Configuration
Language (HCL)
 Written in Go Lang
 A tool that can be used to
orchestrate the provisioning
of:
 Public clouds (Azure, AWS,
GCP, Oracle, Alibaba)
 On-premises (VMware)
 Other (Cisco, GitHub, GitLab,
New Relic, Okta, Rabbit MQ)
 Uses State files (more on
this later)
 Is NOT used for
configuration
 PowerShell Desired State
Configuration (DSC), Chef,
Puppet, Ansible
WHY PEOPLE LOVE TERRAFORM?
 Clean and easy code to write and maintain
 Fully declarative configuration
 Version control on infrastructure
 Implicit dependencies management – explicit can be forced
 Ecosystem of providers and skilled personnel
NEW!
SO, HOW DOES
THIS WORK?
TERRAFORM COMMANDS/WORKFLOW
 Terraform init
 Initializes the current working directory
 Terraform plan
 Execution plan to validate against existing environment
 Terraform apply
 Deploys and updates resources
 Terraform destroy
 Removes all resources defined in a configuration
Init
Plan
Apply
Destroy
BASIC RESOURCE CREATION
 Resource Type
 Required provider
 Name
 Internal (to Terraform) name
 Configuration
 Deployment details
resource "azurerm_resource_group" "SharedServicesRG" {
name = "SharedServicesRG"
location = "Canada Central"
}
NameResource Type
Resource Configuration
TERRAFORM FILE STRUCTURE
terraform {
required_version = ">=0.12.0"
backend "azurerm" {
resource_group_name = "tstate"
storage_account_name = "tstate123"
container_name = "tstate"
key = "terraform.tfstate"
}
}
provider "azurerm" {
version = ">=2.0.0"
subscription_id = "<<REMOVED>>"
client_id = "<<REMOVED>>"
client_secret = "<<REMOVED>>"
tenant_id = "<<REMOVED>>"
}
resource "azurerm_resource_group" "example" {
name = var.resource_group_name
location = var.location
}
resource "azurerm_storage_account" "example" {
name = "storageaccountname"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "GRS"
tags = {
environment = "staging"
}
}
BACKENDS
 Determines how state is loaded and how an
operation such as apply is executed
 By default, Terraform uses the "local" backend
 Benefits of backends:
 Working in a team
 Store state remotely and protect state with locks to
prevent corruption
 Keeping sensitive information off disk
 Retrieved on demand and only stored in memory
 Remote operations
 Remote execution
terraform {
required_version = ">=0.12.0"
backend "azurerm" {
resource_group_name = "tstate"
storage_account_name = "tstate123"
container_name = "tstate"
key = "terraform.tfstate"
}
}
STATE
 State keeps track of the all managed resources and their associated properties with current values.
 Essential for managing changes to infrastructure over time
 Preserve the state file for the entire life cycle of the resources
 You can create a separate state file per resource group, application, shared service (ie. core networking)
 Terraform Workspaces should also be used to separate application and environment boundaries
 Recommended to use a remote backend to save state in centralized, secure storage
 Example: Storage account, Terraform Cloud, Terraform Enterprise, Artifactory, Consul
 You must initialize the Terraform State
 This is what terraform init does
IMPORTANT!
Secrets (like
usernames/passwords, access
keys/tokens, etc.) can be
written to your state file!
PROVIDERS
 The provider block is used to configure the
named provider
 Is responsible for creating and managing
resources, and for all other interactions including
authentication
 The version argument is optional, but
recommended
provider "azurerm" {
version = ">=2.0.0"
subscription_id = "<<REMOVED>>"
client_id = "<<REMOVED>>"
client_secret = "<<REMOVED>>"
tenant_id = "<<REMOVED>>"
}
VARIABLES
 Parameterize the configurations
 If no value is assigned to a variable and the
variable has a default key in its declaration,
that value will be used for the variable
 Can be provided…
 Within the Terraform template
 Within its own Terraform template file
 Within a .TFVARS files
 Through command-line
 Through Environment variables
NOTE!
Variables have precedence
1. Command-line
2. From a file
3. Environment variables
4. UI Input
resource "azurerm_resource_group" "example" {
name = var.resource_group_name
location = var.location
}
variable "location" {
type = string
default = "westus"
description = "Specify a location see: az acc
ount list-locations -o table"
}
DEPENDENCIES
 Implicit dependencies, which Terraform and
the provider determine automatically based
on the configuration
 Explicit dependencies, which you define using
the depends_on meta-argument
resource "azurerm_resource_group" "example" {
name = var.resource_group_name
location = var.location
}
resource "azurerm_storage_account" "example" {
name = "storageaccountname"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "GRS"
tags = {
environment = "staging"
}
}
BONUS!
Terraform v0.13.0 beta
Modules will support…
count, for_each, and
depends_on
OUTPUTS
 Used to organize data to be easily queried and shown back to the Terraform user
 Data is outputted when apply is called
 Outputs can be queried after a run using the terraform output <<output name>> command
output "SharedServices-RGName" {
value = azurerm_virtual_network.SharedServicesVNET.*.resource_group_name
}
output "SharedServices-VNet-Name" {
value = azurerm_virtual_network.SharedServicesVNET.*.name
}
output "SharedServices-VNet-ID" {
value = azurerm_virtual_network.SharedServicesVNET.*.id
}
PEANUT BUTTER /
JELLY TIME!
FEATURE COMPARISON
Feature ARM Terraform
Infrastructure as Code (IaC) Yes Yes
Readability JavaScript Object Notation (JSON) HashiCorp Configuration Language (HCL)
Execution plans Yes (‘What-If’ Preview) Yes
Dependencies Yes (Explicit) Yes (Implied)
Multi-Cloud No Yes
Configuration
Inline ‘DeploymentScript’ (PowerShell)
Preview
Provisioners / other Providers
Rollback State Yes – deploy prior template / rollback Yes – maintains state
Azure Preview features Yes Yes – inline ARM snippets
KeyVault support Yes Yes (also integrates with HashiCorp Vault)
Corrupted State State not needed Can be an issue
Supports DevOps Yes Yes
Cost / Support Free, uses Azure support Free / Paid (purchase support)
Parallel deployments Yes Yes
FEATURE COMPARISON (CONTINUED)
Feature ARM Terraform
Runs “Locally”
ARM template is uploaded / deployed in
Azure
Terraform uses REST calls via a client
machine
Delete resource in portal and not worry
about state Yes No
Support Comments Via an Attribute Yes including block comments
Speed Can take a while
Can be fast since it can deploy just a single
item based upon its plan
Math Functions Yes Yes
Count / Loops Yes Yes
Sub-Templates/Modules Yes – Linked Templates Yes – Modules
Deploy to multiple resource groups Requires many template Can be done in one template
Reference existing resources Variable with resource ID path “data” resource type
Reverse Engineer resources Export and Visual Studio Object by Object through importing
SYNTAX DIFFERENCES
SO YOU DO IT
RIGHT, THE FIRST
TIME!
BEST PRACTICES
 Use remote backends
 Manage Terraform, providers and modules versions
 Use implicit dependencies
 Use modules (custom or from the HashiCorp public registry https://registry.terraform.io)
 Use ARM templates only if you don’t have another choice
FOR LEARNIN’
STUFF
RESOURCES
 Why we use Terraform and not Chef, Puppet, Ansible, SaltStack, or CloudFormation - Yevgeniy
Brikman
 Best practices lab (by James Dumont Le Douarec)
 Built-in Terraform functions
 Terraform on Azure documentation (aka.ms/TFHub)
 Microsoft is investing deeply in Terraform on Azure
 Introducing the Azure Terraform Resource Provider
 Top questions about Terraform and Azure
 Adin’s personal curated list of Terraform learning resources
Don’t forget about these Visual
Studio Code (VS Code)
extensions:
 Azure Terraform (by
Microsoft)
 Terraform (by Mikael
Olenfalk)
 Now owned by
HashiCorp!
aka.ms/AA8J4ON
CERTIFICATION RESOURCES
 HashiCorp Terraform Certified Associate Preparation Guide (co-authored by Adin)
 Study Guide - Terraform Associate Certification (HashiCorp official)
 Exam Review - Terraform Associate Certification (HashiCorp official)
 Sample Questions - Terraform Associate Certification (HashiCorp official)
THIS IS ME
ADIN ERMIE
 Cloud Solution Architect – Azure Apps & Infra @ Microsoft
 Azure Infrastructure-as-a-Service (IaaS), Platform-as-a-Service (PaaS)
 Cloud Management & Security
 Azure Monitor, Azure Log Analytics and Azure Security Center (ASC)
 Cloud Governance
 Azure Policy, Blueprints, Management Groups, and Azure Cost Management (ACM)
 Business Continuity and Disaster Recovery (BCDR)
 Azure Site Recovery (ASR) / Azure Migrate, and Azure Backup
 Infrastructure-as-Code (IaC)
 Azure Resource Manager (ARM), and Terraform
 5x MVP - Cloud and Datacenter Management (CDM)
 1x HCA – HashiCorp Ambassador
Adin.Ermie@outlook.com
@AdinErmie
https://AdinErmie.com
linkedin.com/in/adinermie

Infrastructure-as-Code (IaC) using Terraform

  • 1.
    INFRASTRUCTUR E-AS-CODE (IAC) USING TERRAFORM(BEGINNER EDITION) Adin Ermie Cloud Solution Architect (Azure Apps & Infra) Microsoft
  • 2.
    AGENDA  Benefits ofInfrastructure-as-Code (IaC)  What is Terraform and why do people love it?  Terraform basics  Commands, workflow, resource creation, file structure  Azure Resource Manager (ARM) vs Terraform  Best practices  Resources for learning and certification
  • 3.
    BENEFITS OF INFRASTRUCTURE-AS-CODE(IAC)  Reproducible environments  Automation – CI/CD  Trackable – GitHub  Language - HCL  Workflow  Providers  Apply same configuration across clouds
  • 4.
    WHAT IS TERRAFORM? A templating language created by HashiCorp called HashiCorp Configuration Language (HCL)  Written in Go Lang  A tool that can be used to orchestrate the provisioning of:  Public clouds (Azure, AWS, GCP, Oracle, Alibaba)  On-premises (VMware)  Other (Cisco, GitHub, GitLab, New Relic, Okta, Rabbit MQ)  Uses State files (more on this later)  Is NOT used for configuration  PowerShell Desired State Configuration (DSC), Chef, Puppet, Ansible
  • 5.
    WHY PEOPLE LOVETERRAFORM?  Clean and easy code to write and maintain  Fully declarative configuration  Version control on infrastructure  Implicit dependencies management – explicit can be forced  Ecosystem of providers and skilled personnel NEW!
  • 6.
  • 7.
    TERRAFORM COMMANDS/WORKFLOW  Terraforminit  Initializes the current working directory  Terraform plan  Execution plan to validate against existing environment  Terraform apply  Deploys and updates resources  Terraform destroy  Removes all resources defined in a configuration Init Plan Apply Destroy
  • 8.
    BASIC RESOURCE CREATION Resource Type  Required provider  Name  Internal (to Terraform) name  Configuration  Deployment details resource "azurerm_resource_group" "SharedServicesRG" { name = "SharedServicesRG" location = "Canada Central" } NameResource Type Resource Configuration
  • 9.
    TERRAFORM FILE STRUCTURE terraform{ required_version = ">=0.12.0" backend "azurerm" { resource_group_name = "tstate" storage_account_name = "tstate123" container_name = "tstate" key = "terraform.tfstate" } } provider "azurerm" { version = ">=2.0.0" subscription_id = "<<REMOVED>>" client_id = "<<REMOVED>>" client_secret = "<<REMOVED>>" tenant_id = "<<REMOVED>>" } resource "azurerm_resource_group" "example" { name = var.resource_group_name location = var.location } resource "azurerm_storage_account" "example" { name = "storageaccountname" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location account_tier = "Standard" account_replication_type = "GRS" tags = { environment = "staging" } }
  • 10.
    BACKENDS  Determines howstate is loaded and how an operation such as apply is executed  By default, Terraform uses the "local" backend  Benefits of backends:  Working in a team  Store state remotely and protect state with locks to prevent corruption  Keeping sensitive information off disk  Retrieved on demand and only stored in memory  Remote operations  Remote execution terraform { required_version = ">=0.12.0" backend "azurerm" { resource_group_name = "tstate" storage_account_name = "tstate123" container_name = "tstate" key = "terraform.tfstate" } }
  • 11.
    STATE  State keepstrack of the all managed resources and their associated properties with current values.  Essential for managing changes to infrastructure over time  Preserve the state file for the entire life cycle of the resources  You can create a separate state file per resource group, application, shared service (ie. core networking)  Terraform Workspaces should also be used to separate application and environment boundaries  Recommended to use a remote backend to save state in centralized, secure storage  Example: Storage account, Terraform Cloud, Terraform Enterprise, Artifactory, Consul  You must initialize the Terraform State  This is what terraform init does IMPORTANT! Secrets (like usernames/passwords, access keys/tokens, etc.) can be written to your state file!
  • 12.
    PROVIDERS  The providerblock is used to configure the named provider  Is responsible for creating and managing resources, and for all other interactions including authentication  The version argument is optional, but recommended provider "azurerm" { version = ">=2.0.0" subscription_id = "<<REMOVED>>" client_id = "<<REMOVED>>" client_secret = "<<REMOVED>>" tenant_id = "<<REMOVED>>" }
  • 13.
    VARIABLES  Parameterize theconfigurations  If no value is assigned to a variable and the variable has a default key in its declaration, that value will be used for the variable  Can be provided…  Within the Terraform template  Within its own Terraform template file  Within a .TFVARS files  Through command-line  Through Environment variables NOTE! Variables have precedence 1. Command-line 2. From a file 3. Environment variables 4. UI Input resource "azurerm_resource_group" "example" { name = var.resource_group_name location = var.location } variable "location" { type = string default = "westus" description = "Specify a location see: az acc ount list-locations -o table" }
  • 14.
    DEPENDENCIES  Implicit dependencies,which Terraform and the provider determine automatically based on the configuration  Explicit dependencies, which you define using the depends_on meta-argument resource "azurerm_resource_group" "example" { name = var.resource_group_name location = var.location } resource "azurerm_storage_account" "example" { name = "storageaccountname" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location account_tier = "Standard" account_replication_type = "GRS" tags = { environment = "staging" } } BONUS! Terraform v0.13.0 beta Modules will support… count, for_each, and depends_on
  • 15.
    OUTPUTS  Used toorganize data to be easily queried and shown back to the Terraform user  Data is outputted when apply is called  Outputs can be queried after a run using the terraform output <<output name>> command output "SharedServices-RGName" { value = azurerm_virtual_network.SharedServicesVNET.*.resource_group_name } output "SharedServices-VNet-Name" { value = azurerm_virtual_network.SharedServicesVNET.*.name } output "SharedServices-VNet-ID" { value = azurerm_virtual_network.SharedServicesVNET.*.id }
  • 17.
  • 18.
    FEATURE COMPARISON Feature ARMTerraform Infrastructure as Code (IaC) Yes Yes Readability JavaScript Object Notation (JSON) HashiCorp Configuration Language (HCL) Execution plans Yes (‘What-If’ Preview) Yes Dependencies Yes (Explicit) Yes (Implied) Multi-Cloud No Yes Configuration Inline ‘DeploymentScript’ (PowerShell) Preview Provisioners / other Providers Rollback State Yes – deploy prior template / rollback Yes – maintains state Azure Preview features Yes Yes – inline ARM snippets KeyVault support Yes Yes (also integrates with HashiCorp Vault) Corrupted State State not needed Can be an issue Supports DevOps Yes Yes Cost / Support Free, uses Azure support Free / Paid (purchase support) Parallel deployments Yes Yes
  • 19.
    FEATURE COMPARISON (CONTINUED) FeatureARM Terraform Runs “Locally” ARM template is uploaded / deployed in Azure Terraform uses REST calls via a client machine Delete resource in portal and not worry about state Yes No Support Comments Via an Attribute Yes including block comments Speed Can take a while Can be fast since it can deploy just a single item based upon its plan Math Functions Yes Yes Count / Loops Yes Yes Sub-Templates/Modules Yes – Linked Templates Yes – Modules Deploy to multiple resource groups Requires many template Can be done in one template Reference existing resources Variable with resource ID path “data” resource type Reverse Engineer resources Export and Visual Studio Object by Object through importing
  • 20.
  • 21.
    SO YOU DOIT RIGHT, THE FIRST TIME!
  • 22.
    BEST PRACTICES  Useremote backends  Manage Terraform, providers and modules versions  Use implicit dependencies  Use modules (custom or from the HashiCorp public registry https://registry.terraform.io)  Use ARM templates only if you don’t have another choice
  • 23.
  • 24.
    RESOURCES  Why weuse Terraform and not Chef, Puppet, Ansible, SaltStack, or CloudFormation - Yevgeniy Brikman  Best practices lab (by James Dumont Le Douarec)  Built-in Terraform functions  Terraform on Azure documentation (aka.ms/TFHub)  Microsoft is investing deeply in Terraform on Azure  Introducing the Azure Terraform Resource Provider  Top questions about Terraform and Azure  Adin’s personal curated list of Terraform learning resources Don’t forget about these Visual Studio Code (VS Code) extensions:  Azure Terraform (by Microsoft)  Terraform (by Mikael Olenfalk)  Now owned by HashiCorp! aka.ms/AA8J4ON
  • 25.
    CERTIFICATION RESOURCES  HashiCorpTerraform Certified Associate Preparation Guide (co-authored by Adin)  Study Guide - Terraform Associate Certification (HashiCorp official)  Exam Review - Terraform Associate Certification (HashiCorp official)  Sample Questions - Terraform Associate Certification (HashiCorp official)
  • 26.
    THIS IS ME ADINERMIE  Cloud Solution Architect – Azure Apps & Infra @ Microsoft  Azure Infrastructure-as-a-Service (IaaS), Platform-as-a-Service (PaaS)  Cloud Management & Security  Azure Monitor, Azure Log Analytics and Azure Security Center (ASC)  Cloud Governance  Azure Policy, Blueprints, Management Groups, and Azure Cost Management (ACM)  Business Continuity and Disaster Recovery (BCDR)  Azure Site Recovery (ASR) / Azure Migrate, and Azure Backup  Infrastructure-as-Code (IaC)  Azure Resource Manager (ARM), and Terraform  5x MVP - Cloud and Datacenter Management (CDM)  1x HCA – HashiCorp Ambassador Adin.Ermie@outlook.com @AdinErmie https://AdinErmie.com linkedin.com/in/adinermie

Editor's Notes

  • #4 Example of GUI / Next-Next-Finish and mis-configuration Trackable/traceable (ie. configuration changes over time; re-deploy then have 10 additional steps post-deploy vs captured in template)
  • #5 Not used for configuration - Illustration of a sfork (yeah you can use it, but not as effective)
  • #6 New Kubernetes Provider https://www.hashicorp.com/blog/deploy-any-resource-with-the-new-kubernetes-provider-for-hashicorp-terraform The kubernetes-alpha provider lets you package, deploy, and manage all Kubernetes resources, including Custom Resource Definitions, using HashiCorp Configuration Language (HCL).  With the addition of the kubernetes-alpha provider, you can now manage the full lifecycle of Kubernetes and its workloads using Terraform. All Kubernetes resources are accessible through this new provider.
  • #8 The terraform init command is used to initialize a working directory containing Terraform configuration files. prepare a working directory for use the root configuration directory is consulted for backend configuration and the chosen backend is initialized using the given configuration settings the configuration is searched for module blocks, and the source code for referenced modules is retrieved from the locations given in their source arguments searches the configuration for both direct and indirect references to providers and attempts to load the required plugins The terraform plan command is used to create an execution plan.  - Will look by default into the current directory only, and will import any file with the extension TF and run the command you specified Determines what actions are necessary to achieve the desired state specified in the configuration files. The optional -out argument can be used to save the generated plan to a file for later execution The terraform apply command is used to apply the changes required to reach the desired state of the configuration By default, apply scans the current directory for the configuration and applies the changes appropriately. Can pass variables in-line on the command-line, or via a var-file The terraform destroy command is used to destroy the Terraform-managed infrastructure. This command accepts all the arguments and flags that the apply command accepts, with the exception of a plan file argument. If -auto-approve is set, then the destroy confirmation will not be shown.
  • #9 Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records. Resource Type: determines the kind of infrastructure object it manages and what arguments and other attributes the resource supports Each resource type in turn belongs to a provider, which is a plugin for Terraform that offers a collection of resource types Name: A resource block declares a resource of a given type (“azurerm_resource_group") with a given local name (“SharedServicesRG"). The name is used to refer to this resource from elsewhere in the same Terraform module, but has no significance outside of the scope of a module. The resource type and name together serve as an identifier for a given resource and so must be unique within a module. Configuration: Most arguments in this section depend on the resource type
  • #12 This state is used by Terraform to map real world resources to your configuration, keep track of metadata, and to improve performance for large infrastructures. Terraform uses this local state to create plans and make changes to your infrastructure. Prior to any operation, Terraform does a refresh to update the state with the real infrastructure.
  • #13 A provider is responsible for understanding API interactions and exposing resources. A provider is simply a third-party plugin that acts as a bridge between Terraform and any third-party, such as AWS, GCP, and more.
  • #14 Input variables serve as parameters for a Terraform module, allowing aspects of the module to be customized without altering the module's own source code, and allowing modules to be shared between different configurations.
  • #16 The terraform output command is used to extract the value of an output variable from the state file.
  • #19 Configurations: - Terraform has Providers for Chef (for example), to trigger configurations being applied as part of a deployment