Reputation: 69
Is it possible to round an integer value in terraform string interpolations?
Upvotes: 3
Views: 2758
Reputation: 578
You can round using floor (or ceil):
$ terraform console
> floor(4.4999 + 0.5)
4
> floor(4.5 + 0.5)
5
Upvotes: 1
Reputation: 1393
There is another native terraform way of doing this, not sure if it's new but I just found it and thought I should add it here for reference:
format("%.2f", data.aws_ec2_spot_price.emr.spot_price)
This will return my spot_price as a 2 digit number, this uses the width operator in the format function
A width modifier can be included with an optional decimal number immediately preceding the verb letter, to specify how many characters will be used to represent the value. Precision can be specified after the (optional) width with a period (.) followed by a decimal number. If width or precision are omitted then default values are selected based on the given value. For example:
Sequence Result
- %f Default width and precision.
- %9f Width 9, default precision.
- %.2f Default width, precision 2.
- %9.2f Width 9, precision 2.
Upvotes: 2
Reputation: 1582
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
Upvotes: 2