what is lookup used for in terraform? - terraform

I am trying to understand what exactly the function "lookup" does in terraform code? does it find maps or lists? just confused how to use this lookup correctly.

The lookup documentation has the following to say about it:
lookup retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.
The normal way to look up a value from a map by key is to use the index syntax, like example["foo"], but that operation will return an error if there is no element with the key foo in the map example.
lookup is therefore similar to the index syntax except for the additional behavior of choosing a fallback value to use instead of an error if the key doesn't exist. lookup(example, "foo", "default") is the same as example["foo"] except that it will produce "default" rather than an error if there is no element with the key "foo".
More recent Terraform versions also have the try function which can serve as a perhaps easier to understand alternative to lookup, because it still uses the normal index syntax as part of the expression: try(example["foo"], "default") is similar to lookup(example, "foo", "default"), and will produce the same result as long as example is a map of strings.

Related

which one to use: if "key" not in dict VS if dict.get("key") is None #Python3

As Zen of Python says:
There should be one– and preferably only one –obvious way to do it.
I can't decide which one of the following lines is better:
ps.cfg is a python dict
if cfg.get("runner") is None:
if "runner" not in cfg:
Is one of them obviously better, or could we say that they are both OK?
It depends on what you want to achieve. If you want to make sure that an element at a certain key exists in that dictionary, i.e. something was inserted at that key, you should utilize capabilities that tell you exactly that. Like in your case:
if "runner" not in cfg:
If you really don't care if actually an element at a certain key exists in that dictionary and you just want to see if trying to retrieve an element of the dictionary will give you None as result, you can also work with the None check.
Just consider that by calling get('some_key') and checking the returned value against None this won't tell you if there is an element existing at key some_key. Because no one prevents you from inserting an element without a value (meaning the value None) into a dictionary at that very key.

How to get the last KEY from a map in groovy?

I am trying to get the last KEY from this map in groovy. However, it seems like groovy doesn't have a method for returning the last key in the map.
def person = [fname: "john", sname: "smith", age: 25]
I have tried person.lastKey() and person.lastEntry() but these methods seems to be specific for java only.
You can use person.keySet()[-1]​ or person.keySet().last()​
And to get whole entry use entrySet() instead of keySet()
See the Groovy demo online
lastKey is part of the SortedMap interface and the Groovy map literal gives you an LinkedHashMap, which is the explanation, why your attempts failed.
Maps (the interface SortedMap inherits from) are on their own not ordered or sorted. So what you are asking here, will only work for ordered (which the Groovy map literal will give you) or sorted maps, so make sure you have one of those or you will see random elements instead of what you perceive as last. If order is important consider using a list of key-value-tuples instead.

How to interpolate expressions in Terraform?

I'm trying to use the keys expression in Terraform to grab a list of keys (from a map variable) and assign it to a local variable. Here is the code snippet:
locals {
project_name_list = keys(${var.project_map})
}
However, I'm getting the following error:
Unknown token: 29:22 IDENT keys
Am I missing something here. Nowhere can I find an example of this expression. As bad as it is, even the official documentation does not help -https://www.terraform.io/docs/configuration/functions/keys.html
HashiCorp has really done a bad job of elaborating the nuances of Terraform for beginners on their website.
Terraform functions need to be wrapped in expression syntax to show that it's not a literal value: "${}"
So try this: project_name_list = "${keys(var.project_map)}"
The example in the documentation is written as though being run from the terraform command line, which already assumes the command is a HCL expression and doesn't require that syntax.
UPDATE
I said above that the expression syntax is to show that it's not a literal value. It's probably more accurate to speak of it as expression syntax vs. configuration syntax. Configuration syntax is the first level of interpolation, which forms the basic structure of your terraform file with resource blocks, data blocks, etc. The second interpolation level is expression syntax which is used to generate values used by your configuration.
Thinking of it in these terms makes better sense of the error message, Unknown token, because terraform is attempting to read it as a configuration key word.
I had compared it to a literal value because it's in the same position as where a literal value would be.

Add Dictionary Keys and Values to Redis List

I am trying to add the current dictionary to a Redis list using a dictionary comprehension and then to print out the first (aka current) keys and values of that list. I say current because this is a process I will be continuing with a while loop to have the list building over time, but I have to always access the first keys/values.
I am sure I am totally butchering this, but this is what I have:
adict = {"a":1,"b":2,"c":3}
{rserver.rpush("list",value) for value in adict}
print(float(rserver.lindex("list",0)))
I need to get a list of both keys and values back.
Help would be MUCH appreciated. Thanks!
I am not quite positive on what your redis-list should contain (please include your expected result in the question), but assuming it should at the end of inserts look something like this ["a:1", "b:1", "c:1"], you can achieve this with
adict = {"a":1,"b":2,"c":3}
for key,value in adict.items():
rserver.rpush("list", ":".join([key, value]))
print(float(rserver.lindex("list",0))) #>>> "a:1"
(as you have not included what interface rserver exactly is, it is a bit hard to guess on its exact behavior)

How to get fields of a Julia object

Given a Julia object of composite type, how can one determine its fields?
I know one solution if you're working in the REPL: First you figure out the type of the object via a call to typeof, then enter help mode (?), and then look up the type. Is there a more programmatic way to achieve the same thing?
For v0.7+
Use fieldnames(x), where x is a DataType. For example, use fieldnames(Date), instead of fieldnames(today()), or else use fieldnames(typeof(today())).
This returns Vector{Symbol} listing the field names in order.
If a field name is myfield, then to retrieve the values in that field use either getfield(x, :myfield), or the shortcut syntax x.myfield.
Another useful and related function to play around with is dump(x).
Before v0.7
Use fieldnames(x), where x is either an instance of the composite type you are interested in, or else a DataType. That is, fieldnames(today()) and fieldnames(Date) are equally valid and have the same output.
suppose the object is obj,
you can get all the information of its fields with following code snippet:
T = typeof(obj)
for (name, typ) in zip(fieldnames(T), T.types)
println("type of the fieldname $name is $typ")
end
Here, fieldnames(T) returns the vector of field names and T.types returns the corresponding vector of type of the fields.

Resources