79440656

Date: 2025-02-14 22:26:32
Score: 0.5
Natty:
Report link

I'd like to preface this by saying the top-voted (and only, so far) answer is inaccurate. See below. But first, my answer.


The keepers map solves the problem of controlling when a new value is generated.

When would you want to generate a new value? The first time you run obviously, but not usually thereafter. In other words, most people want a random value at creation time but also want it to remain stable across reruns. Terraform knows this and so sticks with the previously generated value by default.

But there are times when you do want this value to change. For example assume you've created a VM instance like your example as part of your app cluster. Logs are sent to a centralized log server which categorizes them by hostname. A new version of your app is ready for deployment, so you create a new image and redeploy the instance. At this point, if you did not use keepers, then the instance would be recreated with the same name with the old random value. If you did use keepers, then a new name would be generated. The new name would allow log viewers to differentiate between the two instances.

I would not describe this as the best way to solve this problem, but keepers is certainly one way to address it.


@Tim Malone's answer describes keepers as seed values for RNG. This is misleading because there is no way to obtain the generated value from the keepers value. Additionally, the comment about "ensur[ing] [...] your random string is deterministic" is also very hand-wavy. Pseudorandom number generators, which the random provider relies on, are by definition deterministic. Being deterministic has nothing to do with the behavior of keepers.

The answer also makes the claim:

If you had a random string without any keepers, and you were using it in your server's Name tag as in this example, then Terraform would generate a plan to change the Name (containing a new random ID) every time you ran terraform plan/terraform apply.

Also very misleading. Once a random value has been generated and applied, further plans and applies will not change this value. The only time the random string changes is if

  1. You run and rerun terraform plan without ever applying. Then, since there is no prior resource state for Terraform to plan against, it will always generate a new value.

  2. The random resource is wiped from state, whether by running terraform destroy or manually manipulating the state file.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @Tim
  • Low reputation (0.5):
Posted by: Stanley Yu