Table of Contents
Preface ix
1 Why Terraform 1
The Rise of DevOps 1
What Is Infrastructure as Code? 3
Ad Hoc Scripts 4
Configuration Management Tools 5
Server Templating Tools 7
Server Provisioning Tools 11
Benefits of Infrastructure as Code 13
How Terraform Works 15
How Terraform Compares to Other Infrastructure as Code Tools 17
Configuration Management Versus Provisioning 18
Mutable Infrastructure Versus Immutable Infrastructure 19
Procedural Language Versus Declarative Language 19
Master Versus Masterless 22
Agent Versus Agentless 23
Large Community Versus Small Community 25
Mature Versus Cutting Edge 27
Conclusion 27
2 Getting Started with Terraform 29
Set Up Your AWS Account 30
Install Terraform 33
Deploy a Single Server 34
Deploy a Single Web Server 39
Deploy a Configurable Web Server 45
Deploy a Cluster of Web Servers 49
Deploy a Load Balancer 52
Cleanup 58
Conclusion 58
3 How to Manage Terraform State 59
What Is Terraform State? 60
Shared Storage for State Files 61
Locking State Files 66
Isolating State Files 68
File Layout 70
Read-Only State 73
Conclusion 81
4 How to Create Reusable Infrastructure with Terraform Modules 83
Module Basics 88
Module Inputs 90
Module Outputs 94
Module Gotchas 96
File Paths 96
Inline Blocks 96
Module Versioning 99
Conclusion 104
5 Terraform Tips and Tricks: Loops, If-Statements, Deployment, and Gotchas 107
Loops 108
If-Statements 113
Simple If-Statements 113
More Complicated If-Statements 115
If-Else-Statements 117
Simple If-Else-Statements 118
More Complicated If-Else-Statements 119
Zero-Downtime Deployment 123
Terraform Gotchas 134
Count Has Limitations 134
Zero-Downtime Deployment has Limitations 136
Valid Plans Can Fail 137
Refactoring Can Be Tricky 139
Eventual Consistency Is Consistent…Eventually 141
Conclusion 142
6 How to Use Terraform as a Team 143
Version Control 144
A Repository for Modules 144
A Repository for Live Infrastructure 144
The Golden Rule of Terraform 145
Automated Tests 147
Prepare Your Code 147
Write the Test Code 151
Use Multiple Types of Automated Tests 153
Coding Guidelines 154
Documentation 154
File Layout 155
Style Guide 156
Workflow 157
Plan 157
Staging 157
Code Review 158
Production 159
Some Types of Terraform Changes Can Be Automated 159
Some Types of Terraform Changes Lead to Conflicts 160
Larger Teams May Need to Use a Development Pipeline 163
Conclusion 169
A Recommended Reading 171
Index 175