I have the following structure which is produced by yamldecode(file("myfile.yaml")) and I use Terraform.
[
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
Initial yaml looks like:
test:
- name: "A"
number: '1'
description: "Bla"
- name: "B"
number: '2'
description: "Bla"
I need to get values from all maps in a list of tuples. Please advice
Expected result:
("A", 1, "Bla"), ("B", 2, "Bla")
CodePudding user response:
You can load YAML file as dict using pyyaml library and itterate over data.
Install pyyaml using pip install pyyaml
import yaml
with open("test.yaml", "r") as stream:
data_list_dict = yaml.safe_load(stream)
output_list = []
for data_dict in data_list_dict['test']:
output_list.append(tuple(data_dict.values()))
print(output_list)
Output:
[('1', 'Bla', 'A'), ('2', 'Bla', 'B')]
Or
import yaml
with open("test.yaml", "r") as stream:
data_list_dict = yaml.safe_load(stream)
output_list = [tuple(data_dict.values()) for data_dict in data_list_dict['test']]
print(output_list)
CodePudding user response:
If order is important you can do the following:
locals {
test = [
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
list_of_lists = [for a_map in local.test:
[a_map["name"], a_map["number"], a_map["description"]]]
}
which gives:
[
[
"A",
"1",
"Bla",
],
[
"B",
"2",
"Bla",
],
]
CodePudding user response:
From your question it's not clear whether you're asking how to solve this problem in the Terraform language or in Python -- you only mentioned Terraform in the question body, but you tagged it "python" and used Python syntax to show the tuples.
Others have already shown how to do this in Python, so just in case you were asking about Terraform the following is a Terraform equivalent:
locals {
input = [
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
list_of_tuples = tolist([
for e in local.input : [e.name, e.number, e.description]
])
}
A tuple in Terraform is a kind of sequence type where the length is fixed and each element can have its own specified type. It's the sequence equivalent of an object, whereas a list corresponds with a map.
When evaluating the list_of_tuples
expression above, Terraform will first construct a tuple of tuples (because []
brackets construct tuples) and then convert the outer tuple to be a list with tolist
. The final type of list_of_tuples
would therefore be the following, if written in Terraform's type constraint syntax:
list(tuple([string, number, string]))