In today’s cloud-driven world, Infrastructure as Code (IaC) has become a pivotal concept for DevOps and cloud professionals. IaC allows developers and IT operations to manage and provision their cloud resources using code and software development techniques. One of the most popular IaC tools in the market is Terraform. Developed by HashiCorp, Terraform provides a declarative way to define and provision cloud infrastructure across multiple providers. One of the most crucial commands in the Terraform toolkit is terraform plan
. This command plays a significant role in understanding the potential changes that will be made to your infrastructure before they are actually applied.
What is Terraform Plan?
Understanding the Basics
The terraform plan
command is used to create an execution plan. This plan shows you what Terraform will do when you call terraform apply
. It’s a way to visualize the changes to your infrastructure before making them, ensuring that the changes align with your intentions.
Unlike other Terraform commands, such as terraform apply
which makes actual changes to your infrastructure, or terraform destroy
which removes resources, the terraform plan
command is a read-only operation. It won’t modify your infrastructure, but it will show you what would happen if you decide to apply those changes.
What Does Terraform Plan Do?
At its core, the terraform plan
command compares the current state of your infrastructure (as recorded in the Terraform state file) with the desired state defined in your Terraform configuration files. It then outputs the differences, showing you what additions, modifications, or deletions will occur if you proceed with terraform apply
.
For instance, if you’ve defined an AWS EC2 instance in your Terraform configuration but haven’t yet applied it, running terraform plan
will show that Terraform intends to create this new resource. Conversely, if you remove a resource from your configuration, the plan will indicate that Terraform intends to destroy it.
The terraform plan
command is an integral part of the Terraform lifecycle. Typically, after initializing your Terraform working directory with terraform init
, you’d run terraform plan
to see potential changes and then terraform apply
to enact those changes.
Related Reading
Where does Terraform Plan fit in an IaC Workflow
In an Infrastructure as Code workflow, predictability and transparency are paramount. Before making any changes to your infrastructure, it’s essential to understand the implications of those changes. This is where terraform plan
shines.
- Development Phase: As you write or modify your Terraform configurations, you can use
terraform plan
to ensure that your code reflects your desired infrastructure changes. - Code Review: When collaborating with a team, before merging changes into a shared repository, you can use the output of
terraform plan
as a part of the pull request. This provides reviewers a clear picture of the infrastructure changes that will result from the code changes. - Continuous Integration: In a CI/CD pipeline, after Terraform configurations are merged into the main branch, an automated process can run
terraform plan
to validate and review the changes before they’re applied to the production environment. - Documentation: The output of
terraform plan
can be used as documentation, providing a detailed record of changes over time.
By integrating terraform plan
into these stages, teams can ensure that infrastructure changes are deliberate, predictable, and transparent. This reduces the risk of unintended changes, which can lead to service outages or security vulnerabilities.
For those looking to dive deeper into Terraform and its capabilities, especially in the AWS ecosystem, the article on setting up Terraform provides a comprehensive guide. Additionally, understanding the nuances between Terraform vs CloudFormation can offer insights into choosing the right tool for your cloud infrastructure needs.
Diving Deeper: Terraform Plan Options and Parameters
Terraform, being a versatile Infrastructure as Code tool, provides a plethora of options and parameters to fine-tune its behavior. This flexibility ensures that Terraform can cater to various use cases and scenarios. In this section, we’ll delve deeper into the options and parameters available with the terraform plan
command, and how they can be utilized to customize and optimize your infrastructure planning process.
Terraform Plan Options
Terraform’s plan
command comes with several options that allow users to customize their execution plans. Let’s explore some of the most notable ones:
terraform plan --out
: This option allows you to save the generated execution plan to a file. This is particularly useful when you want to review the plan before applying it or share it with team members for collaborative review. For instance,terraform plan --out=myplan.tfplan
will save the plan to a file namedmyplan.tfplan
.terraform plan --destroy
: This option generates a plan that, if applied, would destroy all resources managed by Terraform in the current workspace. It’s a way to see what would happen if you were to tear down your entire infrastructure.terraform plan -lock
: By default, Terraform locks the state file to prevent concurrent modifications. However, in certain scenarios, you might want to override this behavior. Usingterraform plan -lock=false
disables the state lock during the plan generation.terraform plan -input
: Sometimes, Terraform might require input values that aren’t provided in the configuration. By default, Terraform asks for these inputs interactively. If you want to disable this behavior, you can useterraform plan -input=false
.
These are just a few of the many options available with terraform plan
. Each option is designed to give you more control over how Terraform interacts with your infrastructure and how it presents information to you.
Terraform Plan Variables and Parameters
Variables play a crucial role in Terraform configurations, allowing for dynamic and reusable code. When running the terraform plan
command, you might want to provide specific values for these variables:
terraform plan -var
: This option allows you to set a value for a variable. For instance,terraform plan -var="region=us-west-1"
sets theregion
variable tous-west-1
.terraform plan -var-file
: If you have multiple variables, it might be more efficient to store them in a file and provide that file as an input. For example,terraform plan -var-file="prod.tfvars"
would use the variable definitions from theprod.tfvars
file.terraform --var-file
: Similar to the above, but allows you to specify multiple variable files. The variables from the files are merged with later files overwriting earlier ones.
Using variables and parameters effectively can make your Terraform configurations more modular and adaptable to different environments or scenarios.
Terraform Plan vs Apply
Both terraform plan
and terraform apply
are fundamental commands in the Terraform workflow. However, they serve different purposes:
terraform plan
: As discussed, this command generates an execution plan, showing you what Terraform intends to do. It’s a read-only operation and doesn’t modify the actual infrastructure.terraform apply
: This command takes the execution plan and applies it, making the actual changes to your infrastructure. If you’ve saved a plan using the--out
option, you can provide it toterraform apply
to ensure that the exact plan is executed, like so:terraform apply myplan.tfplan
.
It’s generally a good practice to run terraform plan
before terraform apply
, especially in production environments. This two-step approach ensures that you’re aware of the changes Terraform will make, reducing the risk of unintended modifications.
In some scenarios, you might be tempted to run terraform apply
directly, as it can generate and show a plan before prompting for confirmation. However, separating the planning and applying stages provides a clearer workflow and better opportunity for review.
For those looking to understand more about how Terraform interacts with AWS, the article on creating an EC2 instance using Terraform offers a hands-on guide. Additionally, if you’re curious about how Terraform stacks up against AWS’s native IaC tool, our comparison of Terraform vs CloudFormation provides a detailed analysis.
Practical Usage of Terraform Plan
Terraform, as a leading Infrastructure as Code (IaC) tool, offers a myriad of commands and options to manage and provision cloud resources. Among these, the terraform plan
command stands out as a critical step in the Terraform workflow. Let’s dive into its practical applications, exploring real-world examples and advanced use cases.
Terraform Plan Example
Imagine you’re tasked with setting up an AWS S3 bucket to store application logs. Here’s a step-by-step guide on how to use terraform plan
in this scenario:
- Terraform Configuration: Start by writing a basic Terraform configuration for an S3 bucket:
provider "aws" { region = "us-west-1" } resource "aws_s3_bucket" "app_logs" { bucket = "my-app-logs" acl = "private" }
- Initialize Terraform: Before running any Terraform command, you need to initialize your working directory:
terraform init
- Run Terraform Plan: Execute the
terraform plan
command to see the proposed changes:
terraform plan
Upon execution, you’ll see an output detailing the actions Terraform intends to take. In this case, it will indicate the creation of a new S3 bucket.
- Interpreting the Output: The
terraform plan output
will show a+
sign next to theaws_s3_bucket.app_logs
, indicating that this resource will be created. Always review this output carefully to ensure the changes align with your intentions.
Terraform Plan Out and File Management
The terraform plan
command offers the ability to save its output for later use, especially when you want to review or share the plan before applying the changes.
- Using
terraform plan --out
: This option allows you to save the plan to a file:
terraform plan --out=myplan.tfplan
This creates a myplan.tfplan
file which contains the execution plan.
- Applying a Saved Plan: If you’re satisfied with the plan, you can apply it directly using:
terraform apply "myplan.tfplan"
This ensures that the exact changes you reviewed are the ones being applied.
- Example of
terraform plan out
: Let’s say you’re working in a team environment, and before any infrastructure change, a code review is required. By using theterraform plan --out
option, you can generate a plan, share the.tfplan
file with your team for review, and once approved, apply the exact changes.
Advanced Usage
Terraform offers advanced options to fine-tune the planning phase:
- Using
terraform target plan
: Sometimes, you might want to focus on specific resources rather than the entire infrastructure. Theterraform target
option allows you to do just that:
terraform plan -target=aws_s3_bucket.app_logs
This will generate a plan only for the specified S3 bucket, leaving other resources untouched.
- Understanding
terraform diff
: Whileterraform diff
isn’t a direct command, the concept of seeing a “difference” is inherent in theterraform plan
command. It shows you the difference between your current infrastructure state and the proposed changes in your configuration. This “diff” is crucial for understanding the impact of your changes.
In conclusion, the terraform plan
command is more than just a preview mechanism. It’s a powerful tool that, when used effectively, can ensure safe, predictable, and efficient infrastructure management. For those keen on diving deeper into Terraform’s capabilities, especially in an AWS context, our guide on creating an EC2 instance using Terraform offers a hands-on approach.
Common Mistakes to Avoid with Terraform Plan
When working with terraform plan
, it’s essential to be aware of potential pitfalls that can disrupt your infrastructure management. The following table outlines ten common mistakes developers often make and provides guidance on how to sidestep them:
Mistake | Description | How to Avoid |
---|---|---|
1. Neglecting to Run terraform plan | Skipping the terraform plan step and directly running terraform apply can lead to unintended changes. | Always run terraform plan before terraform apply to preview changes. |
2. Ignoring Plan Output | Overlooking the details of the plan output can result in undesired modifications. | Always review the terraform plan output carefully before applying. |
3. Overusing -target Option | Overusing -target can lead to configuration drift. | Use -target sparingly and apply the entire plan regularly. |
4. Not Versioning Terraform Configurations | Failing to use version control can lead to inconsistencies. | Use a version control system like Git for Terraform code. |
5. Hardcoding Sensitive Data | Embedding sensitive information in configurations is risky. | Use Terraform variables, secrets management tools, or environment variables. |
6. Not Setting Up Backend State Locking | Concurrent Terraform operations can corrupt the state. | Implement state locking using backends like Amazon S3 with DynamoDB. |
7. Not Using Workspaces | Using the default workspace for different environments can lead to conflicts. | Use separate Terraform workspaces for different environments (e.g., dev, prod). |
8. Not Pinning Provider Versions | Using different provider versions can lead to unexpected behavior. | Always pin to specific provider versions in Terraform configurations. |
9. Not Handling Dependencies Explicitly | Implicit dependencies can lead to race conditions. | Use depends_on to explicitly set resource dependencies. |
10. Not Reviewing Deprecated Features | Using deprecated features can break configurations in future versions. | Regularly review Terraform and provider documentation for deprecations and update accordingly. |
By understanding these common mistakes and their solutions, you can ensure a more efficient and error-free Terraform experience while maintaining the integrity of your infrastructure.
Terraform Plan Best Practices
Using the terraform plan
command effectively is an essential aspect of infrastructure management. Here are 10 best practices to help guide your Terraform usage and ensure smoother deployments.
Best Practice | Description |
---|---|
Always Run terraform plan Before terraform apply | Before making any changes to your infrastructure, always preview them using terraform plan . This ensures you’re aware of the changes Terraform intends to make, preventing unintended modifications. |
Use Version Control | Store your Terraform configurations in a version control system (like Git). This allows you to track changes, collaborate with others, and roll back if necessary. |
Modularize Configurations | Break down Terraform configurations into smaller, reusable modules. This makes the output of terraform plan more manageable and easier to understand. |
Secure Sensitive Data | Never hard-code sensitive data like passwords or API keys. Use Terraform variables or secrets management tools to handle them securely. |
Use -out Option | Use the -out option to save the terraform plan output to a file. This ensures that terraform apply uses the exact plan, preventing drift between plan and apply stages. |
Regularly Update Provider Versions | Ensure you’re using updated providers to benefit from the latest features and security patches. However, always test changes in a non-production environment first. |
Implement Workspaces | Use Terraform workspaces to manage multiple environments (like staging, production) to segregate and manage resources effectively. |
Review Plan Outputs Collaboratively | In a team setting, review terraform plan outputs collaboratively. This collective oversight can catch potential issues before they’re applied. |
Limit Scope with -target Sparingly | While the -target option can be useful to limit the scope of changes, use it sparingly. Over-reliance can lead to configuration drift and inconsistencies. |
Educate and Document | Ensure that all team members understand the Terraform workflow and the significance of terraform plan . Document conventions, workflows, and any custom configurations for clarity. |
Remember, while these best practices provide a solid foundation, always tailor them to your organization’s specific needs and infrastructure requirements.
Additional Terraform Commands and Concepts
Terraform, as a cornerstone in the Infrastructure as Code (IaC) paradigm, offers a suite of commands that allow developers and operations teams to manage and provision cloud infrastructure seamlessly. Let’s delve deeper into some of these commands and understand their significance in the Terraform lifecycle.
Terraform Init and Apply
Terraform’s workflow is designed to be both intuitive and systematic. Two of the most fundamental commands in this workflow are terraform init
and terraform apply
.
- Understanding
terraform init
:- The
terraform init
command is used to initialize a working directory containing Terraform configuration files. - It’s the first command you should run after writing a new Terraform configuration or cloning an existing one from version control.
- This command prepares the working directory for other operations, downloads the necessary provider plugins, and sets up the backend for storing the state.
- The
- The Relationship Between Commands:
- The sequence of commands typically follows the pattern of
terraform init
, thenterraform plan
, and finallyterraform apply
. - After initializing with
terraform init
, you useterraform plan
to preview changes, as we discussed earlier. - Post this,
terraform apply
is used to apply the desired changes and provision the infrastructure. It’s crucial to understand thatterraform apply
will make actual changes to your infrastructure, so always use it judiciously.
- The sequence of commands typically follows the pattern of
Terraform Code Example
To better understand how Terraform commands interact with configuration files, let’s consider a simple example:
provider "aws" { region = "us-west-1" } resource "aws_s3_bucket" "demo_bucket" { bucket = "my-demo-bucket" acl = "private" }
In this configuration, we’re defining an AWS provider and specifying an S3 bucket resource. After writing this configuration:
- Run
terraform init
to initialize the directory. - Execute
terraform plan
to preview the changes. - If everything looks good, run
terraform apply
to create the S3 bucket.
This example showcases the basic syntax and interaction of Terraform commands with the configuration. For more complex configurations, the principles remain the same, but the interactions can become more intricate.
Terraform Apply Options
While terraform apply
is straightforward in its basic usage, it comes with a variety of options to fine-tune its behavior:
- Targeted Apply: Using the
-target
option, you can specify particular resources to apply changes to, leaving others untouched. This is especially useful in large configurations where you want to modify a specific resource. For instance:terraform apply -target=aws_s3_bucket.demo_bucket
- Auto-approve: By default,
terraform apply
prompts for confirmation before making changes. If you’re confident about the changes, you can bypass this prompt using the-auto-approve
flag. However, use this with caution, especially in production environments. - Differences from
terraform plan
: While both commands can show the changes Terraform intends to make,terraform apply
goes a step further by actually executing those changes. It’s always recommended to runterraform plan
beforeterraform apply
to ensure you’re aware of the impending modifications.
Conclusion
The terraform plan
command, while pivotal, is just one piece of the Terraform puzzle. Understanding the broader ecosystem of Terraform commands, from initialization with terraform init
to actual infrastructure provisioning with terraform apply
, is crucial for effective IaC practices. As you delve deeper into Terraform, always prioritize understanding and safety over speed, ensuring that your infrastructure changes are both intentional and beneficial.
Frequently Asked Questions (FAQs) about Terraform Plan
1. What is terraform plan
used for?
terraform plan
is a command in Terraform that allows users to see which actions Terraform will execute prior to making any changes, ensuring that the set of changes matches the user’s expectations.
2. How does terraform plan
differ from terraform apply
?
While terraform plan
provides a preview of what changes will be made to your infrastructure, terraform apply
actually executes those changes. It’s recommended to always run terraform plan
before terraform apply
to verify the changes.
3. Can I save the output of terraform plan
for later use?
Yes, you can save the output using the --out
parameter, like so: terraform plan --out=plan-output
. This saved plan can then be applied later with terraform apply plan-output
.
4. How do I target a specific resource with terraform plan
?
You can target a specific resource using the -target
flag followed by the resource name, e.g., terraform plan -target=aws_instance.my_instance
.
5. What does the terraform plan -destroy
command do?
This command shows you a plan of resources that will be destroyed. It’s a way to see what would happen if you were to destroy your infrastructure without actually making any changes.
6. How can I use variables with terraform plan
?
You can use the -var
flag to set variables. For example: terraform plan -var "instance_type=t2.micro"
. Alternatively, you can use -var-file
to specify a file containing variable definitions.
7. Why am I seeing “No changes. Infrastructure is up-to-date” when running terraform plan
?
This message indicates that the current state of your infrastructure matches your Terraform configuration. No changes are needed.
8. How can I see a detailed plan output?
By default, terraform plan
provides a detailed output. If you want to see even more details, you can use the -detailed-exitcode
flag.
9. Can I use terraform plan
without an internet connection?
While you can run the command, it may fail if Terraform needs to fetch provider plugins or if your configuration references external modules or resources that require an internet connection.
10. How do I interpret the +
, -
, and ~
symbols in the plan output?
The symbols represent the actions Terraform will take:
+
: Resource will be created.-
: Resource will be destroyed.~
: Resource will be updated in-place.
By understanding these FAQs, you’ll be better equipped to navigate the intricacies of terraform plan
and its role in infrastructure management.
Additional Resources
For those eager to expand their Terraform knowledge, the official Terraform documentation is an invaluable resource. Additionally, our in-depth guides on setting up Terraform and creating an EC2 instance using Terraform, and setting up an EKS Cluster using Terraform EKS module provide hands-on insights into practical Terraform applications.