'Terraform AlreadyExistsException: An alias with the name arn:aws:kms:XXXXX:XXXXXXXXX:alias/myalias already exists

When running terraform apply I get the following error

Terraform AlreadyExistsException: An alias with the name arn:aws:kms:XXXXX:XXXXXXXXX:alias/myalias already exists

I can confirm that the resource (the KMS-Key-Alias) exists on AWS. How can this happen? How can I resolve this?



Solution 1:[1]

The problem is that the resource was created, but the Terraform state does not contain this resource.

How this can happen

  • the resource was created manually in AWS
  • the resource was created using Terraform but the state does not contain the information. This might happen because
    • the state file was deleted manually
    • the state is in PENDING DELETION(not removed totally, but still exists with same name/path/arn)
    • there is more than one developer, but the state file is not shared (this post describes in detail how to set this up)
    • the state file was not updated correctly (it might have been overwritten by an older version, it might for some reason have failed to be updated despite the correct applied changes from Terraform,...)
  • a resource with this name appears twice in your Terraform code

Solution

You can import the resource in your Terraform state using something like

terraform import aws_kms_alias.a alias/myalias

To figure out the correct command look up the Terraform docu for your resouce of interest. E.g. here is the docu for Terraform kms_alias. In the bottom it tells you how to import the resource (some resources can only be imported by id, some by name).

Alternatively, if you are dealing with many resources and deleting them is acceptable (i.e. you would not want to delete a database, if you still need the data, you would not want to delete a KMS-Key, if you still need it for decription (an alias would be acceptable to be deleted, but make sure you keep the information to which KMS-Key it is linked)), you can also just delete the resources and then let Terraform recreate them.

If the issue appears repeatedly, try to find out why this happens (see "how this can happen" above) and fix this. This post provides some more context about how state is managed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gautam Mehta