I have a simple AWS deployment with a vpc, public subnet, route, and security group. Running terraform apply
will launch an AWS instance, and I have that instance configured to associate a public IP. After the instance has been created, I run terraform plan
and it properly says everything is up to date. No problems so far.
We have a management node that will shut down that instance if it's unused for a period of time as a cost saving measure.
Here's the problem: Once that instance is shut down, when I run terraform plan
, the aws provider sees everything configured properly, but since the public IP has been released, the value for associate_public_ip_address no longer matches what is configured in the terraform configs, so terraform wants to delete and recreate that instance:
associate_public_ip_address: "false" => "true" (forces new resource)
Is there a way to get terraform to ignore just that one parameter?
This question is marginally related to https://github.com/hashicorp/terraform/issues/7262. But in my case, I don't want to set the expected state, I just want to be able to tell terraform to ignore that one parameter because it's ok that it's not associated right now, as long as it's configured to be associated when it starts.
(This occurred to me while writing this question: I have not experimented with configuring the subnet to automatically associate public ip for instances launched in it. Conceivably, by making the subnet automatically do it, and removing the option from "aws_instance", I might be able to make terraform not pay attention to that value...but I doubt it.)
You can use a lifecycle block to ignore certain attribute changes.
Using this, the resource is initially created using the provided value for that attribute. Upon a subsequent plan, apply, etc., Terraform will ignore changes to that attribute.
If we add an ignore for associate_public_ip_address
in the lifecycle block, a stopped instance will no longer trigger a new resource.
Note that if you alter any other parameter that would require a new instance, the stopped one will be terminated and replaced.
Example based on the Terraform aws_instance example code :
provider "aws" {
region = "us-west-2"
}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical account ID
}
resource "aws_instance" "web" {
ami = "${data.aws_ami.ubuntu.id}"
instance_type = "t2.micro"
associate_public_ip_address = "true"
tags {
Name = "HelloWorld"
}
lifecycle {
ignore_changes = ["associate_public_ip_address"]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With