2

I stumbled upon a general problem in Terraform. For example, I have a resource such as aws_autoscaling_group which has a desired_capacity which can be scaled up or down based on CloudWatch alarms.

However, when running terraform apply the Terraform state file does not know about these changes and tries to set the capacity back to the initial value defined in the state.

I thought about a solution and came up with this:

# initialise terraform, ideally against a remote state in S3
terraform init
# remove resource from state
terraform state rm "aws_autoscaling_group.main"
# import resource from remote so it reflects the current capacity
terraform import "aws_autoscaling_group.main" "my-autoscaling-group"

However, when running terraform plan afterwards it does not reflect the imported changes:

~ aws_autoscaling_group.main
      desired_capacity:          "3" => "2"
      force_delete:              "" => "true"
      metrics_granularity:       "" => "1Minute"
      wait_for_capacity_timeout: "" => "10m"
Plan: 0 to add, 1 to change, 0 to destroy.

Also, this is very error prone: for example, after importing the resource the remote resource might change (e.g. an alarm triggers directly after I have imported the resource) so it will be out of sync again.

Is this intended design and if so, what can I do about it?

1 Answer 1

4

Yes this is how terraform works. It looks at its state file for what it knows should be the state of your infrastructure and then it queries the API for what it currently is and basically does a diff and tells you this is what changed and I'm going to change this to make it the state you told me. Of course you are using ASGs that can change dynamically.

So terraform as lifecycle options you can use

https://www.terraform.io/docs/configuration/resources.html#lifecycle

So we can use those to tell terraform that you want to ignore any changes to certain options in a resource

So in your case

lifecycle {
    ignore_changes = ["desired_capacity"]
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .