Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID 'aws_subnet.archer-public-1.id' does not exist
status code: 400, request id: 26b4f710-e968-484d-a17a-6faa5a9d15d5
The above subnet_id assignment doesn’t work… removing the double-quotes doesn’t either… So how can I dynamically deploy that EC2 in each public Subnet defined above?
Given that these two subnets are following a systematic pattern, I agree that this seems like a good candidate for for_each.
For the sake of completeness, there’s another answer that can be used in (rarer) situations where the objects in question are not configured systematically but you need to select one dynamically anyway:
The for_each mechanism is a way to construct a lookup table like this automatically by systematically creating many resource instances from a single resource block, but it’s possible to construct such a lookup table manually in rarer situations where the objects themselves are not configured systematically.
Both are fantastic examples above, thanks very much. One other question: what’s the advantage of using locals{} construct instead of var {} construct? Just wondering, don’t see any distinction between them.
A variable block defines an input variable that should be set by the caller of your module, similar in principle to a parameter to a function in a general-purpose programming language.
A locals block, on the other hand, defines a reusable value that is internal to the module where you define it, similar to a local variable in a general-purpose programming language.
When your values are constants anyway it is in principle possible to use a variable block with a default set as equivalent to an entry in a locals block. However, for the example I shared in my previous comment a locals block would be required because the local value is derived from other objects in the same module, whereas input variables can refer (indirectly) only to objects in the parent module.
(If you are currently working only in a single-module configuration without any module blocks then this distinction can feel rather arbitrary indeed, but for a root module a variable block is intended to have its value set by -var or -var-file arguments on the command line, whereas a locals entry is always defined only in the configuration.)