Terraform aws_cloudfront_cache_policy pass multiple cookies to cookies_config - amazon-web-services

I can't seem to pass multiple cookies in the "items" list when in "cookies_config -> cookies"
Here is my variable:
variable "cache_policy_defaults" {
type = object({
name = string
comment = string
default_ttl = number
max_ttl = number
min_ttl = number
cookie_behavior = string
cookies_to_forward = optional(list(string))
header_behavior = string
headers_to_forward = optional(list(string))
query_string_behavior = string
query_strings_to_forward = optional(list(string))
}
)
default = {
name = ""
comment = ""
default_ttl = 60
max_ttl = 60
min_ttl = 60
cookie_behavior = "none"
cookies_to_forward = []
header_behavior = "none"
headers_to_forward = []
query_string_behavior = "none"
query_strings_to_forward = []
}
}
Here are my locals:
locals {
origin_id = "origin_${local.origin_config.domain_name}"
origin_config = merge(var.origin_defaults, var.origin_settings)
restrictions = merge(var.restrictions_defaults, var.restrictions_settings)
default_cache_behavior = merge(var.default_cache_behavior_defaults, var.default_cache_behavior_settings)
cache_policy = merge(var.cache_policy_defaults, var.cache_policy_settings)
cache_policy_name = "cache_policy_${var.name}"
}
Here is my tfvars:
"cache_policy_settings": {
"min_ttl": 30,
"max_ttl": 30,
"default_ttl": 30,
"cookie_behavior": "whitelist",
"cookies_to_forward": ["123", "456"]
}
Here is my main.tf:
resource "aws_cloudfront_cache_policy" "this" {
name = lookup(local.cache_policy, local.cache_policy.name, local.cache_policy_name)
comment = local.cache_policy.comment
default_ttl = local.cache_policy.default_ttl
max_ttl = local.cache_policy.max_ttl
min_ttl = local.cache_policy.min_ttl
parameters_in_cache_key_and_forwarded_to_origin {
cookies_config {
cookie_behavior = local.cache_policy.cookie_behavior
dynamic "cookies" {
for_each = local.cache_policy.cookies_to_forward != null ? local.cache_policy.cookies_to_forward : null
content {
items = local.cache_policy.cookies_to_forward
}
}
}
headers_config {
header_behavior = local.cache_policy.header_behavior
dynamic "headers" {
for_each = local.cache_policy.headers_to_forward != null ? local.cache_policy.headers_to_forward : null
content {
items = local.cache_policy.headers_to_forward
}
}
}
query_strings_config {
query_string_behavior = local.cache_policy.query_string_behavior
dynamic "query_strings" {
for_each = local.cache_policy.query_strings_to_forward != null ? local.cache_policy.query_strings_to_forward : null
content {
items = local.cache_policy.query_strings_to_forward
}
}
}
}
}
The docs state
items: (Required) A list of item names (cookies, headers, or query strings).
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_cache_policy#items
However, the list does not accept multiple items.
Error: Too many list items
on main.tf line 57, in resource "aws_cloudfront_cache_policy" "this":
57: cookies_config {
Attribute supports 1 item maximum, but config has 2 declared.
It seems that I should just be able to pass a list of items? If I change the my input list to only contain a single value, then it works.

Here is the trick:
for_each = local.cache_policy.cookies_to_forward != null ? [1] : null
This tells Terraform to create exactly one block by making the true value of the ternary [1].
Thanks Jason for putting me on the right track.

Related

Terraform create either one block type or another within a resource

I am trying to create an alert policy within GCP using Terraform and Based on a boolean value I want to choose wether to create condition_threshold or conditionAbsent type policy.
Since these are both different kinds of blocks within google_monitoring_alert_policy, I am not able to find a way to create either one or other based on a boolean value.
resource "google_monitoring_alert_policy" "logging_alert_policy" {
for_each = local.metrics_map
project = var.project
display_name = lower(format("%s%s%s%s", join("_", [element(split("-", each.value.appcode), length(split("-", each.value.appcode)) - 1), element(split("-", each.value.appcode), 0)]), " ", "log_match ", each.value.display_name))
combiner = each.value.how_to_trigger
dynamic "conditions" {
for_each = each.value.conditions
content {
display_name = lower(format("%s%s%s%s", join("_", [element(split("-", conditions.value.appcode), length(split("-", conditions.value.appcode)) - 1), element(split("-", conditions.value.appcode), 0)]), " ", "log_match ", conditions.value.display_name))
# condition_threshold {
# filter = lower("metric.type=\"logging.googleapis.com/user/${format("%s%s%s%s", conditions.value.appcode, "-", lower(replace(lookup(conditions.value, "metric_name"), "/\\W|_|\\s/", "-")), "")}\" resource.type=\"${conditions.value.resource_type}\"")
# comparison = conditions.value.comparison
# threshold_value = conditions.value.threshold_value
# duration = conditions.value.duration
# trigger {
# count = lookup(conditions.value, "trigger_count", var.default_metric_alert["trigger_count"])
# }
# aggregations {
# alignment_period = conditions.value.alignment_period
# per_series_aligner = conditions.value.per_series_aligner
# cross_series_reducer = conditions.value.cross_series_reducer
# group_by_fields = conditions.value.group_by_fields
# }
# }
condition_absent {
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_MAX"
cross_series_reducer = "REDUCE_MAX"
group_by_fields = ["resource.label.container_name"]
}
trigger {
count = 1
}
duration = "180s"
filter = lower("metric.type=\"logging.googleapis.com/user/${format("%s%s%s%s", conditions.value.appcode, "-", lower(replace(lookup(conditions.value, "metric_name"), "/\\W|_|\\s/", "-")), "")}\" resource.type=\"${conditions.value.resource_type}\"")
}
}
}
I would propose nested dynamic blocks that rely on local computed set of one element - or no elements.
Short example of that idea:
locals {
absent = false # let's say we want to have "condition_threshold" block if this is true
conditions_config = local.absent == false ? ["1"] : []
absent_conditions_config = local.absent == true ? ["1"] : []
# I agree the above code is ugly but shows exactly the idea
}
# [...]
dynamic "conditions" {
for_each = each.value.conditions
content {
#[...]
dynamic "condition_threshold" {
for_each = toset(local.conditions_config) # this will be one element if local.absent = false
# content { ... }
}
dynamic "condition_absent" {
for_each = toset(local.absent_conditions_config) # this will be one element if local.absent = true
# content { ... }
}

Is there a way to find an element in a list and delete items after it that are of a specific type without using indicies?

I have a project that needs me to remove items if one of the properties of the item I'm trying to find within the list is true. Just so it's easier understand the project I am pasting all code needed to understand it below.
fun main() {
val acct1 = AccountId(72)
val calendars = mutableListOf<CalendarDrawerCalendarItem>()
val calendars2 = mutableListOf<CalendarDrawerCalendarItem>()
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 3),"toast", true)))
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 4), "chicken", false)))
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 5), "pizza", true)))
calendars2.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 1), "bagel", true)))
// These are example calls to collapse
collapse(calendars, CalendarDrawerGroupItem(true, CalendarGroupDescriptor( acct1, "My Calendars")))
collapse(calendars2, CalendarDrawerGroupItem(false, CalendarGroupDescriptor(acct1, "Group Calendars")))
}
fun collapse(calendars: List<CalendarDrawerListItem>, group: CalendarDrawerGroupItem): List<CalendarDrawerListItem> {
val collapsedResults = mutableListOf<CalendarDrawerListItem>()
val findGroupGiven = group
collapsedResults.addAll(calendars)
if (collapsedResults.contains(findGroupGiven)) {
group.collapsed = true
// logic for deleting items here
}
return collapsedResults
}
I'll also put the classes so you can see how they're defined
data class AccountId(
val accountId: Int
)
data class CalendarId(
val accountId: AccountId,
val calendarId: Int)
data class CalendarDescriptor(
val accountId: AccountId,
val calendarId: CalendarId,
val name: String,
val isGroupCalendar: Boolean
)
data class CalendarGroupDescriptor(
val accountId: AccountId,
val name: String,
)
sealed class CalendarDrawerListItem
data class CalendarDrawerGroupItem(var collapsed: Boolean, val groupDescriptor: CalendarGroupDescriptor) : CalendarDrawerListItem()
data class CalendarDrawerCalendarItem(val calendarDescriptor: CalendarDescriptor) : CalendarDrawerListItem()
The first step I have done is I must find the given group from the group variable, within calendars. (I did this with the contains() method). Next when I find the group I have to set its collapsed variable to true and any CalendarDrawerCalendarItems after it have to be deleted.
The input will look something like (the exact numbers and values are not the important part):
Input:
calendars:
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 1, isGroup = false))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 2, isGroup = false))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 3, isGroup = false))
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "Group calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 4, isGroup = true))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 5, isGroup = true))
group: CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
The output should look something like this:
Output:
CDGroupItem(collapsed = true, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "Group calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 4, isGroup = true))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 5, isGroup = true))
Any group item that has its collapsed boolean set to true should have all calendar items deleted after it since its collapsed is set to true. Again the names and numbers are not super important. The collapsed bool is. How can I do this without hardcoding or using indicies?
Your example code doesn't use that input and output as-is so I can only give you a general example, but you could use a fold:
val result = calendars.fold(mutableListOf<CalendarDrawerListItem>()) { items, current ->
// basically 'is there a last item stored, and is it a group item, and is it collapsed'
val lastStoredIsCollapsed =
(items.lastOrNull() as? CalendarDrawerGroupItem)?.collapsed == true
if (current is CalendarDrawerCalendarItem && lastStoredIsCollapsed) items
else items.apply { add(current) }
}
It basically pipes out each item into a list, but if the last one it stored is a CalendarDrawerGroupItem with collapsed set to true, it drops drawer items. If the last one is a non-collapsed group item, it can store a drawer item, and that means the next drawer item will be stored (since the last item isn't a collapsed group)
edit: here's the for loop equivalent if it helps, with the full logic for when a calendar is not dropped (the logic in my other example is for whether it should be dropped, which can be condensed a bit):
// assuming 'calendars' is your list of items with 'collapsed' set appropriately
val result = mutableListOf<CalendarDrawerListItem)
for (calendar in calendars) {
val lastStored = result.lastOrNull()
when {
lastStored == null ->
result.add(calendar)
lastStored is CalendarDrawerGroupItem && !lastStored.collapsed ->
result.add(calendar)
lastStored is CalendarDrawerCalendarItem ->
result.add(calendar)
}
}
return result
If you're asking how to actually mutate your list so a collapsed property is set to true, that would be easy if the property was a var in your data class. Since it's a val you'll have to do something like this:
val calendarInputWithCollapsedSet = calendars.map { calendar ->
if ((calendar as? CalendarDrawerGroupItem)?.groupDescriptor == group.groupDescriptor)
calendar.copy(collapsed = true) else calendar
}
So if you find a matching group (you'll have to work out how to match them, I'm guessing) you transform it into a copy with its collapsed property set
And then you can run the fold or whatever on that new list.

Terraform - Copy AWS SSM Parameters

longtime lurker first time poster
Looking for some guidance from you all. I'm trying to replicate the aws command to essentially get the parameters (ssm get-parameters-by-path) then loop through the parameters and get them
then loop through and put them into a new parameter (ssm put-parameter)
I understand there's a for loop expression in TF but for the life of me I can't put together how I would achieve this.
so thanks to the wonderful breakdown below, I've gotten closer! But have this one issue. Code below:
provider "aws" {
region = "us-east-1"
}
data "aws_ssm_parameters_by_path" "parameters" {
path = "/${var.old_env}"
recursive = true
}
output "old_params_by_path" {
value = data.aws_ssm_parameters_by_path.parameters
sensitive = true
}
locals {
names = toset(data.aws_ssm_parameters_by_path.parameters.names)
}
data "aws_ssm_parameter" "old_param_name" {
for_each = local.names
name = each.key
}
output "old_params_names" {
value = data.aws_ssm_parameter.old_param_name
sensitive = true
}
resource "aws_ssm_parameter" "new_params" {
for_each = local.names
name = replace(data.aws_ssm_parameter.old_param_name[each.key].name, var.old_env, var.new_env)
type = data.aws_ssm_parameter.old_param_name[each.key].type
value = data.aws_ssm_parameter.old_param_name[each.key].value
}
I have another file like how the helpful poster mentioned and created the initial dataset. But what's interesting is that after you create the set after the second set, it overwrites the first set! The idea is that I would be able to tell terraform, I have this current set of SSM parameters and I want you to copy that info (values, type) and create a brand new set of parameters (and not destroy anything that's already there).
Any and all help would be appreciated!
I understand, It's not easy at the beginning. I will try to elaborate step-by-step on how I achieve that.
Anyway, it's nice to include any code, that you tried before, even if doesn't work.
So, firstly I create some example parameters:
# create_parameters.tf
resource "aws_ssm_parameter" "p" {
count = 3
name = "/test/${count.index}/p${count.index}"
type = "String"
value = "test-${count.index}"
}
Then I try to view them:
# example.tf
data "aws_ssm_parameters_by_path" "parameters" {
path = "/test/"
recursive = true
}
output "params_by_path" {
value = data.aws_ssm_parameters_by_path.parameters
sensitive = true
}
As an output I received:
terraform output params_by_path
{
"arns" = tolist([
"arn:aws:ssm:eu-central-1:999999999999:parameter/test/0/p0",
"arn:aws:ssm:eu-central-1:999999999999:parameter/test/1/p1",
"arn:aws:ssm:eu-central-1:999999999999:parameter/test/2/p2",
])
"id" = "/test/"
"names" = tolist([
"/test/0/p0",
"/test/1/p1",
"/test/2/p2",
])
"path" = "/test/"
"recursive" = true
"types" = tolist([
"String",
"String",
"String",
])
"values" = tolist([
"test-0",
"test-1",
"test-2",
])
"with_decryption" = true
}
aws_ssm_parameters_by_path is unusable without additional processing, so we need to use another data source, to get a suitable object for a copy of provided parameters. n the documentation I found aws_ssm_parameter. However, to use it, I need the full name of the parameter.
List of the parameter names I retrieved in the previous stage, so now only needed is to iterate through them:
# example.tf
locals {
names = toset(data.aws_ssm_parameters_by_path.parameters.names)
}
data "aws_ssm_parameter" "param" {
for_each = local.names
name = each.key
}
output "params" {
value = data.aws_ssm_parameter.param
sensitive = true
}
And as a result, I get:
terraform output params
{
"/test/0/p0" = {
"arn" = "arn:aws:ssm:eu-central-1:999999999999:parameter/test/0/p0"
"id" = "/test/0/p0"
"name" = "/test/0/p0"
"type" = "String"
"value" = "test-0"
"version" = 1
"with_decryption" = true
}
"/test/1/p1" = {
"arn" = "arn:aws:ssm:eu-central-1:999999999999:parameter/test/1/p1"
"id" = "/test/1/p1"
"name" = "/test/1/p1"
"type" = "String"
"value" = "test-1"
"version" = 1
"with_decryption" = true
}
"/test/2/p2" = {
"arn" = "arn:aws:ssm:eu-central-1:999999999999:parameter/test/2/p2"
"id" = "/test/2/p2"
"name" = "/test/2/p2"
"type" = "String"
"value" = "test-2"
"version" = 1
"with_decryption" = true
}
}
Each parameter object has been retrieved, so now it is possible to create new parameters - which can be done like this:
# example.tf
resource "aws_ssm_parameter" "new_param" {
for_each = local.names
name = "/new_path${data.aws_ssm_parameter.param[each.key].name}"
type = data.aws_ssm_parameter.param[each.key].type
value = data.aws_ssm_parameter.param[each.key].value
}

Problem in rendering Multiple Drilldown in fusioncharts

I am using Django. I want use the drilldown feature in fusioncharts. I am able to get the first drilldown correctly. But when I code for the second drilldown it is showing "No data to display". Also the following code renders all the charts in the same type. But I want to render the child charts in different types. I am sharing the snippet below.
def chart(request):
dataSource = {}
dataSource['chart'] = {
"caption": "Top 10 Most Populous Countries",
"showValues": "0",
"theme": "zune"
}
dataSource['data'] = []
dataSource['linkeddata'] = []
sbc = MTD.pdobjects.values('Vertical', 'Channel','Brand','Sales_Value')
sbc_df = sbc.to_dataframe().reset_index(drop=True)#Trying to use filtered model for dataframe
sbc_df['Sales_Value']=sbc_df['Sales_Value'].astype(float)
chn_gb=sbc_df.groupby('Channel')['Sales_Value'].sum().reset_index()
channel=list(chn_gb['Channel'])
channel_val=list(chn_gb['Sales_Value'])
sbc_gb=pandas.pivot_table(sbc_df,index=['Vertical','Channel'],values=['Sales_Value'],aggfunc='sum').reset_index()
brd_gb=pandas.pivot_table(sbc_df,index=['Vertical','Channel','Brand'],values=['Sales_Value'],aggfunc='sum').reset_index()
for i in range(len(channel)):
data = {}
data['label'] = channel[i]
data['value'] = channel_val[i]
data['link'] = 'newchart-json-'+ channel[i]
dataSource['data'].append(data)
linkData2 = {}
linkData2['id'] = channel[i]
linkedchart2 = {}
linkedchart2['chart'] = {
"caption" : "Top 10 Most Populous Cities - " + channel[i] ,
"showValues": "0",
"theme": "fusion",
}
linkedchart2['data'] = []
sbc_filtered=sbc_gb[sbc_gb.Channel == channel[i]]
vertical_list=list(sbc_filtered['Vertical'])
vertical_val=list(sbc_filtered['Sales_Value'])
for k in range(len(sbc_filtered)):
arrDara2 = {}
arrDara2['label'] = vertical_list[k]
arrDara2['value'] = vertical_val[k]
arrDara2['link'] = 'newchart-json-'+ vertical_list[k]
linkedchart2['data'].append(arrDara2)
linkData1 = {}
# Inititate the linkData for cities drilldown
linkData1['id'] = vertical_list[k]
linkedchart1 = {}
linkedchart1['chart'] = {
"caption" : "Top 10 Most Populous Cities - " + vertical_list[k] ,
"showValues": "0",
"theme": "fusion",
}
linkedchart1['data'] = []
brd_filtered=brd_gb[(brd_gb.Channel == channel[i]) & (brd_gb.Vertical== vertical_list[k])]
brd_list=list(brd_filtered['Brand'])
brd_val=list(brd_filtered['Sales_Value'])
for j in range(len(brd_filtered)):
arrDara1 = {}
arrDara1['label'] = brd_list[j]
arrDara1['value'] = brd_val[j]
linkedchart1['data'].append(arrDara1)
linkData1['linkedchart'] = linkedchart1
dataSource['linkeddata'].append(linkData1)
linkData2['linkedchart'] = linkedchart2
dataSource['linkeddata'].append(linkData2)
print(dataSource)
column2D = FusionCharts("column2D", "ex1" , "700", "400", "chart-1", "json", dataSource)
return render(request, 'table.html',{'output':column2D.render()})
Kindly help me to achieve the successive drilldown correctly.
Thanks
In order to change the chart type for the child chart you need to use configureLink API method to set the child chart type, you can also set different chart at a different level, provided the datastructure for each chart is correct, here is how you can do
myChart.configureLink([
{ type: 'bar2d' },
{ type: 'line' },
{ type: 'pie2d' }
]);
Here is a demo - http://jsfiddle.net/x0c2wo7k/
Please note the above sample is using plain javascript

Create vTiger Sales Order fails due to MANDATORY_FIELDS_MISSING "message":"Mandatory Fields Missing

I'm trying to create a SalesOrder via WebServices but it always fails due to missing mandatory fields.
I'm sending the following fields.
The error message does not specify the missing fields
I'm using vTiger 6.0.0
How can I figure it out
salesOrder.subject = fullDescription
salesOrder.sostatus = "delivered"
salesOrder.account_id ='11x28'
salesOrder.bill_street = shipping.address.street
salesOrder.bill_city = shipping.address.city
salesOrder.bill_state = shipping.address.state
salesOrder.bill_code = shipping.address.postalCode
salesOrder.bill_country = shipping.address.postalCode
salesOrder.ship_street = shipping.address.street
salesOrder.ship_city = shipping.address.city
salesOrder.ship_state = shipping.address.state
salesOrder.ship_code = shipping.address.postalCode
salesOrder.ship_country = shipping.address.postalCode
salesOrder.invoicestatus = "Created"
salesOrder.productid = selectedServices[0].id
salesOrder.quantity = 1
salesOrder.listprice = selectedServices[0].unit_price
//
salesOrder.comment= ""
salesOrder.tax1 = ""
salesOrder.tax2 = "10.000"
salesOrder.tax3 = "6.000"
salesOrder.pre_tax_total = "876.00"
salesOrder.currency_id = "21x1"
salesOrder.conversion_rate = "1.000"
salesOrder.tax4 = ""
salesOrder.duedate = "2014-12-12"
salesOrder.carrier = "FedEx"
salesOrder.pending = ""
salesOrder.txtAdjustment = "-21.00000000"
salesOrder.salescommission = "5.000"
salesOrder.exciseduty = "0.000"
salesOrder.hdnGrandTotal = "995.16000000"
salesOrder.hdnSubTotal = "876.00000000"
salesOrder.hdnTaxType = "group"
salesOrder.hdndiscountamount = "0"
salesOrder.hdnS_H_Percent = "21"
salesOrder.discount_percent = "25.000"
salesOrder.discount_amount = ""
salesOrder.terms_conditions = "- Unless "
salesOrder.enable_recurring = "0"
I was missing the LineItems. Please notice that it has to be CamelCase
"LineItems": [
{
"productid": "25x142",
"listprice": "299.00000000",
"quantity": "1"
}
],
you missed the mandatory field "Assigned TO"