Terraform resources only force a new resource if there's no clear upgrade path when modifying a resource to match the new configuration. This is done at the provider level by setting the ForceNew: true
flag on the parameter.
An example is shown with the ami
parameter on the aws_instance
resource:
Schema: map[string]*schema.Schema{
"ami": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
This tells Terraform that if the ami
parameter is changed then it shouldn't attempt to perform an update but instead destroy the resource and create a new one.
You can override the destroy then create behaviour with the create_before_destroy
lifecycle configuration block:
resource "aws_instance" "example" {
# ...
lifecycle {
create_before_destroy = true
}
}
In the event you changed the ami
or some other parameter that can't be updated then Terraform would then create a new instance and then destroy the old one.
How you handle zero downtime upgrades of resources can be tricky and is largely determined on what the resource is and how you handle it. There's some more information about that in the official blog.
In your very specific use case with it being the security_groups
that has changed this is mentioned on the aws_instance
resource docs:
NOTE: If you are creating Instances in a VPC, use vpc_security_group_ids instead.
This is because Terraform's AWS provider and the EC2 API that Terraform is using is backwards compatible with old EC2 Classic AWS accounts that predate VPCs. With those accounts you could create instances outside of VPCs but you couldn't change the security groups of the instance after it was created. If you wanted to change ingress/egress for the instance you needed to work within the group(s) you had attached to the instance already. With VPC based instances AWS allowed users to modify instance security groups without replacing the instance and so exposed a different way of specifying this in the API.
If you move to using vpc_security_group_ids
instead of security_groups
then you will be able to modify these without replacing your instances.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…