SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
Lifecycle of a resource in Terraform
by Anton Babenko
Anton Babenko
Terraform AWS fanatic
Organiser of {HashiСorp, AWS, DevOps}
User Groups in Norway
DevOpsDays Oslo (29-30th October 2018)
github.com/antonbabenko
twitter.com/antonbabenko
linkedin.com/in/antonbabenko
Write, plan, and create infrastructure as code
www.terraform.io
Once created, infrastructure is going to
be updated…
And new versions of Terraform
will come out! Yay!!!
This talk is about evolution of resources
Code structure, Terraform coding tricks, refactoring
Terraform primitives
• Resources
• Data sources
• Variables
• Terraform state
Resources
• Create, Read, Update, Delete
• Lifecycles:
• ignore_changes
• prevent_destroy
• create_before_destroy
Data sources — read-only
Variables
• string, integer, boolean
• list
• map
Types of variables
Type of variable =>
string, integer,
boolean
list [] map {}
Command line Yes Yes Yes
*.tfvars Yes Yes Yes
Inside computing values (count,
lifecycle)
Yes No No
Inside other variables (string) Yes Yes Yes
Inside other variables (list) Yes Yes Yes, partially
Inside other variables (map) Yes Yes Yes
Terraform state
JSON file (*.tfstate) with information
about created resources
Humans should not touch it (often)
AWS S3 bucket
AWS EC2 Security Group
AWS EC2 Security Group module
Small infrastructure
As infrastructure grows and you manage more resources — how to group
them?
Resources + Data Sources = Module
Create Your First Module
https://www.terraform.io/docs/enterprise/guides/recommended-practices/part3.2.html#3-create-your-first-module
Types of Terraform modules
• Resource modules — very flexible, no relations to other modules, born to be
open-sourced
• Infrastructure modules — group of versioned resource modules, data-
sources, company-wide standards, code-generators (eg, jsonnet)
Usage of resource modules
Q: Why use resource modules
instead of resources?
A: Resources can’t be versioned,
but modules can.
Usage of infrastructure module
Modules tip #0
Check Terraform Registry before starting new resource module
Modules tip #1 — count types
Value of 'count' cannot be computed (issue #10857)
Modules tip #2 — scope
Remember the scope — no computed values in counts, no loops, no strict
assumptions on region/service availability.
Modules tip #3 — implementation
«Terraform module which creates RDS instance»
https://github.com/terraform-aws-modules/terraform-aws-rds
Modules tip #3 — implementation (example)
Modules tip #3 — usage (example)
Modules tip #4 — size
Usually infrastructure modules repositories have 99.9% waste — «terraform init» is slow
How to call modules?
There are two extremes:
1. Call many modules in one place
2. Call one module in one place
Composite pattern — many-in-one
Good:
1. Declare variables and outputs in fewer places
Bad:
1. Large blast radius — easier to break things
2. Locks everything at once
3. Single run vs orchestration concern (eg, first
run: data{0}=>resources{1}=>outputs{1}; second
run: data{0,1}=>resources{2}=>outputs{2})
4. No way to specify dependencies between
modules (depends_on)
Composite pattern — one-in-one
Good:
1. Small blast radius — harder to break
things
2. Possible to orchestrate, or chain runs
3. Easy to navigate
Bad:
1. Declare variables and outputs in
more places
Composite pattern — everything-in-between
The most popular choice
How to structure compositions?
1. Primary cloud provider services (VPC, ALB) or group of services (network, DB, shared)
2. Code changing frequency
3. Code change initiator (human or CI server)
4. Relation between components (eg, security group together with EC2 instance)
5. Used technology (AWS CodeDeploy, K8S, OpenShift)
6. Logical name of environment (staging, production)
7. Project
Code structure guidelines
• Try to keep Terraform state small and secure
• Use Terragrunt to orchestrate your configurations and to reduce copy-paste
• Let users to operate with «easy» values and keep interpolation magic hidden
most of the time
Poor man orchestration inception
WIP — https://github.com/antonbabenko/terraform-best-practices
Read more
Refactoring using Terraform 0.11
Refactoring
Any change (add feature, fix bug, improve design, optimise resource usage)
to the code which brings codebase closer to the desired state.
• incremental
• small
• accept the ugliness
• «edit & prey» vs «cover & modify»
Add new features/resources
Often easy, but…
Refactoring — conditional
Use existing resource or create a new one
Refactoring — lists
If user2 is removed then user3 and user4 will be recreated — this is a
problem for stateful resources like AWS IAM access keys.
jsonnet — alternative to lists for stateful
resources (eg, AWS IAM Access Keys)
Refactoring — import
• terraform import aws_iam_account_alias.this alias
• Use https://github.com/dtan4/terraforming to generate *.tf and tfstate from
existing AWS resources
Refactoring — rename/move
Refactoring — testing
•Basics — pre-commit (fmt, validate)
•Medium — review terraform plan
•On PR — Atlantis (runatlantis.io)
•Integration testing — terratest, awsspec
Refactoring — edge cases
• Test in different AWS regions (S3 signature, EC2 ClassicLink, IPv6)
• Check or open new github issues
Summary
• Terraform 0.11 has certain limitations — plan in advance!
• Use composition pattern — write less and simpler
• Reuse existing code and modules, fallback to documentation
Related Terraform projects
• https://github.com/antonbabenko/pre-commit-terraform — pre-commit git hooks to take care of
Terraform configurations (fmt, validate, terraform-docs)
• https://github.com/terraform-aws-modules/ — Collection of verified Terraform AWS modules
supported by the community
• https://github.com/antonbabenko/terraform-best-practices — Terraform best practices with
examples and arguments (WIP)
• https://cloudcraft.co/app?beta — «Export your AWS diagram as Terraform code» (tweet, modules.tf)
• https://github.com/antonbabenko/terrapin — Terraform module generator (POC)
• https://github.com/antonbabenko/terrible — Orchestrate Terraform configuration using Ansible
(POC)
Thank you!
Questions?
Code: github.com/antonbabenko
DM are open for all: twitter.com/antonbabenko

Mais conteúdo relacionado

Mais procurados

Kubernetes @ meetic
Kubernetes @ meeticKubernetes @ meetic
Kubernetes @ meetic
Sébastien Le Gall
 
Handling Redis failover with ZooKeeper
Handling Redis failover with ZooKeeperHandling Redis failover with ZooKeeper
Handling Redis failover with ZooKeeper
ryanlecompte
 

Mais procurados (20)

The Operator Pattern - Managing Stateful Services in Kubernetes
The Operator Pattern - Managing Stateful Services in KubernetesThe Operator Pattern - Managing Stateful Services in Kubernetes
The Operator Pattern - Managing Stateful Services in Kubernetes
 
OSDC 2018 | Monitoring Kubernetes at Scale by Monica Sarbu
OSDC 2018 | Monitoring Kubernetes at Scale by Monica SarbuOSDC 2018 | Monitoring Kubernetes at Scale by Monica Sarbu
OSDC 2018 | Monitoring Kubernetes at Scale by Monica Sarbu
 
Gocd – Kubernetes/Nomad Continuous Deployment
Gocd – Kubernetes/Nomad Continuous DeploymentGocd – Kubernetes/Nomad Continuous Deployment
Gocd – Kubernetes/Nomad Continuous Deployment
 
OSDC 2018 | Introduction to SaltStack in the Modern Data Center by Mike Place
OSDC 2018 | Introduction to SaltStack in the Modern Data Center by Mike PlaceOSDC 2018 | Introduction to SaltStack in the Modern Data Center by Mike Place
OSDC 2018 | Introduction to SaltStack in the Modern Data Center by Mike Place
 
Best practices in Deploying SUSE CaaS Platform v3
Best practices in Deploying SUSE CaaS Platform v3Best practices in Deploying SUSE CaaS Platform v3
Best practices in Deploying SUSE CaaS Platform v3
 
Kubernetes @ meetic
Kubernetes @ meeticKubernetes @ meetic
Kubernetes @ meetic
 
Demystifying Application Connectivity with Kubernetes in the Docker Platform
Demystifying Application Connectivity with Kubernetes in the Docker PlatformDemystifying Application Connectivity with Kubernetes in the Docker Platform
Demystifying Application Connectivity with Kubernetes in the Docker Platform
 
Securing & Monitoring Your K8s Cluster with RBAC and Prometheus”.
Securing & Monitoring Your K8s Cluster with RBAC and Prometheus”.Securing & Monitoring Your K8s Cluster with RBAC and Prometheus”.
Securing & Monitoring Your K8s Cluster with RBAC and Prometheus”.
 
Docker on mesos
Docker on mesosDocker on mesos
Docker on mesos
 
The Enterprise IT Checklist for Docker Operations
The Enterprise IT Checklist for Docker Operations The Enterprise IT Checklist for Docker Operations
The Enterprise IT Checklist for Docker Operations
 
Spark day 2017 - Spark on Kubernetes
Spark day 2017 - Spark on KubernetesSpark day 2017 - Spark on Kubernetes
Spark day 2017 - Spark on Kubernetes
 
Kubernetes Meetup - Seattle 2017-06-01
Kubernetes Meetup - Seattle 2017-06-01Kubernetes Meetup - Seattle 2017-06-01
Kubernetes Meetup - Seattle 2017-06-01
 
Orchestrating Redis & K8s Operators
Orchestrating Redis & K8s OperatorsOrchestrating Redis & K8s Operators
Orchestrating Redis & K8s Operators
 
Micro services vs hadoop
Micro services vs hadoopMicro services vs hadoop
Micro services vs hadoop
 
(Draft) Kubernetes - A Comprehensive Overview
(Draft) Kubernetes - A Comprehensive Overview(Draft) Kubernetes - A Comprehensive Overview
(Draft) Kubernetes - A Comprehensive Overview
 
Handling Redis failover with ZooKeeper
Handling Redis failover with ZooKeeperHandling Redis failover with ZooKeeper
Handling Redis failover with ZooKeeper
 
Persistent Data Storage for Docker Containers by Andre Moruga
Persistent Data Storage for Docker Containers by Andre MorugaPersistent Data Storage for Docker Containers by Andre Moruga
Persistent Data Storage for Docker Containers by Andre Moruga
 
Autoscaling Kubernetes
Autoscaling KubernetesAutoscaling Kubernetes
Autoscaling Kubernetes
 
SUSE CaaSP: deploy OpenFaaS and Ethereum Blockchain on Kubernetes
SUSE CaaSP: deploy OpenFaaS and Ethereum Blockchain on KubernetesSUSE CaaSP: deploy OpenFaaS and Ethereum Blockchain on Kubernetes
SUSE CaaSP: deploy OpenFaaS and Ethereum Blockchain on Kubernetes
 
Openshift Container Platform on Azure
Openshift Container Platform on AzureOpenshift Container Platform on Azure
Openshift Container Platform on Azure
 

Semelhante a OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform for the future by Anton babenko

Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm
Chandler Huang
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/Export
DuraSpace
 
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
Peter Keane
 
End-to-end Data Governance with Apache Avro and Atlas
End-to-end Data Governance with Apache Avro and AtlasEnd-to-end Data Governance with Apache Avro and Atlas
End-to-end Data Governance with Apache Avro and Atlas
DataWorks Summit
 

Semelhante a OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform for the future by Anton babenko (20)

Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019
 
Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
 
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
 
Large Scale Crawling with Apache Nutch and Friends
Large Scale Crawling with Apache Nutch and FriendsLarge Scale Crawling with Apache Nutch and Friends
Large Scale Crawling with Apache Nutch and Friends
 
Large Scale Crawling with Apache Nutch and Friends
Large Scale Crawling with Apache Nutch and FriendsLarge Scale Crawling with Apache Nutch and Friends
Large Scale Crawling with Apache Nutch and Friends
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
 
Terraform Modules Restructured
Terraform Modules RestructuredTerraform Modules Restructured
Terraform Modules Restructured
 
Effective terraform
Effective terraformEffective terraform
Effective terraform
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform Training
 
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceCOMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
Scaling an invoicing SaaS from zero to over 350k customers
Scaling an invoicing SaaS from zero to over 350k customersScaling an invoicing SaaS from zero to over 350k customers
Scaling an invoicing SaaS from zero to over 350k customers
 
Terraform Modules and Continuous Deployment
Terraform Modules and Continuous DeploymentTerraform Modules and Continuous Deployment
Terraform Modules and Continuous Deployment
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm
 
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
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/Export
 
MODELS 2019: Querying and annotating model histories with time-aware patterns
MODELS 2019: Querying and annotating model histories with time-aware patternsMODELS 2019: Querying and annotating model histories with time-aware patterns
MODELS 2019: Querying and annotating model histories with time-aware patterns
 
Storm - SpaaS
Storm - SpaaSStorm - SpaaS
Storm - SpaaS
 
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
 
End-to-end Data Governance with Apache Avro and Atlas
End-to-end Data Governance with Apache Avro and AtlasEnd-to-end Data Governance with Apache Avro and Atlas
End-to-end Data Governance with Apache Avro and Atlas
 

Último

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 

OSDC 2018 | Lifecycle of a resource. Codifying infrastructure with Terraform for the future by Anton babenko

  • 1. Lifecycle of a resource in Terraform by Anton Babenko
  • 2. Anton Babenko Terraform AWS fanatic Organiser of {HashiСorp, AWS, DevOps} User Groups in Norway DevOpsDays Oslo (29-30th October 2018) github.com/antonbabenko twitter.com/antonbabenko linkedin.com/in/antonbabenko
  • 3.
  • 4.
  • 5. Write, plan, and create infrastructure as code www.terraform.io
  • 6.
  • 7. Once created, infrastructure is going to be updated…
  • 8. And new versions of Terraform will come out! Yay!!!
  • 9. This talk is about evolution of resources Code structure, Terraform coding tricks, refactoring
  • 10. Terraform primitives • Resources • Data sources • Variables • Terraform state
  • 11. Resources • Create, Read, Update, Delete • Lifecycles: • ignore_changes • prevent_destroy • create_before_destroy
  • 12. Data sources — read-only
  • 13. Variables • string, integer, boolean • list • map
  • 14. Types of variables Type of variable => string, integer, boolean list [] map {} Command line Yes Yes Yes *.tfvars Yes Yes Yes Inside computing values (count, lifecycle) Yes No No Inside other variables (string) Yes Yes Yes Inside other variables (list) Yes Yes Yes, partially Inside other variables (map) Yes Yes Yes
  • 15. Terraform state JSON file (*.tfstate) with information about created resources Humans should not touch it (often)
  • 18. AWS EC2 Security Group module
  • 19. Small infrastructure As infrastructure grows and you manage more resources — how to group them?
  • 20. Resources + Data Sources = Module
  • 21. Create Your First Module https://www.terraform.io/docs/enterprise/guides/recommended-practices/part3.2.html#3-create-your-first-module
  • 22. Types of Terraform modules • Resource modules — very flexible, no relations to other modules, born to be open-sourced • Infrastructure modules — group of versioned resource modules, data- sources, company-wide standards, code-generators (eg, jsonnet)
  • 23. Usage of resource modules Q: Why use resource modules instead of resources? A: Resources can’t be versioned, but modules can.
  • 25. Modules tip #0 Check Terraform Registry before starting new resource module
  • 26. Modules tip #1 — count types Value of 'count' cannot be computed (issue #10857)
  • 27. Modules tip #2 — scope Remember the scope — no computed values in counts, no loops, no strict assumptions on region/service availability.
  • 28. Modules tip #3 — implementation «Terraform module which creates RDS instance» https://github.com/terraform-aws-modules/terraform-aws-rds
  • 29. Modules tip #3 — implementation (example)
  • 30. Modules tip #3 — usage (example)
  • 31. Modules tip #4 — size Usually infrastructure modules repositories have 99.9% waste — «terraform init» is slow
  • 32. How to call modules? There are two extremes: 1. Call many modules in one place 2. Call one module in one place
  • 33. Composite pattern — many-in-one Good: 1. Declare variables and outputs in fewer places Bad: 1. Large blast radius — easier to break things 2. Locks everything at once 3. Single run vs orchestration concern (eg, first run: data{0}=>resources{1}=>outputs{1}; second run: data{0,1}=>resources{2}=>outputs{2}) 4. No way to specify dependencies between modules (depends_on)
  • 34. Composite pattern — one-in-one Good: 1. Small blast radius — harder to break things 2. Possible to orchestrate, or chain runs 3. Easy to navigate Bad: 1. Declare variables and outputs in more places
  • 35. Composite pattern — everything-in-between The most popular choice
  • 36. How to structure compositions? 1. Primary cloud provider services (VPC, ALB) or group of services (network, DB, shared) 2. Code changing frequency 3. Code change initiator (human or CI server) 4. Relation between components (eg, security group together with EC2 instance) 5. Used technology (AWS CodeDeploy, K8S, OpenShift) 6. Logical name of environment (staging, production) 7. Project
  • 37. Code structure guidelines • Try to keep Terraform state small and secure • Use Terragrunt to orchestrate your configurations and to reduce copy-paste • Let users to operate with «easy» values and keep interpolation magic hidden most of the time
  • 41. Refactoring Any change (add feature, fix bug, improve design, optimise resource usage) to the code which brings codebase closer to the desired state. • incremental • small • accept the ugliness • «edit & prey» vs «cover & modify»
  • 43. Refactoring — conditional Use existing resource or create a new one
  • 44. Refactoring — lists If user2 is removed then user3 and user4 will be recreated — this is a problem for stateful resources like AWS IAM access keys.
  • 45. jsonnet — alternative to lists for stateful resources (eg, AWS IAM Access Keys)
  • 46. Refactoring — import • terraform import aws_iam_account_alias.this alias • Use https://github.com/dtan4/terraforming to generate *.tf and tfstate from existing AWS resources
  • 48. Refactoring — testing •Basics — pre-commit (fmt, validate) •Medium — review terraform plan •On PR — Atlantis (runatlantis.io) •Integration testing — terratest, awsspec
  • 49. Refactoring — edge cases • Test in different AWS regions (S3 signature, EC2 ClassicLink, IPv6) • Check or open new github issues
  • 50. Summary • Terraform 0.11 has certain limitations — plan in advance! • Use composition pattern — write less and simpler • Reuse existing code and modules, fallback to documentation
  • 51. Related Terraform projects • https://github.com/antonbabenko/pre-commit-terraform — pre-commit git hooks to take care of Terraform configurations (fmt, validate, terraform-docs) • https://github.com/terraform-aws-modules/ — Collection of verified Terraform AWS modules supported by the community • https://github.com/antonbabenko/terraform-best-practices — Terraform best practices with examples and arguments (WIP) • https://cloudcraft.co/app?beta — «Export your AWS diagram as Terraform code» (tweet, modules.tf) • https://github.com/antonbabenko/terrapin — Terraform module generator (POC) • https://github.com/antonbabenko/terrible — Orchestrate Terraform configuration using Ansible (POC)
  • 52. Thank you! Questions? Code: github.com/antonbabenko DM are open for all: twitter.com/antonbabenko