In the below scenario, could someone confirm what the terraform refresh & apply work?
Initially a user has created a Security Group by giving value to the "name" property as "sg-123" as shown in below code. Then the user ran terraform apply command which created a Security Group in AWS Cloud.
resource "aws_security_group" "mySgGroup" { name = "sg-123" . . . . . }
Then the user came back to the same .tf file and changed the value of name property from sg-123 to sg-456 as shown in below code. Then the user ran terraform apply command.
resource "aws_security_group" "mySgGroup" { name = "sg-456" . . . . . }
Now what is going to happen in the above scenario? Will terraform just modifies the name of the existing Security Group in the Cloud Infrastructure to sg-456 (or) will it create a brand new Security Group with name "sg-456"? I think the Terraform will just rename the name of the existing Security Group instead of creating a brand new Security Group. But my question is- how the Terraform determine that it should just modify the name of the existing Security Group? Why Terraform will not create a new Security Group with new name and delete the existing Security Group with name: sg-123?
Please help with this question.
When you update the name
attribute of an aws_security_group
in Terraform from "sg-123" to "sg-456" and run terraform apply
, here's what happens under the hood, due to AWS and Terraform's behavior:
Immutable name
Attribute: In AWS, the name of a standard security group is immutable once the group is created. This states that you cannot update the name of an existing security group directly. If you need a security group with a different name, a new security group needs to be created.
Terraform's Actions: Given this limitation, Terraform's approach when you change the name
property of an aws_security_group
resource and apply your configuration is twofold:
State Management: Terraform manages your infrastructure's state through a state file, tracking the IDs and attributes of managed resources. When you modify your Terraform configuration and apply these changes, Terraform compares the desired state (your configuration files) against the actual state (information in the state file and the real cloud infrastructure). For changes that require a resource to be recreated (like changing an immutable attribute), Terraform decides on a strategy, typically "create before destroy" or "destroy before create," based on the resource and context. For an aws_security_group
's name
change, Terraform opts for creating the new group before destroying the old one, if possible, ensuring that your infrastructure aligns with your specified configuration.
This behavior ensures your infrastructure is always in sync with your Terraform configurations, albeit with the necessary steps to respect cloud provider constraints like immutability of certain resource attributes.