Search code examples
terraformmappingterraform-provider-gcphashicorp

Terraform metadata condition


I have two environments. I'm trying to write a condition in the ssh metadata block to add a ssh key depending on the environment.
For example: If env-1, add ssh1 key, if env-2 add ssh-2 key. Trying with map, but can not do this correctly. How to do it better?

metadata = {
    count = var.ENV_TYPE != "ENV-1" ? 1 : 0
    ssh-keys = "centos:ssh-rsa AAAAsfdsds..."
    instance_role = var.GCP_CUSTOM_METADATA
    app_env_monitoring = var.GCP_CUSTOM_METADATA_MONITORING
}
metadata = {
        count = var.ENV_TYPE = "ENV-1" ? 1 : 0
        ssh-keys = "centos:ssh-rsa BBBBsfdsds..."
        instance_role = var.GCP_CUSTOM_METADATA
        app_env_monitoring = var.GCP_CUSTOM_METADATA_MONITORING
    }

Solution

  • You can probably achieve what you want by using a ternary operator:

    metadata = {
        ssh-keys = var.ENV_TYPE == "ENV-1" ? "centos:ssh-rsa BBBBsfdsds..." : "centos:ssh-rsa AAAAsfdsds..."
        instance_role = var.GCP_CUSTOM_METADATA
        app_env_monitoring = var.GCP_CUSTOM_METADATA_MONITORING
    }
    

    Additionally, I would strongly suggest moving the SSH key at least into a variable. In that case, the above code would look cleaner:

    metadata = {
        ssh-keys           = var.ENV_TYPE == "ENV-1" ? var.ssh_key_env1 : var.ssh_key_env2
        instance_role      = var.GCP_CUSTOM_METADATA
        app_env_monitoring = var.GCP_CUSTOM_METADATA_MONITORING
    }