AWS on Terraform - How to avoid 'forces new resource'

前端 未结 1 831
误落风尘
误落风尘 2020-12-11 06:15

I\'m using Terraform to launch my cloud environments.

It seems that even minor configuration change affects many of the resources behind the scenes.

For exam

相关标签:
1条回答
  • 2020-12-11 06:58

    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.

    0 讨论(0)
提交回复
热议问题