SlideShare a Scribd company logo
1 of 71
Download to read offline
The Hitchhiker's Guide to
Terraform your Infrastructure
Fernanda Martins - Tweakers Developers Summit 2020
Bio
github.com/flmmartins
linkedin.com/flmmartins
@flmmartins
Work @ L1NDA
Smart tools for workers and
businesses in the hospitality
industry.
DevOps Minion
Infrastructure as code lover
CI/CD enthusiast
Open Source addict
Gamer
Pianist wanna-be
Dutch learner
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
What is Terraform?
Provider: Use AWS
Resource: Create role
Resource:
Attach other
policies
Data: Build policy
https://learn.hashicorp.com/
terraform
https://events.hashicorp.co
m/workshops/amsterdam/
Terraform 0.12
● If you are starting to use terraform, use terraform 0.12
● All of the code in this presentation is 0.11
● All best practices in this presentation are terraform 0.12 compatible
Tip #1 - Migrating to 0.12
Use tfswitch to have multiple terraform
versions
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Modules
I used to write my own modules all
the time…
Module Writing
Modules
Tip #2 - Open Source Modules
Use Open Source modules! Help the community!
https://github.com/terraform-aws-modules
https://github.com/cloudposse
Tip #3 - Build modules & divide to conquer
Use Open Source modules + Your business rules
Module Source in Terraform
Repo Module Folder
Version
Local Path Module
Modules - Git Repository
● Allow re-use across different
terraform repositories
● Allow versioning
● Versioning allow better
development
Versioning will make your workflow
more complex
Modules - One repository for each module
Complexity will increase even more
because you will have thousands of
repositories to manage version & etc
Modules - Git Repository
Tip #4 - Use separate repository for modules
Use separate Git Repository for your modules if they are used across
multiple repositories or if you need versioning
Tip #5 - Avoid creating one repository for module
Use one repository with all your modules instead!
Modules - Securing Inputs & Outputs
Tip #6 - Secure Variables: Use CLI for passwords
Use var_file or TF_VAR
Tip #7 - Secure Outputs
If Terraform generates password use the sensitive option in your
outputs or a secret manager (Vault, etc…)
Document your modules with terraform-docs
Tip #8 - Tool to document your modules
It will generate documentation based in the description attribute
from inputs and outputs
https://github.com/segmentio/terraform-docs
Module Order & Dependency
● Terraform executes everything in parallel
● Order execution is done by using one module as input to other module.
This will tell Terraform to first run
run the bucket principal and then
run hosting_bucket
Dependency Drama
Troubled Dev: What if there’s no way to link 2
modules? What if only order does the trick?
https://github.com/hashicorp/terraform/issues/10462
Dependency Problem
Tip #9 - Use terragrunt to manage dependencies
You will see terragrunt be used to solve issues that terraform does
not during this presentation. More spoilers on next slides!
https://github.com/gruntwork-io/terragrunt
Before running this, run
the kms_role
Module Recap
● Avoid hassle: Use Open Source Modules
https://github.com/terraform-aws-modules
https://github.com/cloudposse
● Make your code in modules & divide to conquer
● Use a separate git repository for your modules to have versioning and more control
● Avoid creating one repository to each module to help your sanity
● Document your modules with https://github.com/segmentio/terraform-docs
● Use Terragrunt for module dependency control (more in next slides)
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Terraform State
What is a Terraform State?
Terraform must store state. 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 state is a JSON that represents your infrastructure
Important State Requirements
● Keep your state secure
● Remote
● Locking Mechanism
● State per environments
● No manual creation of state
Terraform Workspace, Right?
https://www.reddit.com/r/Terraform/comments/8qj3r2/when_to_use_workspaces/
Terraform State
Tip #10 - Use terragrunt to manage your state for you
https://github.com/gruntwork-io/terragrunt
What is terragrunt?
Terragrunt is a thin wrapper for Terraform that provides extra
tools for keeping your Terraform configurations DRY, working with
multiple Terraform modules, and managing remote state.
Terragrunt - A Terraform Wrapper
Terraform Code
Terragrunt Folder Structure
Terragrunt Environments
Environment Folder
State for Environment
Terragrunt State File development/terraform.tfvars
Remotely in S3
Secure State
Locking
Environment Variables!
Terragrunt - Terraform Call
development/app_storage/terraform.tfvars
Terraform - Don’t forget to use the state!
../../modules/app_storage/main
Required
Terragrunt State in S3
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Coding Tips
Naming & Tags
Naming your infra
${var.product}.${var.environment}.name.service
Example: webapp.demo.user-data.bucket.
PS: If you use more than one region be sure to add it in the name as well
Tip #11 - Use naming conventions
Tagging your infra - Why it is important?
● Distinguish your infrastructure (footprint)
● Monitor your infrastructure
● Group resources.
● Cost Separation
Tag in AWS
myid.label = value
Myid is your identifier and will differentiate your labels from external automation
I also use this format for Kubernetes Labels
Tag in AWS / Use labels in Kubernetes
Label can be:
1. Name - Name is not necessary a tag but I always add it for AWS
2. product - Name of your product
3. environment - your environment
4. component - categorization of asset. AWS: This can be your service like bucket. For
Kubernetes it could be deployment, ingress…
5. part-of - Is this component part of a bigger plan? What? Example: Monitoring,
Cluster-XYZ, CI-server
6. terraform.repository
7. terraform.module = name of your module
8. terraform.module.version = version (it can also be branch name)
Label example
Environment tags
Tip #12 - Standarise Tags/Labels by using Terraform
Module tags
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Data
Data Common Mistakes
● Data can make a resource change on every execution if you use as input.
Examples in aws_security_group:
vpc_id = “${data.aws_vpc.cluster_vpc.id}”
Tip #13 - If data gives trouble, use state data
only as last resort
If you use data from state you might suffer
compilation errors during plan/apply terraform
Only use data from state if absolute necessary
What is Data from the state?
When you use data you are making a request to your current infra for data
When you use data from state you are actually fetching from the actual terraform state
based on what you built. That’s why you should use output in your modules.
data "terraform_remote_state" "vpc" {}
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
null-resource
The Rebel Terraform Resource
Tip #14 - Avoid using null resources
Check if a terraform provider does what needs to be done instead of shell scripting
You will have less work, less coding
null-resources
If trigger change the command will run
Tip #15 - Use null resources with triggers & dependencies (explicit or not)
To ensure everything will run when it has to run
Use cases: Run Ansible & restarts pods in Kubernetes after infra change
Null-resources need to be programed to
destroy
BE CAREFUL with destroys in null_resources
Tip #16 - Add Destroy Conditional to
null-resources
Use with caution
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Local Files & Templating
Local File
Local File
Local File
Tip #17 - Avoid using local_files
Because on every CI/laptop terraform consider local file creation as a
change
Coding Recap
● Use naming conventions and use terraform to enforce it
● Use tags/label conventions and use terraform to enforce it
● If data is forcing your resource to change an alternative it is to get data from the
state
● Avoid use of null provider
● Null Provider: always use with triggers & dependency (explicit or implicit)
● Null Provider: add a destroy conditional when is safe
● Avoid using Local File
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Using Kubernetes with
Terraform
Motivation
● One Tool execution
● Seize the templating from terraform instead of HELM or
another templating library
● I need to alternate between terraform & kubernetes
commands.
Example:
○ Run Kubernetes to create load balancer
○ Run terraform to create dns record
Using null_resource provider
Tip #14 - AGAIN - Avoid using null resources
Using Kubernetes Provider
Using Kubernetes Provider - The issue
Using Kubernetes Provider - The issue
Tip #18 - For simple low maintenance kubernetes resources use terraform
Tip #19 - For sensitive/high maintenance kubernetes resources use other tools
Example: Your application
Agenda
● What is terraform
● Terraform 0.12
Insights on:
● Terraform Modules
● Terraform State
● Naming & Tagging
● Data
● Null Resources
● Local Files & Templating
● Kubernetes with Terraform
● Running Terraform & Pipelines
Running terraform
Terragrunt plan-all/apply-all
Tip #20 - Use Terragrunt plan/apply-all to make sure your infra is always
matching code
● Good for testing if all modules are fine after adding another one
● Module dependency control
● Support for multiple aws-accounts
● And much more...
Terraform plan/apply for 1 module
Why? Plan-All output can be really bad and if you are testing/coding or if when the
output is looking horrible.
To inspect your code better I would use plan with terraform-landscape and during initial
testing I would only apply in one module.
Tip #21 - To better see the results of your plan use landscape CLI
Pipeline
Why use a Pipeline?
● No more hassle of setting your AWS account every run
● My CLI secret variables are now in the CI and I don’t have to
worry about them in my laptop
● Everyone can run terraform
Tip #22 - Build a pipeline to run terraform for you
Plan/Apply
You can choose a module. Ex: app_storage
Environment
Tools to Explore
Tools still to explore
● Terratest - Testing
● Atlantis - CI for terraform
● Helm with Terraform for Kubernetes
● Dependabot - Keep your external modules up to date
● SecretHub - Provision Passwords & Keys for applications
● Will Pulumi beat Terraform? (https://www.pulumi.com/)
○ No more HCLs and Infra Languages: just use pure
Python/JS to build your infra
Thanks!
github.com/flmmartins
linkedin.com/flmmartins
@flmmartins
Questions?
I know the answer is 42

More Related Content

What's hot

Terraform - Taming Modern Clouds
Terraform  - Taming Modern CloudsTerraform  - Taming Modern Clouds
Terraform - Taming Modern CloudsNic Jackson
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructuredAmi Mahloof
 
AWS DevOps - Terraform, Docker, HashiCorp Vault
AWS DevOps - Terraform, Docker, HashiCorp VaultAWS DevOps - Terraform, Docker, HashiCorp Vault
AWS DevOps - Terraform, Docker, HashiCorp VaultGrzegorz Adamowicz
 
Introductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformIntroductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformMichael Heyns
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesYevgeniy Brikman
 
Terraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerTerraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerCalvin French-Owen
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices Nebulaworks
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...Anton Babenko
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformRadek Simko
 
Terraform Modules and Continuous Deployment
Terraform Modules and Continuous DeploymentTerraform Modules and Continuous Deployment
Terraform Modules and Continuous DeploymentZane Williamson
 
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)Stephane Jourdan
 
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...Vinod Narayanankutty
 
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
 
Transforming Infrastructure into Code - Importing existing cloud resources u...
Transforming Infrastructure into Code  - Importing existing cloud resources u...Transforming Infrastructure into Code  - Importing existing cloud resources u...
Transforming Infrastructure into Code - Importing existing cloud resources u...Shih Oon Liong
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021TomStraub5
 
How to deploy PHP projects with docker
How to deploy PHP projects with dockerHow to deploy PHP projects with docker
How to deploy PHP projects with dockerRuoshi Ling
 
Writing Ansible Modules (DENOG11)
Writing Ansible Modules (DENOG11)Writing Ansible Modules (DENOG11)
Writing Ansible Modules (DENOG11)Martin Schütte
 

What's hot (20)

Terraform - Taming Modern Clouds
Terraform  - Taming Modern CloudsTerraform  - Taming Modern Clouds
Terraform - Taming Modern Clouds
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
 
AWS DevOps - Terraform, Docker, HashiCorp Vault
AWS DevOps - Terraform, Docker, HashiCorp VaultAWS DevOps - Terraform, Docker, HashiCorp Vault
AWS DevOps - Terraform, Docker, HashiCorp Vault
 
Introductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformIntroductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with Terraform
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
 
Terraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerTerraform Abstractions for Safety and Power
Terraform Abstractions for Safety and Power
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices
 
Final terraform
Final terraformFinal terraform
Final terraform
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with Terraform
 
Terraform Modules and Continuous Deployment
Terraform Modules and Continuous DeploymentTerraform Modules and Continuous Deployment
Terraform Modules and Continuous Deployment
 
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)
Using Terraform.io (Human Talks Montpellier, Epitech, 2014/09/09)
 
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...
[Alibaba Cloud Singapore Community Meetup Webinar, 3 Sep 2020] Automate Your ...
 
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)
 
Transforming Infrastructure into Code - Importing existing cloud resources u...
Transforming Infrastructure into Code  - Importing existing cloud resources u...Transforming Infrastructure into Code  - Importing existing cloud resources u...
Transforming Infrastructure into Code - Importing existing cloud resources u...
 
Puppet: From 0 to 100 in 30 minutes
Puppet: From 0 to 100 in 30 minutesPuppet: From 0 to 100 in 30 minutes
Puppet: From 0 to 100 in 30 minutes
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021
 
How to deploy PHP projects with docker
How to deploy PHP projects with dockerHow to deploy PHP projects with docker
How to deploy PHP projects with docker
 
Writing Ansible Modules (DENOG11)
Writing Ansible Modules (DENOG11)Writing Ansible Modules (DENOG11)
Writing Ansible Modules (DENOG11)
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 

Similar to Terraform your Infrastructure with Modules, State, and Best Practices

Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdf
Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdfHashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdf
Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdfssuser705051
 
Terraform in production - experiences, best practices and deep dive- Piotr Ki...
Terraform in production - experiences, best practices and deep dive- Piotr Ki...Terraform in production - experiences, best practices and deep dive- Piotr Ki...
Terraform in production - experiences, best practices and deep dive- Piotr Ki...PROIDEA
 
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.pptxssuser0d6c88
 
Terraform + ansible talk
Terraform + ansible talkTerraform + ansible talk
Terraform + ansible talkJames Strong
 
Configuration management II - Terraform
Configuration management II - TerraformConfiguration management II - Terraform
Configuration management II - TerraformXavier Serrat Bordas
 
Terraforming your Infrastructure on GCP
Terraforming your Infrastructure on GCPTerraforming your Infrastructure on GCP
Terraforming your Infrastructure on GCPSamuel Chow
 
Terraform day 1
Terraform day 1Terraform day 1
Terraform day 1Kalkey
 
Collaborative Terraform with Atlantis
Collaborative Terraform with AtlantisCollaborative Terraform with Atlantis
Collaborative Terraform with AtlantisFerenc Kovács
 
Self-service PR-based Terraform
Self-service PR-based TerraformSelf-service PR-based Terraform
Self-service PR-based TerraformAndrew Kirkpatrick
 
Git ops & Continuous Infrastructure with terra*
Git ops  & Continuous Infrastructure with terra*Git ops  & Continuous Infrastructure with terra*
Git ops & Continuous Infrastructure with terra*Haggai Philip Zagury
 
Scaling terraform environments infracoders sydney 30 nov 2017
Scaling terraform environments   infracoders sydney 30 nov 2017Scaling terraform environments   infracoders sydney 30 nov 2017
Scaling terraform environments infracoders sydney 30 nov 2017William Tsoi
 
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 KrakowAnton Babenko
 
OracleBeer_Terraform_soe.pdf
OracleBeer_Terraform_soe.pdfOracleBeer_Terraform_soe.pdf
OracleBeer_Terraform_soe.pdfStefan Oehrli
 
RIMA-Infrastructure as a code with Terraform.pptx
RIMA-Infrastructure as a code with Terraform.pptxRIMA-Infrastructure as a code with Terraform.pptx
RIMA-Infrastructure as a code with Terraform.pptxMrJustbis
 
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...James Anderson
 

Similar to Terraform your Infrastructure with Modules, State, and Best Practices (20)

Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
 
Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdf
Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdfHashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdf
Hashicorp-Terraform-Deep-Dive-with-no-Fear-Victor-Turbinsky-Texuna.pdf
 
Terraform-2.pdf
Terraform-2.pdfTerraform-2.pdf
Terraform-2.pdf
 
Terraform in production - experiences, best practices and deep dive- Piotr Ki...
Terraform in production - experiences, best practices and deep dive- Piotr Ki...Terraform in production - experiences, best practices and deep dive- Piotr Ki...
Terraform in production - experiences, best practices and deep dive- Piotr Ki...
 
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 + ansible talk
Terraform + ansible talkTerraform + ansible talk
Terraform + ansible talk
 
Configuration management II - Terraform
Configuration management II - TerraformConfiguration management II - Terraform
Configuration management II - Terraform
 
Terraforming your Infrastructure on GCP
Terraforming your Infrastructure on GCPTerraforming your Infrastructure on GCP
Terraforming your Infrastructure on GCP
 
Terraform day 1
Terraform day 1Terraform day 1
Terraform day 1
 
Collaborative Terraform with Atlantis
Collaborative Terraform with AtlantisCollaborative Terraform with Atlantis
Collaborative Terraform with Atlantis
 
Self-service PR-based Terraform
Self-service PR-based TerraformSelf-service PR-based Terraform
Self-service PR-based Terraform
 
Terraform
TerraformTerraform
Terraform
 
Git ops & Continuous Infrastructure with terra*
Git ops  & Continuous Infrastructure with terra*Git ops  & Continuous Infrastructure with terra*
Git ops & Continuous Infrastructure with terra*
 
Scaling terraform environments infracoders sydney 30 nov 2017
Scaling terraform environments   infracoders sydney 30 nov 2017Scaling terraform environments   infracoders sydney 30 nov 2017
Scaling terraform environments infracoders sydney 30 nov 2017
 
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
 
OracleBeer_Terraform_soe.pdf
OracleBeer_Terraform_soe.pdfOracleBeer_Terraform_soe.pdf
OracleBeer_Terraform_soe.pdf
 
RIMA-Infrastructure as a code with Terraform.pptx
RIMA-Infrastructure as a code with Terraform.pptxRIMA-Infrastructure as a code with Terraform.pptx
RIMA-Infrastructure as a code with Terraform.pptx
 
TA-002-P.pdf
TA-002-P.pdfTA-002-P.pdf
TA-002-P.pdf
 
Introduction to IAC and Terraform
Introduction to IAC and Terraform Introduction to IAC and Terraform
Introduction to IAC and Terraform
 
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...
GDG Cloud Southlake no. 22 Gutta and Nayer GCP Terraform Modules Scaling Your...
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Terraform your Infrastructure with Modules, State, and Best Practices

  • 1. The Hitchhiker's Guide to Terraform your Infrastructure Fernanda Martins - Tweakers Developers Summit 2020
  • 2. Bio github.com/flmmartins linkedin.com/flmmartins @flmmartins Work @ L1NDA Smart tools for workers and businesses in the hospitality industry. DevOps Minion Infrastructure as code lover CI/CD enthusiast Open Source addict Gamer Pianist wanna-be Dutch learner
  • 3. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 4. What is Terraform? Provider: Use AWS Resource: Create role Resource: Attach other policies Data: Build policy https://learn.hashicorp.com/ terraform https://events.hashicorp.co m/workshops/amsterdam/
  • 5. Terraform 0.12 ● If you are starting to use terraform, use terraform 0.12 ● All of the code in this presentation is 0.11 ● All best practices in this presentation are terraform 0.12 compatible Tip #1 - Migrating to 0.12 Use tfswitch to have multiple terraform versions
  • 6. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 8. I used to write my own modules all the time… Module Writing
  • 9. Modules Tip #2 - Open Source Modules Use Open Source modules! Help the community! https://github.com/terraform-aws-modules https://github.com/cloudposse Tip #3 - Build modules & divide to conquer Use Open Source modules + Your business rules
  • 10. Module Source in Terraform Repo Module Folder Version Local Path Module
  • 11. Modules - Git Repository ● Allow re-use across different terraform repositories ● Allow versioning ● Versioning allow better development Versioning will make your workflow more complex
  • 12. Modules - One repository for each module Complexity will increase even more because you will have thousands of repositories to manage version & etc
  • 13. Modules - Git Repository Tip #4 - Use separate repository for modules Use separate Git Repository for your modules if they are used across multiple repositories or if you need versioning Tip #5 - Avoid creating one repository for module Use one repository with all your modules instead!
  • 14. Modules - Securing Inputs & Outputs Tip #6 - Secure Variables: Use CLI for passwords Use var_file or TF_VAR Tip #7 - Secure Outputs If Terraform generates password use the sensitive option in your outputs or a secret manager (Vault, etc…)
  • 15. Document your modules with terraform-docs Tip #8 - Tool to document your modules It will generate documentation based in the description attribute from inputs and outputs https://github.com/segmentio/terraform-docs
  • 16. Module Order & Dependency ● Terraform executes everything in parallel ● Order execution is done by using one module as input to other module. This will tell Terraform to first run run the bucket principal and then run hosting_bucket
  • 17. Dependency Drama Troubled Dev: What if there’s no way to link 2 modules? What if only order does the trick? https://github.com/hashicorp/terraform/issues/10462
  • 18. Dependency Problem Tip #9 - Use terragrunt to manage dependencies You will see terragrunt be used to solve issues that terraform does not during this presentation. More spoilers on next slides! https://github.com/gruntwork-io/terragrunt Before running this, run the kms_role
  • 19. Module Recap ● Avoid hassle: Use Open Source Modules https://github.com/terraform-aws-modules https://github.com/cloudposse ● Make your code in modules & divide to conquer ● Use a separate git repository for your modules to have versioning and more control ● Avoid creating one repository to each module to help your sanity ● Document your modules with https://github.com/segmentio/terraform-docs ● Use Terragrunt for module dependency control (more in next slides)
  • 20. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 22. What is a Terraform State? Terraform must store state. 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 state is a JSON that represents your infrastructure
  • 23. Important State Requirements ● Keep your state secure ● Remote ● Locking Mechanism ● State per environments ● No manual creation of state
  • 25. Terraform State Tip #10 - Use terragrunt to manage your state for you https://github.com/gruntwork-io/terragrunt What is terragrunt? Terragrunt is a thin wrapper for Terraform that provides extra tools for keeping your Terraform configurations DRY, working with multiple Terraform modules, and managing remote state.
  • 26. Terragrunt - A Terraform Wrapper Terraform Code Terragrunt Folder Structure
  • 28. Terragrunt State File development/terraform.tfvars Remotely in S3 Secure State Locking Environment Variables!
  • 29. Terragrunt - Terraform Call development/app_storage/terraform.tfvars
  • 30. Terraform - Don’t forget to use the state! ../../modules/app_storage/main Required
  • 32. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 35. Naming your infra ${var.product}.${var.environment}.name.service Example: webapp.demo.user-data.bucket. PS: If you use more than one region be sure to add it in the name as well Tip #11 - Use naming conventions
  • 36. Tagging your infra - Why it is important? ● Distinguish your infrastructure (footprint) ● Monitor your infrastructure ● Group resources. ● Cost Separation
  • 37. Tag in AWS myid.label = value Myid is your identifier and will differentiate your labels from external automation I also use this format for Kubernetes Labels
  • 38. Tag in AWS / Use labels in Kubernetes Label can be: 1. Name - Name is not necessary a tag but I always add it for AWS 2. product - Name of your product 3. environment - your environment 4. component - categorization of asset. AWS: This can be your service like bucket. For Kubernetes it could be deployment, ingress… 5. part-of - Is this component part of a bigger plan? What? Example: Monitoring, Cluster-XYZ, CI-server 6. terraform.repository 7. terraform.module = name of your module 8. terraform.module.version = version (it can also be branch name)
  • 39. Label example Environment tags Tip #12 - Standarise Tags/Labels by using Terraform Module tags
  • 40. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 41. Data
  • 42. Data Common Mistakes ● Data can make a resource change on every execution if you use as input. Examples in aws_security_group: vpc_id = “${data.aws_vpc.cluster_vpc.id}” Tip #13 - If data gives trouble, use state data only as last resort If you use data from state you might suffer compilation errors during plan/apply terraform Only use data from state if absolute necessary
  • 43. What is Data from the state? When you use data you are making a request to your current infra for data When you use data from state you are actually fetching from the actual terraform state based on what you built. That’s why you should use output in your modules. data "terraform_remote_state" "vpc" {}
  • 44. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 45. null-resource The Rebel Terraform Resource Tip #14 - Avoid using null resources Check if a terraform provider does what needs to be done instead of shell scripting You will have less work, less coding
  • 46. null-resources If trigger change the command will run Tip #15 - Use null resources with triggers & dependencies (explicit or not) To ensure everything will run when it has to run Use cases: Run Ansible & restarts pods in Kubernetes after infra change
  • 47. Null-resources need to be programed to destroy
  • 48. BE CAREFUL with destroys in null_resources Tip #16 - Add Destroy Conditional to null-resources Use with caution
  • 49. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 50. Local Files & Templating
  • 53. Local File Tip #17 - Avoid using local_files Because on every CI/laptop terraform consider local file creation as a change
  • 54. Coding Recap ● Use naming conventions and use terraform to enforce it ● Use tags/label conventions and use terraform to enforce it ● If data is forcing your resource to change an alternative it is to get data from the state ● Avoid use of null provider ● Null Provider: always use with triggers & dependency (explicit or implicit) ● Null Provider: add a destroy conditional when is safe ● Avoid using Local File
  • 55. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 57. Motivation ● One Tool execution ● Seize the templating from terraform instead of HELM or another templating library ● I need to alternate between terraform & kubernetes commands. Example: ○ Run Kubernetes to create load balancer ○ Run terraform to create dns record
  • 58. Using null_resource provider Tip #14 - AGAIN - Avoid using null resources
  • 61. Using Kubernetes Provider - The issue Tip #18 - For simple low maintenance kubernetes resources use terraform Tip #19 - For sensitive/high maintenance kubernetes resources use other tools Example: Your application
  • 62. Agenda ● What is terraform ● Terraform 0.12 Insights on: ● Terraform Modules ● Terraform State ● Naming & Tagging ● Data ● Null Resources ● Local Files & Templating ● Kubernetes with Terraform ● Running Terraform & Pipelines
  • 64. Terragrunt plan-all/apply-all Tip #20 - Use Terragrunt plan/apply-all to make sure your infra is always matching code ● Good for testing if all modules are fine after adding another one ● Module dependency control ● Support for multiple aws-accounts ● And much more...
  • 65. Terraform plan/apply for 1 module Why? Plan-All output can be really bad and if you are testing/coding or if when the output is looking horrible. To inspect your code better I would use plan with terraform-landscape and during initial testing I would only apply in one module. Tip #21 - To better see the results of your plan use landscape CLI
  • 67. Why use a Pipeline? ● No more hassle of setting your AWS account every run ● My CLI secret variables are now in the CI and I don’t have to worry about them in my laptop ● Everyone can run terraform Tip #22 - Build a pipeline to run terraform for you
  • 68. Plan/Apply You can choose a module. Ex: app_storage Environment
  • 70. Tools still to explore ● Terratest - Testing ● Atlantis - CI for terraform ● Helm with Terraform for Kubernetes ● Dependabot - Keep your external modules up to date ● SecretHub - Provision Passwords & Keys for applications ● Will Pulumi beat Terraform? (https://www.pulumi.com/) ○ No more HCLs and Infra Languages: just use pure Python/JS to build your infra