SlideShare a Scribd company logo
1 of 102
Download to read offline
Terraform modules and some of best-
practices
Anton Babenko
@antonbabenko
March 2019
Anton Babenko
Terraform AWS fanatic since 2015
Organiser of HashiCorp UG, AWS UG, DevOps Norway, DevOpsDays Oslo
I 💚 open-source:
terraform-community-modules + terraform-aws-modules
antonbabenko/pre-commit-terraform — clean code and documentation
antonbabenko/terraform-docs-as-pdf
antonbabenko/modules.tf-lambda — generate Terraform code from visual diagrams
www.terraform-best-practices.com
medium.com/@anton.babenko
@antonbabenko — Twitter, GitHub, Linkedin
Collection of open-source Terraform AWS modules supported by the community.
More than 2 mil. downloads since September 2017.
(VPC, Autoscaling, RDS, Security Groups, ELB, ALB, Redshift, SNS, SQS, IAM, EKS, ECS…)
github.com/terraform-aws-modules
registry.terraform.io/modules/terraform-aws-modules
Write, plan and manage infrastructure as code
www.terraform.io
Google Cloud
Deployment Manager
Azure Resource
Manager
+morethan100providers
Why Terraform and not AWS CloudFormation,
Azure ARM, Google Cloud Deployment Manager?
• Terraform manages 100+ providers, has easier syntax (HCL), has native
support for modules and remote states, has teamwork related features, is an
open-source project.
• Provides a high-level abstraction of infrastructure (IaC)
• Allows for composition and combination
• Supports parallel management of resources (graph, fast)
• Separates planning from execution (dry-run)
Terraform — universal tool for everything with an API
GSuite
Dropbox files and access
New Relic metrics
Datadog users and metrics
Jira issues
All Terraform providers
Let’s start!
Terraform modules
Modules in Terraform are self-contained
packages of Terraform configurations that are
managed as a group.
Resource modules
Create resources in a very flexible configuration
Open-source
Resource modules
Resource modules
Resource modules
Resource modules
Q: Why use resource modules instead of resources?
A: Resources can’t be versioned, but modules can.
Resource modules
Infrastructure modules
Consist of resource modules
Enforce tags and company standards
Use preprocessors, jsonnet, cookiecutter
Infrastructure modules
Infrastructure modules
Infrastructure modules
Types of Terraform modules
Resource modules (github.com/terraform-aws-modules , for eg)
Infrastructure modules
-	[	]	How	to	write	modules?	
-	[	]	How	to	call	modules?	
-	[	]	How	to	work	with	the	code?
Tip №0
Check Terraform Registry before writing resource modules
Hide implementation details
Size
Size
https://github.com/mbtproject/mbt
Things to avoid in modules
Exception: logical providers (template, random, local, http, external)
Providers in modules — evil
Provisioner — evil
Avoid provisioner in all resources
Provisioner — evil
Avoid provisioner in all resources
Provisioner — evil
Avoid provisioner even in EC2 resources
Provisioner — evil
Avoid provisioner even in EC2 resources
null_resource provisioner — good
Traits of good Terraform modules
Documentation and examples
Feature rich
Sane defaults
Clean code
Tests
Read more: http://bit.ly/common-traits-in-terraform-modules
-	[x]	How	to	write	modules?	
		-	[x]	Do	not	write,	if	you	can	
		-	[x]	Avoid	providers	in	modules,	provisioners	
-	[	]	How	to	call	modules?	
-	[	]	How	to	work	with	the	code?
Call Terraform modules
Amount of resources and code keeps growing
How to organize and call?
How to orchestrate calls?
All-in-one
Good:
Declare variables and outputs in
fewer places
Bad:
Large blast radius
Everything is blocked at once
Impossible to specify dependencies
between modules (depends_on)
1-in-1
Good:
Smaller blast radius
Possible to join invocation
Easier and faster to work with
Bad:
Declare variables and outputs
in more places
Which way do you group your code?
All-in-one or 1-in-1?
Correct
MFA (Most Frequent Answer):
Somewhere in between
What kind of orchestration tool do you use?
-target
Makefile
…
Orchestration in Terraform
No really, do not try this at home!
Orchestration = Terragrunt
https://github.com/gruntwork-io/terragrunt/
Orchestration = Terragrunt
Orchestration = Terragrunt
Orchestration = Terragrunt
Orchestration = Terragrunt
tfvars can’t contain dynamic values :(
Orchestration = Terragrunt
Orchestration = Terragrunt
tfvars can’t contain dynamic values, so I
have fixed it :)
before_hook + shell script
https://github.com/antonbabenko/modules.tf-lambda/blob/master/templates/
terragrunt-common-layer/template/common/scripts/
update_dynamic_values_in_tfvars.sh
or use modules.tf
-	[x]	How	to	write	modules?	
-	[x]	How	to	call	modules?	
		-	[x]	1-in-1	works	beter	over	time	
		-	[x]	Orchestration	=	Terragrunt	
		-	[x]	Dynamic	values	in	tfvars	
-	[	]	How	to	work	with	the	code?
Add new features
Usually it is easy…
Create new or use existing
Create new or use existing
Create new or use existing
Create new or use existing
Work with lists
Work with lists
Work with lists
https://jsonnet.org/
Work with stateful lists
Work with stateful lists
Work with stateful lists
Work with stateful lists
Work with stateful lists
Integration
Integration
Auto-integration
Edge cases
Different AWS regions (version of S3 signature, EC2 ClassicLink,
IPv6)
Date of creation of AWS account
Limits on resources in AWS
Services and features availability
Avoid in Terraform
Not secret arguments should not be specified as command line
arguments => put them in tfvars
Reduce usage of "-target" and "-parallelism"
"Terraform workspaces" evil in=> separate by directories
Dependency hell in modules
-	[x]	How	to	write	modules?	
-	[x]	How	to	call	modules?	
-	[x]	How	to	work	with	the	code?	
		-	[x]	Lists	in	Terraform	0.11	can	be	painful	
		-	[x]	Perceive	Terraform	easier
-	[x]	How	to	write	modules?	
-	[x]	How	to	call	modules?	
-	[x]	How	to	work	with	the	code?	
-	[x]	Terraform	0.12	beta!
Terraform 0.12
HCL2 — simplified syntax
Loops ("for")
Dynamic blocks ("for_each")
Correct conditional operators (… ? … : …)
Extended types of variables
Templates in values
Links between resources are supported (depends_on everywhere)
Read more — https://www.hashicorp.com/blog/announcing-terraform-0-1-2-beta
Summary
Write less and simpler (Terraform 0.12 won’t fix your code for you!)
Use existing modules and utilities
How to handle secrets in Terraform?
• Can you accept secrets to be saved in state file in plaintext? Probably not.
• AWS IAM password & access secret keys — use PGP as keybase.io
• AWS RDS — set dummy password and change after DB is created
• AWS RDS — use iam_database_authentication_enabled = true
• EC2 instance user-data + AWS KMS
• EC2 instance user-data + AWS System Manager’s Parameter Store
• AWS Secrets Manager
• https://github.com/opencredo/terrahelp
• Other options:
• Secure remote state location (S3 bucket policy, KMS key)
What are the tools/solutions out there?
• Terraform Registry — collection of public Terraform modules for common
infrastructure configurations for any provider — https://registry.terraform.io/
• Terraform linter to detect errors that can not be detected by `terraform plan`
— https://github.com/wata727/tflint
• Terraform version manager — https://github.com/kamatama41/tfenv
• A web dashboard to inspect Terraform States — https://github.com/
camptocamp/terraboard
• Jsonnet — The data templating language — http://jsonnet.org
• terraform-compliance - BDD style Terraform validation/compliancy check —
https://github.com/eerkunt/terraform-compliance
Atlantis — Start working on Terraform as a team
A unified workflow for collaborating on Terraform through GitHub, GitLab and
Bitbucket
https://www.runatlantis.io
https://github.com/terraform-aws-modules/terraform-aws-atlantis
Bonus
✓ cloudcraft.co — design, plan and visualize
✓ terraform-aws-modules — building blocks of AWS infrastructure
✓ Terraform — infrastructure as code
Infrastructure as code generator — from visual diagrams to Terraform
https://github.com/antonbabenko/modules.tf-lambda
Demo video: https://www.youtube.com/watch?v=F1Ax1zfZbiY
1. Go to cloudcraft.co
2. Sign up, sign in (free account)
3. Draw your AWS infrastructure
4. Click "Export"
5. Click "Terraform code export"
Try it yourself!
modules.tf — generated code
✓ Potentially ready-to-use Terraform configurations
✓ Suits best for bootstrapping
✓ Enforces Terraform best-practices
✓ Batteries included (terraform-aws-modules, terragrunt, pre-commit)
✓ 100% free and open-source (https://github.com/antonbabenko/
modules.tf-lambda)
✓ Released under MIT license
Thanks!
Questions?
github.com/antonbabenko
twitter.com/antonbabenko

More Related Content

What's hot

What's hot (20)

Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
Terraform
TerraformTerraform
Terraform
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
 
Helm 3
Helm 3Helm 3
Helm 3
 
Effective terraform
Effective terraformEffective terraform
Effective 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
TerraformTerraform
Terraform
 
Terraform
TerraformTerraform
Terraform
 
Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and Grafana
 
Terraform Basics
Terraform BasicsTerraform Basics
Terraform Basics
 
Introduce to Terraform
Introduce to TerraformIntroduce to Terraform
Introduce to Terraform
 
Cloud Monitoring tool Grafana
Cloud Monitoring  tool Grafana Cloud Monitoring  tool Grafana
Cloud Monitoring tool Grafana
 
Terraform in deployment pipeline
Terraform in deployment pipelineTerraform in deployment pipeline
Terraform in deployment pipeline
 
Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019
 
The journey to GitOps
The journey to GitOpsThe journey to GitOps
The journey to GitOps
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
 
Introduction to helm
Introduction to helmIntroduction to helm
Introduction to helm
 
Kubernetes Helm (Boulder Kubernetes Meetup, June 2016)
Kubernetes Helm (Boulder Kubernetes Meetup, June 2016)Kubernetes Helm (Boulder Kubernetes Meetup, June 2016)
Kubernetes Helm (Boulder Kubernetes Meetup, June 2016)
 

Similar to Terraform modules and some of best-practices - March 2019

Similar to Terraform modules and some of best-practices - March 2019 (20)

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
 
Terraform modules and (some of) best practices
Terraform modules and (some of) best practicesTerraform modules and (some of) best practices
Terraform modules and (some of) best practices
 
Terraform modules and (some of) best practices
Terraform modules and (some of) best practicesTerraform modules and (some of) best practices
Terraform modules and (some of) best practices
 
Terraform Q&A - HashiCorp User Group Oslo
Terraform Q&A - HashiCorp User Group OsloTerraform Q&A - HashiCorp User Group Oslo
Terraform Q&A - HashiCorp User Group Oslo
 
Manage any AWS resources with Terraform 0.12 - April 2020
Manage any AWS resources with Terraform 0.12 - April 2020Manage any AWS resources with Terraform 0.12 - April 2020
Manage any AWS resources with Terraform 0.12 - April 2020
 
Terraform 0.12 + Terragrunt
Terraform 0.12 + TerragruntTerraform 0.12 + Terragrunt
Terraform 0.12 + Terragrunt
 
Terraform AWS modules and some best-practices - May 2019
Terraform AWS modules and some best-practices - May 2019Terraform AWS modules and some best-practices - May 2019
Terraform AWS modules and some best-practices - May 2019
 
Terraform Abstractions for Safety and Power
Terraform Abstractions for Safety and PowerTerraform Abstractions for Safety and Power
Terraform Abstractions for Safety and Power
 
Terraform vs Pulumi
Terraform vs PulumiTerraform vs Pulumi
Terraform vs Pulumi
 
Terraform AWS modules and some best practices - September 2019
Terraform AWS modules and some best practices - September 2019Terraform AWS modules and some best practices - September 2019
Terraform AWS modules and some best practices - September 2019
 
What you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructureWhat you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructure
 
[AWSKRUG 아키텍처 모임] 세일즈부스트 인프라스트럭처 사례 공유
[AWSKRUG 아키텍처 모임] 세일즈부스트 인프라스트럭처 사례 공유[AWSKRUG 아키텍처 모임] 세일즈부스트 인프라스트럭처 사례 공유
[AWSKRUG 아키텍처 모임] 세일즈부스트 인프라스트럭처 사례 공유
 
OSDC 2019 | Terraform best practices with examples and arguments by Anton Bab...
OSDC 2019 | Terraform best practices with examples and arguments by Anton Bab...OSDC 2019 | Terraform best practices with examples and arguments by Anton Bab...
OSDC 2019 | Terraform best practices with examples and arguments by Anton Bab...
 
Terraform training - Modules 🎒
Terraform training - Modules 🎒Terraform training - Modules 🎒
Terraform training - Modules 🎒
 
DevOps Days Kyiv 2019 -- What you see is what you get for AWS // Anton Babenko
DevOps Days Kyiv 2019 -- What you see is what you get for AWS // Anton BabenkoDevOps Days Kyiv 2019 -- What you see is what you get for AWS // Anton Babenko
DevOps Days Kyiv 2019 -- What you see is what you get for AWS // Anton Babenko
 
What you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructureWhat you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructure
 
Infrastructure as code, using Terraform
Infrastructure as code, using TerraformInfrastructure as code, using Terraform
Infrastructure as code, using Terraform
 
Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
 
Terraform + ansible talk
Terraform + ansible talkTerraform + ansible talk
Terraform + ansible talk
 
Introduction to IAC and Terraform
Introduction to IAC and Terraform Introduction to IAC and Terraform
Introduction to IAC and Terraform
 

More from Anton Babenko

More from Anton Babenko (13)

Gotchas using Terraform in a secure delivery pipeline
Gotchas using Terraform in a secure delivery pipelineGotchas using Terraform in a secure delivery pipeline
Gotchas using Terraform in a secure delivery pipeline
 
Описание инфраструктуры с Terraform на будущее
Описание инфраструктуры с Terraform на будущееОписание инфраструктуры с Terraform на будущее
Описание инфраструктуры с Terraform на будущее
 
Preview of Terraform 0.12 + modules.tf - Kiev HUG meetup
Preview of Terraform 0.12 + modules.tf - Kiev HUG meetupPreview of Terraform 0.12 + modules.tf - Kiev HUG meetup
Preview of Terraform 0.12 + modules.tf - Kiev HUG meetup
 
"I’ve heard you know infrastructure"
"I’ve heard you know infrastructure""I’ve heard you know infrastructure"
"I’ve heard you know infrastructure"
 
"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 ...
 
Continuous delivery in AWS
Continuous delivery in AWSContinuous delivery in AWS
Continuous delivery in AWS
 
Tools exist for a reason
Tools exist for a reasonTools exist for a reason
Tools exist for a reason
 
AWS CodeDeploy - basic intro
AWS CodeDeploy - basic introAWS CodeDeploy - basic intro
AWS CodeDeploy - basic intro
 
Managing AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormationManaging AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormation
 
Designing for elasticity on AWS - 9.11.2015
Designing for elasticity on AWS - 9.11.2015Designing for elasticity on AWS - 9.11.2015
Designing for elasticity on AWS - 9.11.2015
 
Recap of AWS re:invent 2015
Recap of AWS re:invent 2015Recap of AWS re:invent 2015
Recap of AWS re:invent 2015
 
Designing for elasticity on AWS
Designing for elasticity on AWSDesigning for elasticity on AWS
Designing for elasticity on AWS
 
Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Terraform modules and some of best-practices - March 2019