How can we dynamically generate a list of map in terraform? - dynamic

I have a list of rules which i want to generate at runtime as it depends on availability_domains where availability_domains is a list
availability_domains = [XX,YY,ZZ]
locals {
rules = [{
ad = XX
name = "service-XX",
hostclass = "hostClassName",
instance_shape = "VM.Standard2.1"
...
},{
ad = YY
name = "service-YY",
hostclass = "hostClassName",
instance_shape = "VM.Standard2.1"
...
}, ...]
}
Here, all the values apart from ad and name are constant. And I need rule for each availability_domains.
I read about null_resource where triggers can be used to generate this but i don't want to use a hack here.
Is there any other way to generate this list of map?
Thanks for help.

First, you need to fix the availability_domains list to be a list of strings.
availability_domains = ["XX","YY","ZZ"]
Assuming availability_domains is a local you just run a forloop on it.
locals {
availability_domains = ["XX","YY","ZZ"]
all_rules = {"rules" = [for val in local.availability_domains : { "ad" : val, "name" : "service-${val}" , "hostclass" : "hostClassName", "instance_shape" : "VM.Standard2.1"}] }
}
or if you dont want the top level name to the array then this should work as well
locals {
availability_domains = ["XX","YY","ZZ"]
rules = [for val in local.availability_domains : { "ad" : val, "name" : "service-${val}" , "hostclass" : "hostClassName", "instance_shape" : "VM.Standard2.1"}]
}

Related

Get value out of a tolist([ data object in Terraform

I have this terraform output:
output "cloud_connection" {
value = data.cloud_connection.current.connection[0]
}
$ terraform output
cloud_connection = tolist([
{
"id" = "123"
"settings" = toset([
{
"vlan_id" = 100
},
])
"connection_type" = "cloud"
},
])
I need to get the vlan_id to reuse it later on.
output "cloud_connection" {
value = data.cloud_connection.current.connection[0].settings[0].vlan_id
}
$ terraform output
cloud_connection = tolist([
tolist([
100,
]),
])
The problem is I can't seem to be able to get the vlan id out of a list.
When I try:
output "cloud_connection" {
value = data.connection.current.connection[0].settings[0].vlan_id[0]
}
I am getting this error:
│ Elements of a set are identified only by their value and don't have any separate index or key to select
│ with, so it's only possible to perform operations across all elements of the set.
How can I get the vlan_id alone?
Thanks
Assuming that you know that you have at least 1 element in each of the nested collections, the idiomatic way would be to use splat expression with some flattening:
output "cloud_connection" {
value = flatten(data.connection.current.connection[*].settings[*].vlan_id)[0]
}
You can use the function join, assuming you´re getting the following output:
$ terraform output
cloud_connection = tolist([
tolist([
100,
]),
])
For example:
output "cloud_connection" {
value = join(",",data.cloud_connection.current.connection[0].settings[0].vlan_id)
}
That returns:
cloud_connection = "100"

Dynamic form with composable-form

I'm trying to implement a dynamic form in Elm 0.19 using hecrj/composable-form.
I receive a json with the fields, their descriptions, etc, so I don't know beforehand how many fields it will have.
So the traditional way of defining a form:
Form.succeed OutputValues
|> Form.append field1
|> Form.append field2
doesn't work because I don't know the OutputValues structure beforehand.
I've seen there is a function Form.list which looks like a promising path, though it seems to expect all fields equal, which is not my case, I may have a text field and a select field for example.
Is there any straight forward way of doing this with this library?
Thank you.
The form library doesn't explicitly support what you're trying to do, but we can make it work!
tldr;
Here's my example of how you can take JSON and create a form: https://ellie-app.com/bJqNh29qnsva1
How to get there
Form.list is definitely the promising path. You're also exactly right that Form.list requires all of the fields to be of the same type. So let's start there! We can make one data structure that can hold them by making a custom type. In my example, I called it DynamicFormFieldValue. We'll make a variant for each kind of field. I created ones for text, integer, and select list. Each one will need to hold the value of the field and all of the extras (like title and default value) to make it show up nicely. This will be what we decode the JSON into, what the form value is, and what the form output will be. The resulting types looks like this:
type alias TextFieldRequirements =
{ name : String
, default : Maybe String
}
type alias IntFieldRequirements =
{ name : String
, default : Maybe Int
}
type alias SelectFieldRequirements =
{ name : String
, default : Maybe String
, options : List ( String, String )
}
type DynamicFormFieldValue
= TextField String TextFieldRequirements
| IntField Int IntFieldRequirements
| SelectField String SelectFieldRequirements
To display the form, you just need a function that can take the form value and display the appropriate form widget. The form library provides Form.meta to change the form based on the value. So, we will pattern match on the custom type and return Form.textField, Form.numberField, or Form.selectField. Something like this:
dynamicFormField : Int -> Form DynamicFormFieldValue DynamicFormFieldValue
dynamicFormField fieldPosition =
Form.meta
(\field ->
case field of
TextField textValue ({ name } as requirements) ->
Form.textField
{ parser = \_ -> Ok field
, value = \_ -> textValue
, update = \value oldValue -> TextField value requirements
, error = always Nothing
, attributes =
{ label = name
, placeholder = ""
}
}
IntField intValue ({ name } as requirements) ->
Form.numberField
{ parser = \_ -> Ok field
, value = \_ -> String.fromInt intValue
, update = \value oldValue -> IntField (Maybe.withDefault intValue (String.toInt value)) requirements
, error = always Nothing
, attributes =
{ label = name
, placeholder = ""
, step = Nothing
, min = Nothing
, max = Nothing
}
}
SelectField selectValue ({ name, options } as requirements) ->
Form.selectField
{ parser = \_ -> Ok field
, value = \_ -> selectValue
, update = \value oldValue -> SelectField value requirements
, error = always Nothing
, attributes =
{ label = name
, placeholder = ""
, options = options
}
}
)
Hooking this display function up is a bit awkward with the library. Form.list wasn't designed with use-case in mind. We want the list to stay the same length and just be iterated over. To achieve this, we will remove the "add" and "delete" buttons and be forced to provide a dummy default value (which will never get used).
dynamicForm : Form (List DynamicFormFieldValue) (List DynamicFormFieldValue)
dynamicForm =
Form.list
{ default =
-- This will never get used
TextField "" { name = "", default = Nothing }
, value = \value -> value
, update = \value oldValue -> value
, attributes =
{ label = "Dynamic Field Example"
, add = Nothing
, delete = Nothing
}
}
dynamicFormField
Hopefully the ellie example demonstrates the rest and you can adapt it to your needs!

Terraform - Iterate over a list generated from a for_each on a data block

UPDATE -> To all folks with this particular problem, I found the solution, it is at the end of this question.
UPDATE 2 -> The last solution that I presented here was WRONG, see the update at the end.
I am retrieving a list of cidr_blocks from a data block to use as a value on a aws_ec2_transit_gateway_route, but so far I have been unable to iterate through that list to get individual values and set it on the appropriate place.
The important piece of my data_block.tf looks like this:
data "aws_vpc" "account_vpc" {
provider = aws.dev
count = "${length(data.aws_vpcs.account_vpcs.ids)}"
id = element(tolist(data.aws_vpcs.account_vpcs.ids), 0)
}
data "aws_subnet_ids" "account_subnets" {
provider = aws.dev
vpc_id = element(tolist(data.aws_vpcs.account_vpcs.ids), 0)
}
data "aws_subnet" "cidrblocks" {
provider = aws.dev
for_each = data.aws_subnet_ids.account_subnets.ids
id = each.value
}
And the part where I intend to use it is this one, tgw_rt.tf:
resource "aws_ec2_transit_gateway_route" "shared-routes" {
provider = aws.shared
#count = length(data.aws_subnet.cidrblocks.cidr_block)
#destination_cidr_block = lookup(data.aws_subnet.cidrblocks.cidr_block[count.index], element(keys(data.aws_subnet.cidrblocks.cidr_block[count.index]),0), "127.0.0.1/32")
#destination_cidr_block = data.aws_subnet.cidrblocks.cidr_block[count.index]
#destination_cidr_block = [data.aws_subnet.cidrblocks.*.cidr_block]
destination_cidr_block = [for s in data.aws_subnet.cidrblocks : s.cidr_block]
/* for_each = [for s in data.aws_subnet.cidrblocks: {
destination_cidr_block = s.cidr_block
}] */
#destination_cidr_block = [for s in data.aws_subnet.cidrblocks : s.cidr_block]
#destination_cidr_block = data.aws_subnet.cidrblocks.cidr_block[count.index]
transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.fromshared.id
transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.shared.id
}
The part in comments is what I have tried so far and nothing worked.
The error that is happening currently when using that uncommented part is
Error: Incorrect attribute value type
on modules/tgw/tgw_rt.tf line 20, in resource "aws_ec2_transit_gateway_route" "shared-routes":
20: destination_cidr_block = [for s in data.aws_subnet.cidrblocks : s.cidr_block]
|----------------
| data.aws_subnet.cidrblocks is object with 3 attributes
Inappropriate value for attribute "destination_cidr_block": string required.
I would really appreciate it if one of the terraform gods present here could shed some light on this problem.
SOLUTION - THIS IS WRONG Since it was complaining about it being an object with 3 attributes (3 Cidr blocks), to iterate i had to use this:
destination_cidr_block = element([for s in data.aws_subnet.cidrblocks : s.cidr_block], 0)
CORRECT SOLUTION The solution was to add a small part to #kyle suggestion, I had to use an object to represent the data and convert it to a map, you rock #kyle:
for_each = {for s in data.aws_subnet.cidrblocks: s.cidr_block => s}
destination_cidr_block = each.value.cidr_block
Thank you all in Advance
I haven't used data.aws_subnet, but I think you were close with your for_each attempt-
resource "aws_ec2_transit_gateway_route" "shared-routes" {
...
for_each = [for s in data.aws_subnet.cidrblocks: s.cidr_block]
destination_cidr_block = each.value
...
}

Terraform conditions in a module

I am trying to create some simple logic when calling applicationg gateway module.
When creating WAF v2 application gateway I want to specify more attributes that simple application gateway can't handle and they won't be described.
resource "azurerm_application_gateway" {
name = var.appgatewayname
resource_group_name = data.azurerm_resource_group.rg.name
location = data.azurerm_resource_group.rg.location
......................
waf_configuration {
enabled = "${length(var.waf_configuration) > 0 ? lookup(var.waf_configuration, "enabled", "") : null }"
firewall_mode = "${length(var.waf_configuration) > 0 ? lookup(var.waf_configuration, "firewall_mode", "") : null }"
............
Calling module:
module "GWdemo" {
source = "./...."
sku-name = "WAF_v2"
sku-tier = "WAF_v2"
sku-capacity = 1
waf-configuration = [
{
enabled = true
firewall_mode = "Detection"
}
Am I thinking right that if waf-configuration map is specified it should specify following settings is applied and if not than null?
When working with Terraform we often want to reframe problems involving a conditional test into problems involving a collection that may or may not contain elements, because the Terraform language features are oriented around transforming collections into configuration on an element-by-element basis.
In your case, you have a variable that is already a list, so it could work to just ensure that its default value is an empty list rather than null, and thus that you can just generate one waf_configuration block per element:
variable "waf_configuration" {
type = list(object({
enabled = bool
firewall_mode = string
}))
default = []
}
Then you can use a dynamic block to generate one waf_configuration block per element of that list:
dynamic "waf_configuration" {
for_each = var.waf_configuration
content {
enabled = waf_configuration.value.enabled
firewall_mode = waf_configuration.value.firewall_mode
}
}
Although it doesn't seem to apply to this particular example, another common pattern is a variable that can be set to enable something or left unset to disable it. For example, if your module was designed to take only a single optional WAF configuration, you might define the variable like this:
variable "waf_configuration" {
type = object({
enabled = bool
firewall_mode = string
})
default = null
}
As noted above, the best way to work with something like that in Terraform is to recast it as a list that might be empty. Because it's a common situation, there is a shorthand for it via splat expressions:
dynamic "waf_configuration" {
for_each = var.waf_configuration[*]
content {
enabled = waf_configuration.value.enabled
firewall_mode = waf_configuration.value.firewall_mode
}
}
When we apply the [*] operator to a value of a non-list/non-set type, Terraform will test to see if the value is null. If it is null then the result will be an empty list, while if it is not null then the result will be a single-element list containing that one value.
After converting to a list we can then use it in the for_each argument to dynamic in the usual way, accessing the attributes from that possible single element inside the content block. We don't need to repeat the conditionals for each argument because the content block contents are evaluated only when the list is non-empty.
I would encourage you to upgrade to Terraform v0.12.x and this should get a much easier to do. I would leverage the new dynamic block syntax to make the block optional based on whatever condition you need to use.
Here is a rough example, but should get you going in the correct direction.
dynamic "waf-configuration " {
for_each = length(var.waf_configuration) > 0 ? [] : [1]
content {
enabled = "${length(var.waf_configuration) > 0 ? lookup(var.waf_configuration, "enabled", "") : null }"
firewall_mode = "${length(var.waf_configuration) > 0 ? lookup(var.waf_configuration, "firewall_mode", "") : null }"
}
}

Conditionally adjust visible columns in Rally Cardboard UI

So I want to allow the user to conditionally turn columns on/off in a Cardboard app I built. I have two problems.
I tried using the 'columns' attribute in the config but I can't seem to find a default value for it that would allow ALL columns to display(All check boxes checked) based on the attribute, ie. the default behavior if I don't include 'columns' in the config object at all (tried null, [] but that displays NO columns).
So that gets to my second problem, if there is no default value is there a simple way to only change that value in the config object or do I have to encapsulate the entire variable in 'if-else' statements?
Finally if I have to manually build the string I need to parse the values of an existing custom attribute (a drop list) we have on the portfolio object. I can't seem to get the rally.forEach loop syntax right. Does someone have a simple example?
Thanks
Dax - Autodesk
I found a example in the online SDK from Rally that I could modify to answer the second part (This assumes a custom attribute on Portfolio item called "ADSK Kanban State" and will output values to console) :
var showAttributeValues = function(results) {
for (var property in results) {
for (var i=0 ; i < results[property].length ; i++) {
console.log("Attribute Value : " + results[property][i]);
}
}
};
var queryConfig = [];
queryConfig[0] = {
type: 'Portfolio Item',
key : 'eKanbanState',
attribute: 'ADSK Kanban State'
};
rallyDataSource.findAll(queryConfig, showAttributeValues);
rally.forEach loops over each key in the first argument and will execute the function passed as the second argument each time.
It will work with either objects or arrays.
For an array:
var array = [1];
rally.forEach(array, function(value, i) {
//value = 1
//i = 0
});
For an object:
var obj = {
foo: 'bar'
};
rally.forEach(obj, function(value, key) {
//value = 'bar'
//key = 'foo'
});
I think that the code to dynamically build a config using the "results" collection created by your query above and passed to your sample showAttributeValues callback, is going to look a lot like the example of dynamically building a set of Table columns as shown in:
Rally App SDK: Is there a way to have variable columns for table?
I'm envisioning something like the following:
// Dynamically build column config array for cardboard config
var columnsArray = new Array();
for (var property in results) {
for (var i=0 ; i < results[property].length ; i++) {
columnsArray.push("'" + results[property][i] + "'");
}
}
var cardboardConfig = {
{
attribute: 'eKanbanState',
columns: columnsArray,
// .. rest of config here
}
// .. (re)-construct cardboard...
Sounds like you're building a neat board. You'll have to provide the board with the list of columns to show each time (destroying the old board and creating a new one).
Example config:
{
attribute: 'ScheduleState'
columns: [
'In-Progress',
'Completed'
]
}