How-to setup a HA/DR database in AWS? [9 - Generate a random value]
In this part (and the last part of the serie), we will see how to generate a random value.
Really useful to generate unique names for a snapshot for example, you will see that there are multiple definitions available, depending on what you need.
Random Id
resource "random_id" "rdm_id" { byte_length = 8}
Declared as this, it will generate for you an 8 bytes long id which can be retrieve in :
- base64 : random_id.rdm_id.id => MDc3NDA2OGE5YTNhMjc5MQ==
- decimal digits : random_id.rdm_id.dec => 537061447926687633
- hexadecimal digits : random_id.rdm_id.hex => 0774068a9a3a2791
But it you are doing it like this, the random_id will always be the same!
So to be sure the value change when something append, you can use the keepers parameter.
With this, you can say "if the parameter X and Y change, so the random value must change too".
In this example the random value will change each time the arn of the global cluster example will change.
resource "random_id" "rdm_id" { byte_length = 8 keepers = { first = aws_rds_global_cluster.example.arn }}
And if you want this value to change each time the script is executed, use a timestamp :
resource "random_id" "rdm_id" { byte_length = 8 keepers = { first = timestamp() }}
Other random possibilities
Following the same pattern, Terraform let you to generate random
- integer
resource "random_integer" "priority" { min = 1 max = 50000}
- password
resource "random_password" "password" { length = 16 special = true override_special = "_%@"}
- string
resource "random_string" "random" { length = 16 special = true override_special = "/@$"}
- UUID
resource "random_uuid" "test" {}
- A shuffled sublist
resource "random_shuffle" "az" { input = ["us-west-1a", "us-west-1c", "us-west-1d", "us-west-1e"] result_count = 2}
Here you will retrieve a sublist of the input list, with only 2 items.
Links
- Terraform doc random_id : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/id
- Terraform doc random_integer : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/integer
- Terraform doc random_password : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/password
- Terraform doc random_shuffle : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/shuffle
- Terraform doc random_string : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/string
- Terraform doc random_uuid : https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/uuid
I hope it will help you and you liked this serie!
Original Link: https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-9-generate-a-random-value-5g8a
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To