Statistics
22
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-30

AuthorKerim Satirli, Taylor Dolezal

Cloud services and SaaS software permeate every company's IT landscape, requiring a shift from manually provisioned services to a more structured approach, with codification at its core. Terraform provides tools to manage the lifecycle of your IT landscape across thousands of different cloud providers and SaaS platforms. By defining your infrastructure as code you can safely and predictably make changes, modularize crucial building blocks, and create reusable service components. Each recipe in this cookbook addresses a specific problem and prefaces the solution with detailed insights into the "how" and "why". If you're just starting with Terraform and codified infrastructure, this book will help you create a solid foundation, on which you can build for years to come. If you're an advanced user, this guide will help you reaffirm your knowledge and take it to the next level, as you challenge yourself with more complex infrastructure, spread across multiple providers. Recipes include: Strategies on how to use Terraform with Version Control Systems Validation and testing patterns for Terraform-managed infrastructure Methods for importing pre-existing resources Transforming infrastructure services into reusable components Integrating Terraform with other HashiCorp tools Deploying Containerized Workloads

Tags
No tags
ISBN: 1098108469
Publisher: O'Reilly Media
Publish Year: 2024
Language: 英文
Pages: 282
File Format: PDF
File Size: 4.7 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Kerim Satirli & Taylor Dolezal Terraform Cookbook Recipes for Codifying Infrastructure
9 7 8 1 0 9 8 1 0 8 4 6 5 5 6 5 9 9 ISBN: 978-1-098-10846-5 US $65.99 CAN $82.99 TERR AFORM Cloud services and SaaS software permeate every company’s IT landscape, requiring a shift from manually provisioned services to a more structured approach, with codification at its core. Terraform provides tools to manage the lifecycle of your IT landscape across thousands of different cloud providers and SaaS platforms. By defining your infrastructure as code, you can safely and predictably make changes, modularize crucial building blocks, and create reusable service components. Each recipe in this cookbook addresses a specific problem and prefaces the solution with detailed insights into the “how” and “why.” If you’re just starting with Terraform and codified infrastructure, this book will help you create a solid foundation you can build on for years to come. If you’re an advanced user, this guide will help you reaffirm your knowledge and take it to the next level as you challenge yourself with more complex infrastructure spread across multiple providers. Recipes include: • Strategies on how to use Terraform with version control systems • Validation and testing patterns for Terraform-managed infrastructure • Methods for importing preexisting resources • Transforming infrastructure services into reusable components • Integrating Terraform with other HashiCorp tools • Deploying containerized workloads Terraform Cookbook “Terraform is radically changing how people bring global digital infrastructure to life. This book is an excellent overview of how practitioners can use this tool to solve real-world challenges and bring order to the chaos of modern infrastructure management at scale.” Chris Devers, Technical Lead, EditShare “This book is a great desktop buddy to help you overcome some tricky tasks.” Adam McPartlan, Lead Consultant, Hippo Digital Kerim Satirli is a senior developer advocate at HashiCorp, where he coaches operators and developers on sustainable infrastructure and orchestration workflows. Taylor Dolezal is the head of ecosystem at the Cloud Native Computing Foundation, where he drives innovation and collaboration in the cloud native landscape.
Kerim Satirli and Taylor Dolezal Terraform Cookbook Recipes for Codifying Infrastructure
978-1-098-10846-5 [LSI] Terraform Cookbook by Kerim Satirli and Taylor Dolezal Copyright © 2025 Hello, Operator BV and Taylor Dolezal. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisition Editor: John Devins Development Editor: Michele Cronin Production Editor: Beth Kelly Copyeditor: nSight, Inc. Proofreader: Emily Wydeven Indexer: BIM Creatives, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea October 2024: First Edition Revision History for the First Edition 2024-10-03: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098108465 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Terraform Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii 1. Getting Started with Terraform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 When to Use Terraform 2 1.2 When Not to Use Terraform 3 1.3 Installing and Configuring Terraform 3 1.4 Understanding Terraform Providers 7 1.5 Understanding Terraform Modules 9 1.6 Modifying Terraform State with terraform console 10 1.7 Using HashiCorp Cloud Platform Terraform 11 1.8 Using Terraform with Visual Studio Code 13 1.9 Managing Terraform Provider Version Constraints 15 1.10 Strategies for Deploying Version-Controlled Terraform Code Repositories 16 1.11 Deploying a Docker Container with Terraform 18 1.12 Upgrading Terraform: From 0.x to 1.x and Beyond 19 1.13 Using Terraform Variables 21 1.14 Consistent Code for a Consistent Experience 22 2. Terraform Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.1 Formatting and Validating Terraform Code 25 2.2 Rapid Experimentation with terraform console 26 2.3 Improving Code Quality with TFLint 27 2.4 Improving Code Quality with TFSec 28 2.5 Validating Code with Preconditions and Postconditions 29 2.6 Validating Code with Open Policy Agent 31 2.7 Documenting Code with terraform-docs 33 2.8 Automating Code Validation with GitHub Actions 35 iii
2.9 Using Dependabot for Provider Version Updates 36 2.10 Using GitHub Codespaces and DevContainers 38 2.11 Limiting Blast Radius with Terraform 43 3. Terraform Syntax Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 3.1 Cleaning User Inputs with trimspace 47 3.2 Removing Prefixes and Suffixes 48 3.3 Working with Regular Expressions 49 3.4 Advanced String Manipulation 51 3.5 Working with Case-Sensitive Strings Using title, upper, and lower 52 3.6 Alphabetically Sorting Lists 54 3.7 Creating Subnets from a CIDR Block 55 3.8 Interacting with the Local Filesystem 57 3.9 Rendering Templates 59 3.10 Validating Input Strings 61 3.11 Optimistically Retrieving Data Using can and try 63 3.12 Sequentially Processing Input Data 66 3.13 Good Error Messages for Bad Input 68 3.14 Consuming Data Across Terraform States 70 4. Terraform Modules and Providers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 4.1 Using Public Modules to Create an EKS Cluster 73 4.2 Linting Terraform with GitHub Actions 76 4.3 Authentication for Terraform Providers 79 4.4 Authentication for Private Modules 81 4.5 Creating a Terraform Module 83 4.6 Managing GitHub Secrets with Terraform 85 4.7 Managing GitHub Repositories with Terraform 87 4.8 Dynamic Configuration with Consul KV 90 4.9 Service-Health-Aware Provider Configuration 92 4.10 Consuming Terraform State with Providers 95 4.11 Using Multiple, Identical Providers 97 5. Container Management with Terraform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 5.1 Using Local Versus Remote Docker Images 101 5.2 Distinguishing Between Cluster Deployment and Cluster Configuration 103 5.3 Authorizing Terraform for Cluster Operations 105 5.4 Scheduling Containers on Kubernetes with YAML 106 5.5 Scheduling Containers on Kubernetes with HCL 107 5.6 Transmuting Kubernetes YAML into HCL using k2tf 109 5.7 Adjusting Annotations for Kubernetes Deployments 111 iv | Table of Contents
5.8 Adjusting Configuration for Kubernetes Deployments 112 5.9 Applying Kubernetes NetworkPolicies with Terraform 114 5.10 Deploying Containers with Helm 117 5.11 Enabling Monitoring for Kubernetes Deployments Using Helm 119 5.12 Scheduling Containers on HashiCorp Nomad 122 6. HCP Terraform and Terraform Enterprise. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 6.1 Setting Up HCP Terraform 126 6.2 Integrating HCP Terraform with VCS 131 6.3 Consuming Terraform State with HCP Terraform 133 6.4 Using HCP Terraform with GitHub Actions 134 6.5 Collaborative Workflows with HCP Terraform 136 6.6 Troubleshooting HCP Terraform and Terraform Enterprise 138 6.7 Enforcing Policy as Code 140 6.8 Managing Costs with HCP Terraform 142 6.9 Utilizing Remote Operations for Large-Scale Deployments 145 6.10 Advanced State Management and Recovery 147 7. Consuming and Managing Secrets with Terraform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 7.1 Dealing with Sensitive Data in Terraform 152 7.2 Retrieving Key-Values from HashiCorp Vault 153 7.3 Managing Kubernetes Secrets with Kubernetes-Native Functions 155 7.4 Managing Kubernetes Secrets with Vault and Terraform 157 7.5 Storing Secrets as Environment Variables 161 7.6 Auditing and Rotating Secrets 162 7.7 Managing Secrets with Terraform and Password Managers 164 7.8 Compliance and Governance with Terraform Secrets 166 7.9 Dynamic Secrets with HashiCorp Vault 168 7.10 Securing Secret Injection in CI/CD Pipelines 170 8. Configuration Management with Terraform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 8.1 Writing Shell Scripts with Terraform 174 8.2 Writing Ansible Configuration with Terraform 175 8.3 Dynamic Configuration with Consul Key-Values 177 8.4 Consuming Data from HTTP Interfaces 179 8.5 Applying Conditional Logic in Terraform 180 8.6 Importing Existing Infrastructure into Terraform 182 8.7 Leveraging Terraform Workspaces 184 8.8 Utilizing Terraform Templates 186 8.9 Managing Dependencies Between Terraform Resources 187 8.10 Using Terraform for Blue-Green Deployments 189 Table of Contents | v
9. Advanced Terraform Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 9.1 Writing Configuration Files with Terraform 194 9.2 Writing Cloud-Init Configuration 195 9.3 Implementing Terraform Modules in CI/CD Pipelines 197 9.4 Advanced State Management in Terraform 200 9.5 Terraform and Multicloud Strategies 202 9.6 Terraform for Scalable Architectures 204 9.7 Terraform Custom Provider Development 207 9.8 Integrating Terraform with Monitoring Tools 210 9.9 Managing Security and Compliance with Terraform 214 9.10 Advanced Debugging Techniques in Terraform 218 10. Real-World Use Cases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 10.1 Managing Multiple Environments with Terraform Workspaces 221 10.2 Deploying a Highly Available Web Application Across Regions 224 10.3 Provisioning a Scalable Kubernetes Cluster on AWS EKS 227 10.4 Implementing Blue-Green Deployments with Terraform 230 10.5 Automating Database Migrations with Terraform and AWS RDS 234 10.6 Deploying a Serverless Application on AWS Lambda and API Gateway 237 10.7 Implementing Infrastructure as Code for GitOps Workflows 241 10.8 Optimizing Costs with Terraform and Spot Instances 244 10.9 Deploying a Multicloud Monitoring Solution with Terraform 246 10.10 Automating Disaster Recovery with Terraform and AWS 250 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 vi | Table of Contents
Preface In the not-so-distant past, managing IT infrastructure was a Herculean task. System administrators juggled a dizzying array of manual processes, custom scripts, and vendor-specific tools while keeping systems running smoothly. It was an era marked by configuration drift, unexpected downtime, and the constant fear of “What if the person who set this up leaves?” Enter the age of DevOps and infrastructure as code (IaC). This revolution gave us powerful tools to define, deploy, and manage infrastructure programmatically. At the forefront of this transformation stands HashiCorp Terraform, the most commonly used IaC tool. With Terraform, you can describe your entire infrastructure using a declarative lan‐ guage. Terraform enables you to version, review, and evolve your infrastructure like any other codebase, from servers to databases to load balancers to DNS records–if there’s an API for it, Terraform’s vast provider ecosystem will (very likely!) be able to support it. Instead of clicking through cloud provider consoles or writing provider-specific scripts, you can use a unified workflow across multiple clouds and services. This cookbook is your guide to harnessing the full power of Terraform, from founda‐ tional concepts to advanced techniques and real-world applications. Who Should Read This Book This book is for anyone responsible for creating, managing, or improving infrastruc‐ ture. That includes DevOps engineers, site reliability engineers, infrastructure devel‐ opers, system administrators, and even ambitious developers looking to broaden their skills. If you’ve ever had to provision a server, configure a load balancer, or lose sleep over a 3 A.M. production issue, this book is for you. vii
We don’t assume you’re already an expert in infrastructure or coding. A basic familiarity with cloud concepts and comfort with the command line should suffice. Everything else you need, you’ll learn along the way. Why We Wrote This Book As long-time practitioners and advocates of infrastructure as code, we’ve seen the transformative power of Terraform firsthand. But we’ve also experienced its learning curve and the challenges of applying it to real-world scenarios. While the official Terraform documentation is excellent for reference, there was a clear need for a practical, recipe-based approach to learning and applying Terraform. We wanted to create a resource that not only explains the “how” but also the “why” and “when” of using Terraform effectively. This book is the result of our combined years of experience, distilled into practical, actionable recipes. It’s the book we wish we had when we started our Terraform journey. What You Will Find in This Book Here’s a brief overview of what you’ll find in each chapter: • Chapter 1 gets you started with Terraform, covering installation, basic concepts, and your first deployments. • Chapters 2 and 3 dive deeper into Terraform syntax, functions, and best practices for writing clean, efficient code. • Chapter 4 explores Terraform modules and providers, teaching you how to create reusable, scalable infrastructure components. • Chapter 5 shows how to manage containers with Terraform, including deploy‐ ments to Kubernetes and other orchestration platforms. • Chapter 6 covers HCP Terraform Cloud and Enterprise, helping you understand how to use Terraform in a team setting with enhanced collaboration and gover‐ nance features. • Chapter 7 tackles the crucial topic of secret management in Terraform, ensuring your sensitive data remains secure. • Chapters 8 and 9 delve into advanced Terraform techniques, including configu‐ ration management and complex deployment strategies. • Finally, Chapter 10 combines real-world use cases, demonstrating how to apply everything you’ve learned to solve practical infrastructure challenges. viii | Preface
What You Won’t Find in This Book This book is definitely not a reference manual for every Terraform resource or provider. For those details, we recommend the official Terraform documentation. Instead, we focus on practical applications, best practices, and real-world scenarios that will help you become proficient with Terraform. We’ve tried to make the examples as accessible as possible, primarily using AWS due to its popularity and free tier offerings. However, the principles and techniques you’ll learn apply to cloud providers and services. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a general note. This element indicates a warning or caution. Preface | ix
Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at http://github.com/terraform-cookbook/recipes. We encourage you to clone this reposi‐ tory and follow along with the examples as you read: git clone http://github.com/terraform-cookbook/recipes.git The code examples are organized by chapter, making it easy to find the relevant code for each recipe. Note that some lines of code in the book are formatted to fit the page and might include lines breaks. You can find the correctly formatted code in the GitHub repository. If you have a technical question or a problem using the code examples, please send email to support@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Terraform Cookbook by Kerim Satirli and Taylor Dolezal (O’Reilly). Copyright 2025 Hello, Operator BV and Taylor Dolezal, 978-1-098-10846-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. We hope this book serves as your trusty guide in the exciting world of infrastructure as code with Terraform. May your infrastructure always be in the desired state, your deployments be swift and sure, and your “terraform apply” never need a prayer to the demo gods. Remember, in the world of Terraform, it’s not “to err is human.” To err is a great opportunity to test your rollback strategy. Now go forth and terraform apply responsibly! x | Preface
O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-827-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://oreilly.com/about/contact.html We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/terraform-cookbook. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media Watch us on YouTube: https://youtube.com/oreillymedia Acknowledgments We want to express our heartfelt gratitude directly to the many individuals and groups who have contributed to the creation of this book. Your efforts have not gone unnoticed. First and foremost, we extend our thanks to the incredible team at O’Reilly Media. Special recognition goes to Michele Cronin for her invaluable guidance and support throughout this project. We are also grateful to Beth Kelly for her expertise and to Preface | xi
John Devins for his assistance. Your collective efforts have significantly enhanced the quality and presentation of this book. We thank our reviewers Rosemary Wong, Chris Devers, Werner Dijkerman, Adam McPartlan, Jess Males, Ben Muschko, and Vishwesh Shrimali. Your insightful feed‐ back and suggestions have been instrumental in refining and improving the content of this book. Your expertise and time are greatly appreciated. Last but certainly not least, we want to acknowledge the vibrant Terraform commu‐ nity. This book, like Terraform itself, owes its existence to the collective knowledge, creativity, and passion of countless individuals. Your significant contributions, whether through code, documentation, or shared experiences, have not only shaped this book but the entire Terraform ecosystem. We are all better because of this community’s collaborative spirit and dedication. To everyone who has been a part of this journey, whether mentioned here by name or not, thank you. Your support, encouragement, and expertise have made Terraform Cookbook possible. xii | Preface
CHAPTER 1 Getting Started with Terraform Terraform is a source-available tool created by HashiCorp that allows you to man‐ age your infrastructure as code (IaC). It provides a simple and consistent way to define, provision, and manage resources across cloud platforms and on-premises environments. With Terraform, you can describe your infrastructure in a declarative language called the HashiCorp configuration language (HCL). This allows you to specify the desired state of your infrastructure rather than having to script the steps to get there. Terraform then applies this configuration to create, modify, or delete resources as necessary to achieve the desired state. The real power of Terraform is in its ability to manage complex infrastructure. You can create reusable modules that can be shared and applied to different projects, making it easy to maintain consistency across multiple environments. Additionally, Terraform’s state management system ensures that the current state of your infra‐ structure is tracked and can be used to update, destroy, or re-create resources as needed. One of the significant benefits of using Terraform is its support for a wide range of cloud providers, such as Amazon Web Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure. This allows you to manage your infrastructure across different providers, avoiding vendor lock-in and providing greater flexibility. Terra‐ form is widely used for cloud infrastructure and supports many noncloud-specific providers, such as Kubernetes, GitLab, and PostgreSQL. Its capabilities extend beyond cloud deployments to support hybrid and on-premises environments, includ‐ ing bare-metal hardware servers. Terraform is a powerful tool for reducing the friction around managing IaC, deploy‐ ing, maintaining, and scaling your applications. With Terraform, you can describe 1
your infrastructure using a simple and consistent language, reuse modules, and manage resources across different providers. This book is for infrastructure engineers, DevOps professionals, and cloud architects who want to learn how to effectively manage infrastructure as code using Terraform. Whether you’re new to infrastructure as code or looking to improve your Terraform skills, this book will walk you through practical examples and best practices to help you confidently deploy and manage infrastructure across different environments. It’s important to note that in August 2023, HashiCorp changed Terraform’s license from the Mozilla Public License (MPL) to the Business Source License (BSL). This change sparked significant discussion in the open source community and led to the creation of OpenTofu, an open source fork of Terraform that remains under the MPL. The BSL allows for most open source use cases but restricts using Terraform as a competing product or service. While this book focuses on HashiCorp’s Terraform, we have written our examples, concepts, and practices to work with OpenTofu as well. Users should be aware of these licensing changes and consider their implications when choosing between Terraform and OpenTofu for their projects. 1.1 When to Use Terraform Terraform is an excellent choice when managing complex infrastructure composed of many resources. It’s beneficial when managing infrastructure that spans multiple cloud providers or on-premises environments. Here are some examples of when to use Terraform: Managing multiple environments Terraform excels at managing multiple environments, such as development, stag‐ ing, and production. With Terraform, you can define your infrastructure as code, making it easy to deploy and manage across environments. Managing complex infrastructure Terraform is particularly useful for managing complex infrastructure composed of many resources. With Terraform, you can define your infrastructure in a declarative language, creating, modifying, and deleting resources. Managing infrastructure across cloud providers Terraform is an excellent choice for managing infrastructure across different cloud providers. With Terraform, you can consistently define your infrastructure, regardless of your cloud provider. Automating infrastructure deployment Terraform is an excellent choice for automating infrastructure deployment. With Terraform, you can define your infrastructure as code and use automation tools, such as CI/CD pipelines, to deploy your infrastructure automatically. 2 | Chapter 1: Getting Started with Terraform
1.2 When Not to Use Terraform While Terraform is a powerful tool, some jobs have better choices. Here are some examples of when you might want to consider other tools: Single-server infrastructure If you manage a single server, you might not need Terraform. Simple configura‐ tion management tools such as Ansible or Puppet might be a better choice. Infrastructure as a service (IaaS) If you only use a single cloud provider and manage only a small amount of infrastructure, you might not need Terraform. Many cloud providers offer tools for managing infrastructure, such as AWS CloudFormation or Azure Resource Manager. Platform as a service (PaaS) If you use a service like Netlify or Google App Engine, you might not need Terraform. These providers typically manage the infrastructure for you, so you only need to worry about deploying your application. When deciding whether to use Terraform, consider the complexity of your infra‐ structure and whether you need to manage infrastructure across multiple providers. Consider other tools if you manage only a small amount of infrastructure or use only a single cloud provider. Unique or specialized systems. In some cases, particularly in medium to large organi‐ zations, specialized systems or departments with unique needs might not fit nicely into a standardized infrastructure-as-code approach. For example, manual configura‐ tion or more straightforward scripting tools might better serve a research lab with custom equipment or a department with legacy systems. However, if your organiza‐ tion has broadly adopted an infrastructure-as-code mindset, it’s worth considering whether these “snowflake” systems could benefit from being managed with code. This approach could provide consistency, ease of redeployment, and better integration with your overall infrastructure management strategy. The decision often depends on the specific needs of the system, the skills of the team managing it, and your organization’s overall infrastructure philosophy. 1.3 Installing and Configuring Terraform Problem You need to install Terraform on your local machine or a remote server. 1.2 When Not to Use Terraform | 3
Solution Use the appropriate installation method for your operating system or package manager. Here are the steps for installing Terraform on some popular operating systems: Installing Terraform on Linux Many Linux distributions offer Terraform in their official package repositories. For example, on Debian/Ubuntu systems, you can install Terraform using: sudo apt update sudo apt install terraform On Red Hat-based systems, you can use: sudo yum install terraform If your distribution doesn’t offer Terraform or you need a specific version, follow these manual installation steps: 1. Download the latest Terraform package for Linux from the official Terraform website. 2. Extract the downloaded package to a directory on your system. For example, sudo unzip terraform_1.9.2_linux_amd64.zip -d /usr/local/bin/. 3. Make the Terraform binary executable by running sudo chmod +x /usr/ local/bin/terraform. 4. Verify the installation by running terraform version. Installing Terraform on macOS Homebrew is a popular package manager for macOS, but it’s not included by default. If you don’t have Homebrew installed, install it from https://brew.sh before proceed‐ ing with these instructions: 1. Install Terraform using Homebrew by running: brew tap hashicorp/tap brew install hashicorp/tap/terraform 2. Verify the installation by running: terraform version 4 | Chapter 1: Getting Started with Terraform
Installing Terraform on Windows Follow these steps: 1. Download the latest Terraform package for Windows from the official Terraform website. 2. Extract the downloaded package to a directory on your system. 3. Add the directory containing the Terraform executable to your system’s PATH environment variable. 4. Verify the installation by running terraform version. Installing OpenTofu OpenTofu, the open source fork of Terraform, can be installed using similar methods. Here are the installation steps for different operating systems: Linux You can use the official OpenTofu install script: curl --proto '=https' --tlsv1.2 -fsSL https://get.opentofu.org/install-opentofu.sh | sh Alternatively, you can download the binary from the OpenTofu GitHub releases page, extract it, and move it to your PATH. macOS Using Homebrew: brew install opentofu You can also use the official install script or download the binary described in the Linux instructions. Windows You can use Chocolatey: choco install opentofu Alternatively, download the Windows binary from the GitHub releases page, extract it, and add it to your PATH. After installation, you can verify the installation by running: tofu version 1.3 Installing and Configuring Terraform | 5
OpenTofu uses the tofu command instead of terraform to avoid conflicts if both are installed on the same system. Remember that while the installation processes for Terraform and OpenTofu are different, the usage and syntax are nearly identical. The examples in this book will work with both tools, with the main difference being the command used (terraform versus tofu). Discussion Terraform and OpenTofu are available for various operating systems and can be installed through multiple methods, including package managers, official installers, and manual installation from binaries. The choice of installation method often depends on your specific needs and system configuration. Package managers such as Advanced Packaging Tool (APT), Yellowdog Updater Modified (YUM), and Homebrew offer the most straightforward installation process and automatically handle tasks like adding executables to your PATH. They also make it easy to update to newer versions. However, they may not always offer the latest version immediately after release. Manual installation from binaries gives you more control over the exact version you’re installing and where it’s placed on your system. This can be useful in environ‐ ments where you must run multiple versions or have specific system requirements. However, it requires more hands-on management, including manually updating your PATH and handling upgrades. The installation process for OpenTofu is similar to Terraform, with the main dif‐ ference being the source of the binaries and the command used (tofu instead of terraform). This allows you to have both installed on the same system without conflicts. When installing either tool, verifying the installation by checking the version number is essential. This confirms a successful installation and lets you know the exact ver‐ sion you’re working with, which can be crucial when following tutorials or trouble‐ shooting issues. While Terraform and OpenTofu have different installation processes, their usage and syntax are nearly identical. The examples and concepts in this book apply to both tools, with the primary difference being the command invocation (terraform versus tofu). Regardless of which tool or installation method you choose, understanding the basics of the installation process can be helpful for troubleshooting, upgrading, or setting up development environments. As methods may change, always refer to the official documentation (see Figure 1-1) for the most up-to-date installation instructions. 6 | Chapter 1: Getting Started with Terraform