roundingterraform

Does terraform support math rounding?


Is it possible to round an integer value in terraform string interpolations?


Solution

  • It's a bit of a hack and doesn't use terraform string interpolations but..

    You can do this with the external data source (https://www.terraform.io/docs/providers/external/data_source.html) by delegating it to another program. The example I've included uses bash and jq. However you could probably achieve this without jq.

    Terraform:

    data external "rounder" {
    
      program = ["bash", "${path.module}/round.sh"]
      query {
        value="1.3"
      }
    }
    
    output "round" {
      value = "${data.external.rounder.result.value}"
    }
    

    round.sh:

    #!/usr/bin/env bash
    
    # Exit if any of the intermediate steps fail
    set -e
    
    eval "$(jq -r '@sh "VALUE=\(.value)"')"
    
    ROUNDED=$(printf "%.0f\n" $VALUE)
    
    jq -n --arg rounded "$ROUNDED" '{"value":$rounded}'
    

    Here is an issue about supporting "round" in terraform: https://github.com/hashicorp/terraform/issues/16251