Search code examples
terraformaws-cliterraform-provider-awsssm

How to create/overwrite a parameter in AWS Parameter Store only if it does not exist?


I am using terraform to create a parameter in the AWS Parameter Store.

resource "aws_ssm_parameter" "username" {
  name      = "username"
  type      = "SecureString"
  value     = "to_be_defined"
  overwrite = false
}

provider "aws" {
  version = "~> 1.53"
}

When I run terraform apply for the first time, if the parameter does not exist terraform creates the parameter. However, if I run it again (usually with a different value) I get the error

ParameterAlreadyExists: The parameter already exists. To overwrite this value, set the overwrite option in the request to true

If I understand correctly, this is due to the behaviour of AWS Cli (not specific to the provider).

The current behavior for overwrite = false is

If the parameter does not exist, create it
If the parameter exists, throw exception

What I want to achieve is

If the parameter does not exist, create it
If the parameter exists, do nothing

I did not find a way in AWS CLI documentation to achieve the desired behavior.

I would like to know if there is any way to achieve the desired behaviour using terraform (or directly via AWS CLI)


Solution

  • I agree with @ydaetskcoR that you should maintain the value with terraform state as well.

    But if you insist to ignore the value to be updated if the SSM key is exist, you can use lifecycle ignore_changes(https://www.terraform.io/docs/configuration/resources.html#ignore_changes)

    So in your case, you can update the code to

    resource "aws_ssm_parameter" "username" {
      name      = "username"
      type      = "SecureString"
      value     = "to_be_defined"
      overwrite = false
    
      lifecycle {
        ignore_changes = [
          value,
        ]
      }
    }
    

    overwrite - (Optional) Overwrite an existing parameter. If not specified, will default to false if the resource has not been created by terraform to avoid overwrite of existing resource and will default to true otherwise (terraform lifecycle rules should then be used to manage the update behavior).

    By the way, it is not good design to manage SecureString SSM key/value with terraform, because its tfstate file is not encrypted.