0
votes

Originally I had Terraform script which is creating CloudWatch log group.

resource "aws_cloudwatch_log_group" "main_server_log_group" {
  name              = "server_name"
  retention_in_days = 60
}

I applied it, later I moved it to dedicated module and renamed

resource "aws_cloudwatch_log_group" "server_log_group" {
  name              = "${var.server_name}"
  retention_in_days = 60
}

and using this module in main.tf

module "main_server" {
  source = "./modules/server"
  server_name = "${local.main_server_name}"
}

Now Terrafrom apply is destroying original CloudWatch group and creating new one.

module.main_server.aws_cloudwatch_log_group.main_server_log_group[0]: Creating...
aws_cloudwatch_log_group.main_server_log_group: Destroying... [id=xxxx]

I assume it is because name of Terraform resource has changed, isn't it? This is not expected. Name of CW group has not changed.

Any workaround to keep existing resources while refactoring Terraform code?

1

1 Answers

1
votes

Found solution, apparently it is possible to move resource to a module. State file require an update - https://www.terraform.io/docs/commands/state/mv.html

Update Move state was not working for me. But remove state and import state did the trick.

terraform state rm 'my_resource'
terraform import ...