Documentation for version v0.44.0 is no longer actively maintained. The version you are currently viewing is a static snapshot. For up-to-date documentation, see the latest version.
Structs
Overview ¶
Structs are well-defined data objects, comprised of key/value pairs known as “attributes”. They are a way to store and refer to data of a known structure.
The most commonly used struct
is data.values
, supplied by the @ytt:data
module. For example, a data values defined by:
#@data/values
---
db_conn:
host: acme.example.com
is automatically processed into a struct
(named values
): the keys in the @data/values
file are defined one-for-one as attributes on the struct
.
Those attribues can be referenced by name:
#@ load("@ytt:data", "data")
---
persistence:
db_url: #@ data.values.db_conn.host
Attributes ¶
Attributes are a key/value pair, where the key is a string
and the value can be of any type.
Attributes can be referenced:
- by field (using “dot notation”)
db_url: #@ data.values.db_conn.host
- by string (using “index notation”) (as of v0.31.0):useful when the name of the attribute is not known statically.
db_url: #@ data.values["db_conn"]["host"]
Referencing an attribute that is not defined on the struct
results in an error:
db_url: #@ data.values.bd_conn # <== struct has no .bd_conn field or method
db_host: #@ data.values["db_conn"]["hast"] # <== key "hast" not in struct
Built-in Functions ¶
The following built-ins can be useful with struct
values:
dir()
enumerates all its attributes.load("@ytt:struct", "struct") foo = struct.encode({"a": 1, "b": 2, "c": 3}) keys = dir(foo) # <== ["a", "b", "c"]
getattr()
can be used to select an attribute.#@ for vpc_config in getattr(getattr(data.values.accounts, foundation_name), vpc_name): ... #@ end
- as of v0.31.0,
struct
s support index notation behaving identically, more succinctly/readably:#@ for vpc_config in data.values.accounts[foundation_name][vpc_name]: ... #@ end
- as of v0.31.0,
hasattr()
reports whether a value has a specific attribute# `value` is a struct that _might_ have a field, "additional_ports" def ports(value): if hasattr(value, "additional_ports"): ... end
Creating structs ¶
struct
instances can be made using the @ytt:struct
module.
See ytt Library: struct module for details.
(Help improve our docs: edit this page on GitHub)