SlideShare a Scribd company logo
Infrastructure-as-Code (IaC)
USING TERRAFORM (INTERMEDIATE EDITION)
Adin Ermie
Cloud Solution Architect
(Azure Apps & Infra)
Microsoft
Agenda
Quick basics
•Commands,
resources, file
structure
01
Intermediate
•Commands
•Providers
•Lists, Maps, and
Loops
•Lifecycle
02
Reusability
•Modules
•Data sources
•Remote state
03
Branching
(into DevOps)
•Workspaces (CLI)
•Terraform Cloud
04
Resources
•General
•Certification
05
Microsoft’s investments in
Terraform
Microsoft Team HashiCorp Team
Terraform AzureRM Provider updates
◦ Latest release (July 2, 2020)
enhancements/bug fixes
releases/updates published in June alone!
Terraform Module Registry
◦ https://registry.terraform.io/browse/modules?provider=azurerm
Roadmap
https://github.com/terraform-providers/terraform-provider-azurerm
Terraform v0.13 highlights
 Support for , , and
 New syntax
 Custom
 command connects a CLI user to the Terraform
Cloud app
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with "ami-"."
}
}
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "2.0.0"
}
}
}
Quick basics
Terraform basics
 Commands / Workflows (ie. init, plan, apply, destroy)
 Resource creation (ie. resource types, configurations)
 File structure (ie. backends, providers, variables, outputs)
Init
Plan
Apply
Destroy
resource "azurerm_resource_group" "SharedServicesRG" {
name = "SharedServicesRG"
location = "Canada Central"
}
NameResource Type
Resource Configuration
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"
}
}
Infrastructure-as-Code (IaC)
using Terraform (Beginner)
INTERMEDIATE
CONCEPTS
BEYOND THE BASICS
Terraform commands
 Terraform fmt (-recursive)
 Used to rewrite Terraform configuration files to a canonical format and style
 Terraform graph
 Used to generate a visual representation of either a configuration or execution plan
 Terraform show
 Used to provide human-readable output from a state or plan file
 Terraform validate
 Runs checks that verify whether a configuration is syntactically valid and internally consistent
 Terraform taint
 Manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on
the next apply
Alternative/non-default provider
 Optionally define multiple alternative ("aliased") configurations for a
single provider, to allow management of resources in different regions in
multi-region services
 A resource always has an implicit dependency on its associated provider,
to ensure that the provider is fully configured before any resource
actions are taken
 Arbitrary (ie. variable/parameter) expressions are not permitted for
provider because it must be resolved while Terraform is constructing the
dependency graph, before it is safe to evaluate expressions
Collections Types (Lists, Maps, and Sets)
 list (or tuple) is a sequence of values, like ["us-west-1a", "us-west-1c"]
 map (or object) is a group of values identified by named labels,
like {name = "Mabel", age = 52}
 set(...) is a collection of unique values that do not have any secondary
identifiers or ordering
 Note: When a list or tuple is converted to a set, duplicate values are
discarded, and the ordering of elements is lost
Loops and Conditionals
 Loops allow you to create many of the same resource at the same time
 The count meta-argument accepts a whole number and creates that many instances of the resource
 The for_each meta-argument accepts a map or a set of strings and creates an instance for each item in
that map or set
 The for expression iterates over each element, and then evaluates the expression, with X set to each
respective element
 A conditional expression uses the value of a bool expression to select one of two values
 Allows you to prevent a resource being created, updated or deleted given a certain condition
Lifecycle
 The lifecycle block and its contents are meta-arguments, available for all resource blocks regardless of
type.
 create_before_destroy (bool)
 The new replacement object is created first, and then the prior object is destroyed only once the
replacement is created
 prevent_destroy (bool)
 Cause Terraform to reject (with an error) any plan that would destroy the infrastructure object
associated with the resource, as long as the argument remains present in the configuration
 ignore_changes (list of attribute names)
 Share management responsibilities of a single object with a separate process
 Specifies resource attributes that Terraform should ignore when planning updates to the associated
remote object
REUSABILITY
DON’T REINVENT
(OR RE-CODE)
THE WHEEL
Modules
 A container for multiple resources that are used together
 Can call other modules, which lets you include the child
module's resources
 When sourced from local file paths do not support version,
since they're loaded from the same source repository
 All modules require a source argument, which can either be
the path to a local directory, or a remote module source
 After adding, removing, or modifying module blocks, you must
re-run terraform init to allow Terraform the opportunity to
adjust the installed modules
BONUS!
Terraform v0.13.0 beta
Modules will support…
count, for_each, and
depends_on
Data sources
 Allows a Terraform configuration to make use of information
defined outside of Terraform, or defined by another separate
Terraform configuration
 A data block requests that Terraform read from a given data
source (“azurerm_virtual_network") and export the result
under the given local name (“ProdVNET")
 Within the block body (between { and }) are query constraints
defined by the data source
Remote state
 Allows you to use the root-level outputs of one or more
Terraform configurations as input data for another
configuration
 Only the root-level outputs from the remote state are
accessible. Outputs from modules within the state cannot
be accessed.
 If you want a module output or a resource attribute to be
accessible via a remote state, you must thread the output
through to a root output.
Bonus! TFLint
A part of the GitHub Super Linter
 One linter to rule them all
 Used to validate against issues
 Focused on possible errors, , etc.
 Support for all providers
 Rules that warn against
 AWS = 700+ rules
 Azure = 279 rules (Experimental support)
 GCP = WIP
BRANCHING
INTO DEVOPS
Workspaces (CLI)
 Used to manage collections of infrastructure resources and organize them into meaningful
groups by keeping their configurations (ie. state data, variables) in separate directories
 Technically equivalent to renaming your state file
 Example:
 Code used for a production environment's infrastructure could be split into a networking
configuration, the main application's configuration, and a monitoring configuration
 After splitting the code, you would create "networking-prod", "app1-prod", "monitoring-
prod" workspaces, and assign separate teams to manage them
 The important thing about workspace internals is that workspaces are meant to be a shared
resource. They aren't a private, local-only notion.
Note: Terraform Cloud and Terraform CLI both have
features called "workspaces," but they're slightly
different. CLI workspaces are alternate state files in
the same working directory; they're a convenience
feature for using one configuration to manage
multiple similar groups of resources.
Terraform Cloud
 Manages easy access to shared state and secret data, access controls for approving changes to
infrastructure, a private registry for sharing Terraform modules, detailed policy controls for
governing the contents of Terraform configurations
 Terraform Cloud acts as a remote backend for your Terraform state. State storage is tied to
workspaces, which helps keep state associated with the configuration that created it.
 Performs Terraform runs to provision infrastructure, either on demand or in response to various
events
 Executes these runs on disposable virtual machines in its own cloud infrastructure
 Remote execution helps provide consistency and visibility for critical provisioning operations
app.terraform.io
RESOURCES
FOR LEARNIN’ STUFF
Resources
Adin’s personal curated list of Terraform resources
Advanced Tips & Tricks to Optimize your Terraform Code
Terraform Advanced
Terraform on Microsoft Azure: Terraform projects organization and modules
How to create reusable infrastructure with Terraform modules
Terraform tips & tricks: loops, if-statements, and gotchas
Terraform in Action
Don’t forget about these Visual Studio
Code (VS Code) extensions:
 Azure Terraform (by Microsoft)
 Terraform (by Mikael Olenfalk)
 Now owned by HashiCorp!
Demo example code: https://github.com/mspnp/hadrinf/tree/master/Templates/Terraform/Networking
More resources
Terraform Configurations in Terraform Cloud Workspaces
Terraform Modules hands-on lab
Azure Terraform QuickStart Templates
Misadventures with Terraform
Commodified IaC Using Terraform Cloud
Getting Started with Terraform on Azure: Functions, Expressions, and Loops
Introducing TerraGoat, a “vulnerable-by-design” Terraform training project
Certification resources
HashiCorp Terraform Certified Associate Preparation Guide (co-authored by Adin Ermie)
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 Security Center (ASC) / Azure Sentinel
◦ 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

More Related Content

What's hot

Terraform
TerraformTerraform
Terraform
Phil Wilkins
 
Terraform
TerraformTerraform
Terraform
An Nguyen
 
Infrastructure as Code
Infrastructure as CodeInfrastructure as Code
Infrastructure as Code
Albert Suwandhi
 
Terraform
TerraformTerraform
Terraform
Otto Jongerius
 
Best Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with TerraformBest Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with Terraform
DevOps.com
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform Training
Yevgeniy Brikman
 
Terraform -- Infrastructure as Code
Terraform -- Infrastructure as CodeTerraform -- Infrastructure as Code
Terraform -- Infrastructure as Code
Martin Schütte
 
Terraform
TerraformTerraform
Terraform
Adam Vincze
 
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
Adin Ermie
 
Terraform
TerraformTerraform
Terraform on Azure
Terraform on AzureTerraform on Azure
Terraform on Azure
Mithun Shanbhag
 
Terraform
TerraformTerraform
Terraform
Marcelo Serpa
 
Terraform modules and best-practices - September 2018
Terraform modules and best-practices - September 2018Terraform modules and best-practices - September 2018
Terraform modules and best-practices - September 2018
Anton Babenko
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
Jason Vance
 
Getting Started with Infrastructure as Code
Getting Started with Infrastructure as CodeGetting Started with Infrastructure as Code
Getting Started with Infrastructure as Code
WinWire Technologies Inc
 
Introduce to Terraform
Introduce to TerraformIntroduce to Terraform
Introduce to Terraform
Samsung Electronics
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
Ami Mahloof
 
Terraform Basics
Terraform BasicsTerraform Basics
Terraform Basics
Mohammed Fazuluddin
 
Building infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps KrakowBuilding infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps Krakow
Anton Babenko
 
Intro to Terraform
Intro to TerraformIntro to Terraform
Intro to Terraform
Josh Michielsen
 

What's hot (20)

Terraform
TerraformTerraform
Terraform
 
Terraform
TerraformTerraform
Terraform
 
Infrastructure as Code
Infrastructure as CodeInfrastructure as Code
Infrastructure as Code
 
Terraform
TerraformTerraform
Terraform
 
Best Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with TerraformBest Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with Terraform
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform Training
 
Terraform -- Infrastructure as Code
Terraform -- Infrastructure as CodeTerraform -- Infrastructure as Code
Terraform -- Infrastructure as Code
 
Terraform
TerraformTerraform
Terraform
 
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
Infrastructure-as-Code (IaC) Using Terraform (Advanced Edition)
 
Terraform
TerraformTerraform
Terraform
 
Terraform on Azure
Terraform on AzureTerraform on Azure
Terraform on Azure
 
Terraform
TerraformTerraform
Terraform
 
Terraform modules and best-practices - September 2018
Terraform modules and best-practices - September 2018Terraform modules and best-practices - September 2018
Terraform modules and best-practices - September 2018
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
Getting Started with Infrastructure as Code
Getting Started with Infrastructure as CodeGetting Started with Infrastructure as Code
Getting Started with Infrastructure as Code
 
Introduce to Terraform
Introduce to TerraformIntroduce to Terraform
Introduce to Terraform
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
 
Terraform Basics
Terraform BasicsTerraform Basics
Terraform Basics
 
Building infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps KrakowBuilding infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps Krakow
 
Intro to Terraform
Intro to TerraformIntro to Terraform
Intro to Terraform
 

Similar to Infrastructure-as-Code (IaC) Using Terraform (Intermediate Edition)

Infrastructure as Code with Terraform.pptx
Infrastructure as Code with Terraform.pptxInfrastructure as Code with Terraform.pptx
Infrastructure as Code with Terraform.pptx
Samuel862293
 
Deploy resources on Azure using IaC (Azure Terraform)
Deploy  resources on Azure using IaC (Azure Terraform)Deploy  resources on Azure using IaC (Azure Terraform)
Deploy resources on Azure using IaC (Azure Terraform)
George Grammatikos
 
Terraform Definition, Working and Challenges it Overcomes
Terraform Definition, Working and Challenges it OvercomesTerraform Definition, Working and Challenges it Overcomes
Terraform Definition, Working and Challenges it Overcomes
Eyeglass Repair USA
 
DevOps Online Training | DevOps Training
DevOps Online Training | DevOps TrainingDevOps Online Training | DevOps Training
DevOps Online Training | DevOps Training
Visualpath Training
 
Using Terraform to manage the configuration of a Cisco ACI fabric.
Using Terraform to manage the configuration of a Cisco ACI fabric.Using Terraform to manage the configuration of a Cisco ACI fabric.
Using Terraform to manage the configuration of a Cisco ACI fabric.
Joel W. King
 
Building High Scalability Apps With Terracotta
Building High Scalability Apps With TerracottaBuilding High Scalability Apps With Terracotta
Building High Scalability Apps With Terracotta
David Reines
 
TA-002-P.pdf
TA-002-P.pdfTA-002-P.pdf
TA-002-P.pdf
ssuserea9ab8
 
Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
StephaneBoghossian1
 
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
NETWAYS
 
DevOps Training - Introduction to Terraform
DevOps Training - Introduction to TerraformDevOps Training - Introduction to Terraform
DevOps Training - Introduction to Terraform
Rauno De Pasquale
 
Terraform day1
Terraform day1Terraform day1
Terraform day1
Gourav Varma
 
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptxLinode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
AkwasiBoateng6
 
Hashicorp-Certified-Terraform-Associate-v3-edited.pptx
Hashicorp-Certified-Terraform-Associate-v3-edited.pptxHashicorp-Certified-Terraform-Associate-v3-edited.pptx
Hashicorp-Certified-Terraform-Associate-v3-edited.pptx
ssuser0d6c88
 
Terraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerTerraform Abstractions for Safety and Power
Terraform Abstractions for Safety and Power
Calvin French-Owen
 
Terraform Modules Restructured
Terraform Modules RestructuredTerraform Modules Restructured
Terraform Modules Restructured
DoiT International
 
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
Alex Cachia
 
Hibernate
HibernateHibernate
Infrastructure as Code for Azure: ARM or Terraform?
Infrastructure as Code for Azure: ARM or Terraform?Infrastructure as Code for Azure: ARM or Terraform?
Infrastructure as Code for Azure: ARM or Terraform?
Katherine Golovinova
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
Tim Berry
 
Terraform day 1
Terraform day 1Terraform day 1
Terraform day 1
Kalkey
 

Similar to Infrastructure-as-Code (IaC) Using Terraform (Intermediate Edition) (20)

Infrastructure as Code with Terraform.pptx
Infrastructure as Code with Terraform.pptxInfrastructure as Code with Terraform.pptx
Infrastructure as Code with Terraform.pptx
 
Deploy resources on Azure using IaC (Azure Terraform)
Deploy  resources on Azure using IaC (Azure Terraform)Deploy  resources on Azure using IaC (Azure Terraform)
Deploy resources on Azure using IaC (Azure Terraform)
 
Terraform Definition, Working and Challenges it Overcomes
Terraform Definition, Working and Challenges it OvercomesTerraform Definition, Working and Challenges it Overcomes
Terraform Definition, Working and Challenges it Overcomes
 
DevOps Online Training | DevOps Training
DevOps Online Training | DevOps TrainingDevOps Online Training | DevOps Training
DevOps Online Training | DevOps Training
 
Using Terraform to manage the configuration of a Cisco ACI fabric.
Using Terraform to manage the configuration of a Cisco ACI fabric.Using Terraform to manage the configuration of a Cisco ACI fabric.
Using Terraform to manage the configuration of a Cisco ACI fabric.
 
Building High Scalability Apps With Terracotta
Building High Scalability Apps With TerracottaBuilding High Scalability Apps With Terracotta
Building High Scalability Apps With Terracotta
 
TA-002-P.pdf
TA-002-P.pdfTA-002-P.pdf
TA-002-P.pdf
 
Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
 
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform ...
 
DevOps Training - Introduction to Terraform
DevOps Training - Introduction to TerraformDevOps Training - Introduction to Terraform
DevOps Training - Introduction to Terraform
 
Terraform day1
Terraform day1Terraform day1
Terraform day1
 
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptxLinode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
Linode_eBook_Declarative_Cloud_Infrastructure_Management_with_Terraform.pptx
 
Hashicorp-Certified-Terraform-Associate-v3-edited.pptx
Hashicorp-Certified-Terraform-Associate-v3-edited.pptxHashicorp-Certified-Terraform-Associate-v3-edited.pptx
Hashicorp-Certified-Terraform-Associate-v3-edited.pptx
 
Terraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerTerraform Abstractions for Safety and Power
Terraform Abstractions for Safety and Power
 
Terraform Modules Restructured
Terraform Modules RestructuredTerraform Modules Restructured
Terraform Modules Restructured
 
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
A brief introduction to IaC with Terraform by Kenton Robbins (codeHarbour May...
 
Hibernate
HibernateHibernate
Hibernate
 
Infrastructure as Code for Azure: ARM or Terraform?
Infrastructure as Code for Azure: ARM or Terraform?Infrastructure as Code for Azure: ARM or Terraform?
Infrastructure as Code for Azure: ARM or Terraform?
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
 
Terraform day 1
Terraform day 1Terraform day 1
Terraform day 1
 

Recently uploaded

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 

Recently uploaded (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 

Infrastructure-as-Code (IaC) Using Terraform (Intermediate Edition)

  • 1. Infrastructure-as-Code (IaC) USING TERRAFORM (INTERMEDIATE EDITION) Adin Ermie Cloud Solution Architect (Azure Apps & Infra) Microsoft
  • 2. Agenda Quick basics •Commands, resources, file structure 01 Intermediate •Commands •Providers •Lists, Maps, and Loops •Lifecycle 02 Reusability •Modules •Data sources •Remote state 03 Branching (into DevOps) •Workspaces (CLI) •Terraform Cloud 04 Resources •General •Certification 05
  • 3. Microsoft’s investments in Terraform Microsoft Team HashiCorp Team Terraform AzureRM Provider updates ◦ Latest release (July 2, 2020) enhancements/bug fixes releases/updates published in June alone! Terraform Module Registry ◦ https://registry.terraform.io/browse/modules?provider=azurerm
  • 5. Terraform v0.13 highlights  Support for , , and  New syntax  Custom  command connects a CLI user to the Terraform Cloud app variable "image_id" { type = string description = "The id of the machine image (AMI) to use for the server." validation { condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" error_message = "The image_id value must be a valid AMI id, starting with "ami-"." } } terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "2.0.0" } } }
  • 6. Quick basics Terraform basics  Commands / Workflows (ie. init, plan, apply, destroy)  Resource creation (ie. resource types, configurations)  File structure (ie. backends, providers, variables, outputs) Init Plan Apply Destroy resource "azurerm_resource_group" "SharedServicesRG" { name = "SharedServicesRG" location = "Canada Central" } NameResource Type Resource Configuration 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" } } Infrastructure-as-Code (IaC) using Terraform (Beginner)
  • 8. Terraform commands  Terraform fmt (-recursive)  Used to rewrite Terraform configuration files to a canonical format and style  Terraform graph  Used to generate a visual representation of either a configuration or execution plan  Terraform show  Used to provide human-readable output from a state or plan file  Terraform validate  Runs checks that verify whether a configuration is syntactically valid and internally consistent  Terraform taint  Manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply
  • 9. Alternative/non-default provider  Optionally define multiple alternative ("aliased") configurations for a single provider, to allow management of resources in different regions in multi-region services  A resource always has an implicit dependency on its associated provider, to ensure that the provider is fully configured before any resource actions are taken  Arbitrary (ie. variable/parameter) expressions are not permitted for provider because it must be resolved while Terraform is constructing the dependency graph, before it is safe to evaluate expressions
  • 10. Collections Types (Lists, Maps, and Sets)  list (or tuple) is a sequence of values, like ["us-west-1a", "us-west-1c"]  map (or object) is a group of values identified by named labels, like {name = "Mabel", age = 52}  set(...) is a collection of unique values that do not have any secondary identifiers or ordering  Note: When a list or tuple is converted to a set, duplicate values are discarded, and the ordering of elements is lost
  • 11. Loops and Conditionals  Loops allow you to create many of the same resource at the same time  The count meta-argument accepts a whole number and creates that many instances of the resource  The for_each meta-argument accepts a map or a set of strings and creates an instance for each item in that map or set  The for expression iterates over each element, and then evaluates the expression, with X set to each respective element  A conditional expression uses the value of a bool expression to select one of two values  Allows you to prevent a resource being created, updated or deleted given a certain condition
  • 12. Lifecycle  The lifecycle block and its contents are meta-arguments, available for all resource blocks regardless of type.  create_before_destroy (bool)  The new replacement object is created first, and then the prior object is destroyed only once the replacement is created  prevent_destroy (bool)  Cause Terraform to reject (with an error) any plan that would destroy the infrastructure object associated with the resource, as long as the argument remains present in the configuration  ignore_changes (list of attribute names)  Share management responsibilities of a single object with a separate process  Specifies resource attributes that Terraform should ignore when planning updates to the associated remote object
  • 14. Modules  A container for multiple resources that are used together  Can call other modules, which lets you include the child module's resources  When sourced from local file paths do not support version, since they're loaded from the same source repository  All modules require a source argument, which can either be the path to a local directory, or a remote module source  After adding, removing, or modifying module blocks, you must re-run terraform init to allow Terraform the opportunity to adjust the installed modules BONUS! Terraform v0.13.0 beta Modules will support… count, for_each, and depends_on
  • 15. Data sources  Allows a Terraform configuration to make use of information defined outside of Terraform, or defined by another separate Terraform configuration  A data block requests that Terraform read from a given data source (“azurerm_virtual_network") and export the result under the given local name (“ProdVNET")  Within the block body (between { and }) are query constraints defined by the data source
  • 16. Remote state  Allows you to use the root-level outputs of one or more Terraform configurations as input data for another configuration  Only the root-level outputs from the remote state are accessible. Outputs from modules within the state cannot be accessed.  If you want a module output or a resource attribute to be accessible via a remote state, you must thread the output through to a root output.
  • 17. Bonus! TFLint A part of the GitHub Super Linter  One linter to rule them all  Used to validate against issues  Focused on possible errors, , etc.  Support for all providers  Rules that warn against  AWS = 700+ rules  Azure = 279 rules (Experimental support)  GCP = WIP
  • 18.
  • 20. Workspaces (CLI)  Used to manage collections of infrastructure resources and organize them into meaningful groups by keeping their configurations (ie. state data, variables) in separate directories  Technically equivalent to renaming your state file  Example:  Code used for a production environment's infrastructure could be split into a networking configuration, the main application's configuration, and a monitoring configuration  After splitting the code, you would create "networking-prod", "app1-prod", "monitoring- prod" workspaces, and assign separate teams to manage them  The important thing about workspace internals is that workspaces are meant to be a shared resource. They aren't a private, local-only notion. Note: Terraform Cloud and Terraform CLI both have features called "workspaces," but they're slightly different. CLI workspaces are alternate state files in the same working directory; they're a convenience feature for using one configuration to manage multiple similar groups of resources.
  • 21. Terraform Cloud  Manages easy access to shared state and secret data, access controls for approving changes to infrastructure, a private registry for sharing Terraform modules, detailed policy controls for governing the contents of Terraform configurations  Terraform Cloud acts as a remote backend for your Terraform state. State storage is tied to workspaces, which helps keep state associated with the configuration that created it.  Performs Terraform runs to provision infrastructure, either on demand or in response to various events  Executes these runs on disposable virtual machines in its own cloud infrastructure  Remote execution helps provide consistency and visibility for critical provisioning operations app.terraform.io
  • 23. Resources Adin’s personal curated list of Terraform resources Advanced Tips & Tricks to Optimize your Terraform Code Terraform Advanced Terraform on Microsoft Azure: Terraform projects organization and modules How to create reusable infrastructure with Terraform modules Terraform tips & tricks: loops, if-statements, and gotchas Terraform in Action Don’t forget about these Visual Studio Code (VS Code) extensions:  Azure Terraform (by Microsoft)  Terraform (by Mikael Olenfalk)  Now owned by HashiCorp! Demo example code: https://github.com/mspnp/hadrinf/tree/master/Templates/Terraform/Networking
  • 24. More resources Terraform Configurations in Terraform Cloud Workspaces Terraform Modules hands-on lab Azure Terraform QuickStart Templates Misadventures with Terraform Commodified IaC Using Terraform Cloud Getting Started with Terraform on Azure: Functions, Expressions, and Loops Introducing TerraGoat, a “vulnerable-by-design” Terraform training project
  • 25. Certification resources HashiCorp Terraform Certified Associate Preparation Guide (co-authored by Adin Ermie) 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 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 Security Center (ASC) / Azure Sentinel ◦ 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

  1. Terraform Graph: The output is in the DOT format, which can be used by GraphViz to generate charts. Terraform Show: This can be used to inspect a plan to ensure that the planned operations are expected, or to inspect the current state as Terraform sees it. Terraform Validate: Primarily useful for general verification of reusable modules, including correctness of attribute names and value types. Terraform Taint: This command will not modify infrastructure, but does modify the state file in order to mark a resource as tainted. Once a resource is marked as tainted, the next plan will show that the resource will be destroyed and recreated and the next apply will implement this change. Note that tainting a resource for recreation may affect resources that depend on the newly tainted resource.
  2. The provider meta-argument overrides Terraform's default behavior of selecting a provider configuration based on the resource type name. By default, Terraform takes the initial word in the resource type name (separated by underscores) and selects the default configuration for that named provider. For example, the resource type azurerm_resource_group is associated automatically with the default configuration for the provider named azurerm. The provider meta-argument expects a <PROVIDER>.<ALIAS> reference, which does not need to be quoted.
  3. Count: If the resource has the count argument set, the value of this expression is a list of objects representing its instances. Each instance has a distinct infrastructure object associated with it and each is separately created, updated, or destroyed when the configuration is applied. When count is set, Terraform distinguishes between the resource block itself and the multiple resource instances associated with it. Instances are identified by an index number, starting with 0. <TYPE>.<NAME>[<INDEX>] (for example, aws_instance.server[0], aws_instance.server[1], etc.) refers to individual instances. For Each: If your resource instances are almost identical, count is appropriate. If some of their arguments need distinct values that can't be directly derived from an integer, it's safer to use for_each. The for_each meta-argument accepts a map or a set of strings and creates an instance for each item in that map or set.  For: A for expression can also include an optional if clause to filter elements from the source collection, which can produce a value with fewer elements than the source If the result type is an object (using { and } delimiters) then the value result expression can be followed by the ... symbol to group together results that have a common key
  4. Create Before Destroy: By default, when Terraform must make a change to a resource argument that cannot be updated in-place due to remote API limitations, Terraform will instead destroy the existing object and then create a new replacement object with the new configured arguments. Some resource types offer special options to append a random suffix onto each object name to avoid collisions, for example. Terraform CLI cannot automatically activate such features, so you must understand the constraints for each resource type before using create_before_destroy with it. Prevent Destroy: This can be used as a measure of safety against the accidental replacement of objects that may be costly to reproduce, such as database instances Note that this setting does not prevent the remote object from being destroyed if the resource block were removed from configuration entirely Ignore Changes: In some rare cases, settings of a remote object are modified by processes outside of Terraform, which Terraform would then attempt to "fix" on the next run. Think about when using Azure Policy and ‘deployIfNotExists’ policy actions
  5. Terraform Modules are a way that you can encapsulate shared code. The module takes inputs, does something and then produces outputs. By refactoring parts of your infrastructure into Modules you can easily enforce standards and keep resources in sync. Explain how you create a module (i.e a folder IS a module), and how you use a module (code-call).
  6. How do you reference an existing resource that was either deployed by a different Terraform template/process/workflow; or, already exists within the target environment (ie. a VNET)?
  7. Previous example was using Data Sources but this example is more real-world for the separation of, say, the Networking code vs Application code. For example, the Networking team can have their own workspace, state, modules, etc. and produces outputs for VNET and Subnet IDs. The Application team needs to leverage the VNET ID for deploying their App. So they can point to the appropriate backend containing the VNET state, and directly reference it. Remote state provides an easy reference to dynamic configuration parameters based on the output of other modules It is a simple way to handle “cross-stack” references in Terraform
  8. Highlight the NOTE first
  9. Terraform Cloud offers a team-oriented remote Terraform workflow The foundations of this workflow are remote Terraform execution, a workspace-based organizational model, version control integration, command-line integration, remote state management with cross-workspace data sharing, and a private Terraform module registry.
  10. NEWS: HashiICorp just recently (as of June 10th) released the v2 of the VS Code extension Important as this is the first official release from HashiCorp since taking over the extension See my blog for an article showing it in action!