terraform‐lifecycle - robjcook/sync GitHub Wiki
To modify an AWS EC2 instance using Terraform without destroying and recreating it, you need to ensure that the changes you make are in-place updates rather than destructive changes. Here are some steps and considerations to help you achieve this:
-
State Management: Ensure you are using the latest state of your infrastructure.
terraform init terraform refresh
-
Plan Changes: Always use
terraform plan
to review the changes before applying them.terraform plan
-
Modify Attributes: Make sure the attributes you are changing do not require the instance to be destroyed and recreated. For example, changing the instance type (
instance_type
) will require a replacement, but changing thetags
orsecurity_groups
might not. -
Use the
create_before_destroy
andprevent_destroy
Lifecycle Rules: These rules can help control how Terraform handles resources.resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" lifecycle { prevent_destroy = true } tags = { Name = "example-instance" } }
-
Ensure No Conflicting Changes: Avoid changes that inherently require the instance to be recreated, such as switching subnets or instance types.
-
Testing in a Separate Environment: Before making changes in production, test them in a staging environment to ensure they don't lead to unintended recreations.
Example
Here's an example of a Terraform configuration for an EC2 instance with tags and a security group:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "example-instance"
}
lifecycle {
prevent_destroy = true
}
security_groups = ["default"]
}
Applying Changes
-
Initialize Terraform:
terraform init
-
Review the Plan:
terraform plan
-
Apply the Plan:
terraform apply
Making Non-Destructive Changes
For example, to update the tags or security groups:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "updated-example-instance"
}
lifecycle {
prevent_destroy = true
}
security_groups = ["updated-security-group"]
}
Again, use terraform plan
to ensure the changes do not lead to destruction and recreation of the instance.
Summary
By carefully managing the attributes you change and using lifecycle rules, you can update your AWS EC2 instances with Terraform without destroying and recreating them. Always use terraform plan
to verify the impact of your changes before applying them.