How to get string value from an array of string defined in json template using terraform - arrays

I am trying to create routes in Transit gateway route table using a json template. However, while fetching each string value from an array of string defined in json template, getting error as below;
Error: Incorrect attribute value type\n\n on main.tf line 90, in resource \"aws_ec2_transit_gateway_route\" \"ip_route\":\n 90: destination_cidr_block = each.value.ip_network\n |----------------\n | each.value.ip_network is tuple with 3 elements\n\nInappropriate value for attribute \"destination_cidr_block\": string require
Here below is my code -->
resource "aws_ec2_transit_gateway_route" "ip_route" {
for_each = jsondecode(file("templates/my.json"))
destination_cidr_block = each.value.ip_network
transit_gateway_attachment_id = "tgw-attach-123"
transit_gateway_route_table_id = each.value.tgw_rt_id
}
json file -->
{
"RT-1": {
"tgw_rt_id": "tgw-rtb-00128",
"ip_network": [
"1.1.1.0/24",
"1.1.2.0/24",
"1.1.3.0/24"
]
},
"RT-2": {
"tgw_rt_id": "tgw-rtb-01f1b",
"ip_network": [
"1.1.1.0/24",
"1.1.2.0/24",
"1.1.3.0/24"
]
}
}
I am able to get the "destination_cidr_block" value as "string" if only single string is passed in "ip_network" (eg: "ip_network": "1.1.1.0/24") but failed to fetch when defined with array of string.

As you've identified, the destination_cidr_block only accepts a single CIDR block (a string), not multiple CIDR blocks. You need to create a separate aws_ec2_transit_gateway_route for each CIDR block for each route table. You can do this by flattening the map so there's one element for each RT/CIDR combination.
locals {
route_tables = jsondecode(file("templates/my.json"))
rt_cidr_blocks = merge([
for k, rt in local.route_tables:
{
for i, ip_network in rt.ip_network:
"${k}-${i}" => {
tgw_rt_id = rt.tgw_rt_id
ip_network = ip_network
}
}
]...)
}
resource "aws_ec2_transit_gateway_route" "ip_route" {
for_each = local.rt_cidr_blocks
destination_cidr_block = each.value.ip_network
transit_gateway_attachment_id = each.key
transit_gateway_route_table_id = each.value.tgw_rt_id
}
If you want to see what the flattened map looks like now:
output "rt_cidr_blocks" {
value = local.rt_cidr_blocks
}
Output:
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
blocks = {
"RT-1-0" = {
"ip_network" = "1.1.1.0/24"
"tgw_rt_id" = "tgw-rtb-00128"
}
"RT-1-1" = {
"ip_network" = "1.1.2.0/24"
"tgw_rt_id" = "tgw-rtb-00128"
}
"RT-1-2" = {
"ip_network" = "1.1.3.0/24"
"tgw_rt_id" = "tgw-rtb-00128"
}
"RT-2-0" = {
"ip_network" = "1.1.1.0/24"
"tgw_rt_id" = "tgw-rtb-01f1b"
}
"RT-2-1" = {
"ip_network" = "1.1.2.0/24"
"tgw_rt_id" = "tgw-rtb-01f1b"
}
"RT-2-2" = {
"ip_network" = "1.1.3.0/24"
"tgw_rt_id" = "tgw-rtb-01f1b"
}
}

Related

How can I use a script to delete all data on a google spreadsheet?

I have a google form that exports all of the answers to a google sheet. I also have a script that exports my google sheets (aka my form answers) and converts it to json. The problem is, If I make another response on google forms, my script converts both responses into a json when I only want the most recent response to converted. What I need is an addition to my script to delete all rows after it exports the data so when I try again it doesn't take the old responses.
// Tweak the makePrettyJSON_ function to customize what kind of JSON to export.
var FORMAT_ONELINE = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY = 'Pretty';
var LANGUAGE_JS = 'JavaScript';
var LANGUAGE_PYTHON = 'Python';
var STRUCTURE_LIST = 'List';
var STRUCTURE_HASH = 'Hash (keyed by "id" column)';
/* Defaults for this particular spreadsheet, change as desired */
var DEFAULT_FORMAT = FORMAT_PRETTY;
var DEFAULT_LANGUAGE = LANGUAGE_JS;
var DEFAULT_STRUCTURE = STRUCTURE_LIST;
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{name: "Export JSON for this sheet", functionName: "exportSheet"},
{name: "Export JSON for all sheets", functionName: "exportAllSheets"}
];
ss.addMenu("Export JSON", menuEntries);
}
function makeLabel(app, text, id) {
var lb = app.createLabel(text);
if (id) lb.setId(id);
return lb;
}
function makeListBox(app, name, items) {
var listBox = app.createListBox().setId(name).setName(name);
listBox.setVisibleItemCount(1);
var cache = CacheService.getPublicCache();
var selectedValue = cache.get(name);
Logger.log(selectedValue);
for (var i = 0; i < items.length; i++) {
listBox.addItem(items[i]);
if (items[1] == selectedValue) {
listBox.setSelectedIndex(i);
}
}
return listBox;
}
function makeButton(app, parent, name, callback) {
var button = app.createButton(name);
app.add(button);
var handler = app.createServerClickHandler(callback).addCallbackElement(parent);;
button.addClickHandler(handler);
return button;
}
function makeTextBox(app, name) {
var textArea = app.createTextArea().setWidth('100%').setHeight('200px').setId(name).setName(name);
return textArea;
}
function exportAllSheets(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheetsData = {};
for (var i = 0; i < sheets.length; i++) {
var sheet = sheets[i];
var rowsData = getRowsData_(sheet, getExportOptions(e));
var sheetName = sheet.getName();
sheetsData[sheetName] = rowsData;
}
var json = makeJSON_(sheetsData, getExportOptions(e));
displayText_(json);
}
function exportSheet(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rowsData = getRowsData_(sheet, getExportOptions(e));
var json = makeJSON_(rowsData, getExportOptions(e));
displayText_(json);
}
function getExportOptions(e) {
var options = {};
options.language = e && e.parameter.language || DEFAULT_LANGUAGE;
options.format = e && e.parameter.format || DEFAULT_FORMAT;
options.structure = e && e.parameter.structure || DEFAULT_STRUCTURE;
var cache = CacheService.getPublicCache();
cache.put('language', options.language);
cache.put('format', options.format);
cache.put('structure', options.structure);
Logger.log(options);
return options;
}
function makeJSON_(object, options) {
if (options.format == FORMAT_PRETTY) {
var jsonString = JSON.stringify(object, null, 4);
} else if (options.format == FORMAT_MULTILINE) {
var jsonString = Utilities.jsonStringify(object);
jsonString = jsonString.replace(/},/gi, '},\n');
jsonString = prettyJSON.replace(/":\[{"/gi, '":\n[{"');
jsonString = prettyJSON.replace(/}\],/gi, '}],\n');
} else {
var jsonString = Utilities.jsonStringify(object);
}
if (options.language == LANGUAGE_PYTHON) {
// add unicode markers
jsonString = jsonString.replace(/"([a-zA-Z]*)":\s+"/gi, '"$1": u"');
}
return jsonString;
}
function displayText_(text) {
var output = HtmlService.createHtmlOutput("<textarea style='width:100%;' rows='20'>" + text + "</textarea>");
output.setWidth(400)
output.setHeight(300);
SpreadsheetApp.getUi()
.showModalDialog(output, 'Exported JSON');
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData_(sheet, options) {
var headersRange = sheet.getRange(1, 1, sheet.getFrozenRows(), sheet.getMaxColumns());
var headers = headersRange.getValues()[0];
var dataRange = sheet.getRange(sheet.getFrozenRows()+1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
var objects = getObjects_(dataRange.getValues(), normalizeHeaders_(headers));
if (options.structure == STRUCTURE_HASH) {
var objectsById = {};
objects.forEach(function(object) {
objectsById[object.id] = object;
});
return objectsById;
} else {
return objects;
}
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData_(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders_(arrayTranspose_(headersTmp)[0]);
return getObjects(arrayTranspose_(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects_(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty_(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders_(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader_(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader_(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum_(letter)) {
continue;
}
if (key.length == 0 && isDigit_(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty_(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum_(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit_(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit_(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose_(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
} ```
This isn't my original script and I am not that knowledgeable in this space so any help is appreciated.
Clear contents on all sheets
function clearAll() {
SpreadsheetApp.getActive().getSheets().forEach(sh => sh.clear());
}

Flutter : How to get the value of the other properties from a List?

All of my Json data is already inside in my model. And I have also a list of data inside "selectedBranches[]". What do I want is to get the other value of the other properties which is the BranchCode and BranchId based on the value from the selectedBranches list and put it to the another list.
My selectedBranches List is consist of list of branchFullName properties from my json data.
But dart says The argument type 'List' can't be assigned to the parameter type 'Pattern'.
#Code Snippet#
selectedBranches = [ex1,ex2,ex3,ex4];
selectedAssignBranches = [];
assignBranch() {
branchModel1 = GetBranchList.fromJson(jsonData1);
var newArr = branchModel1.data;
for (var u in newArr) {
AssignBranch assignModel = new AssignBranch();
if (u.branchFullName.contains(selectedBranches/*error*/)) {
assignModel.BranchCode = u.branchCode;
assignModel.BranchID = u.brID;
selectedAssignBranches.add(assignModel);
}
}
}
#Model#
class Datum {
String branchCode;
String branchName;
String stat;
String brID;
String branchFullName;
I already solve the problem. You just need to have a nested for loop. Thats it!
assignBranch() {
branchModel1 = GetBranchList.fromJson(jsonData1);
var newArr = branchModel1.data;
for (var i in selectedBranches) {
for (var u in newArr) {
if (u.branchFullName == (i)) {
AssignBranch assignModel = new AssignBranch();
assignModel.BranchCode = u.branchCode;
assignModel.BranchID = u.brID;
selectedAssignBranches.add(assignModel);
}
}
}
}

How to grab variable from one API that is within a nested Array response body?

How to grab the contentID and content title add it within an array and have it used in the URL of API 2
if i use the code below for section title and sectionid it is working because it is not in an nested array but for the contentid and contenttitle it is not working as it is in a nested array.
In the API 1 test tab i have:
for (i = 0; i < resultCount; i++) {
var id = jsonData[i].contents[0].contentId;
var modelString = jsonData[i].contents[0].contentTitle;
console.log(id)
console.log(modelString)
if (modelString.includes(“APIAUTOMATIONcontent”) || modelString.includes(“Testcontent”) || modelString.includes("{{POST-NewSlide}}") || modelString.includes(“stringcontent”)) {
hasDelete.push(id);
// (id) - this creates an integer (int)
// "announcementId": id, (creating object)
// "hasDelete": modelString.includes("Delete") || modelString.includes("Test")
// });
} else {
doesntHaveDelete.push(id)
// "announcementId": id
// });
}
}
// Check that each object in response contained keyword and length matches from test
pm.test(Number of Content that has APIAUTOMATIONcontent or Test ready to be deleted = ${hasDelete.length} out of Total ${resultCount} , function() {
console.log(hasDelete);
console.log(doesntHaveDelete);
pm.expect(hasDelete.length);
});
pm.collectionVariables.set(‘deletesections’, JSON.stringify(hasDelete));
Like you're iterating over each section in your response body, you also need to iterate over the contents array, you can do it like below:
for (i = 0; i < resultCount; i++) {
contentCount = jsonData[i].contents.length;
for (j = 0; j < contentCount; j++) {
let content = jsonData[i].contents[j];
console.log(content.contentId);
console.log(content.sectionId);
console.log(content.contentTitle);
console.log(content.pdfLink);
console.log(content.videoLink);
console.log(content.sortOrder);
}
}

How to convert JSON to URL params string as per my expected value?

I am working on an angular project. For a method getting a response JSON to convert stringify and POST a body to an API is done. Now the problem is for another one function I should send this value as a URL parameter I tried some ways but didn't get expected result. Please find the below codes and help me out. Thanks
Here is my JSON format value
const bodyJSON = [{FullPackageIDs:[11,7],
PartialPkg:[
{PackageID:4,
FormsList:[
{Form_Name:"Form name One"},
{Form_Name:"Form name Two"}]},
{PackageID:6,
FormsList:[
{Form_Name:"Form name Three"},
{Form_Name:"Form name Four"},
{Form_Name:"Form name Five"}
]
}
]
}]
My expected URL string value like below
http://localhost:4200/DownloadPackage?FullPackageIDs[0]=11&FullPackageIDs[1]=7&PartialPkg[0].PackageID=4&PartialPkg[0].FormsList[0].Form_Name=Form name One&PartialPkg[0].FormsList[1].Form_Name=Form name Two&PartialPkg[1].PackageID=6&PartialPkg[0].FormsList[0].Form_Name=Form name Three&PartialPkg[1].FormsList[1].Form_Name=Form name Four&PartialPkg[2].FormsList[2].Form_Name=Form name Five
I tried via forloop but didnt get expected result. Here is the code for what I tried.
for (let i = 0; i < getSelectedId.length; i++) {
fullPackageParams = `${fullPackageParams}FullPackageIDs[${i}]=${getSelectedId[i]}&`;
for (let j = 0; j < getPartialId.length; j++) {
// const getPartialName = this.partialPackage.map(res => res[i].FormsList);
const getPartialName = getPartialId[j].FormsList;
partialPackageIDParams = `${partialPackageIDParams}PartialPkg[${j}].PackageID=${getPartialId[j].PackageID}&`;
for (let index = 0; index < getPartialName.length; index++) {
partialPackageNameParams = `PartialPkg[${index}].FormsList[${index}].Form_Name=${getPartialName[index].Form_Name}&`;
}
}
}
console.log('params for full packages', fullPackageParams + partialPackageIDParams + partialPackageNameParams);
even if it seems kinda strange to me that you need to pass all of those params using query, you can try this
it just uses ES6 map, reduce functions to create your query string
let URLQuery = bodyJSON.map(value => {
const packageIDs = value.FullPackageIDs.map((v, i) => `FullPackageIDs[${i}]=${encodeURIComponent(v)}`);
const partialPkgs = value.PartialPkg.map((v, i) => {
const startKey = `PartialPkg[${i}]`;
return [
`${startKey}.PackageID=${v.PackageID}`
].concat(
v.FormsList.map((v, i) => `${startKey}.FormsList[${i}].Form_Name=${encodeURIComponent(v.Form_Name)}`)
);
}).reduce((arr, v) => {
return arr.concat(v)
}, []);
return packageIDs.concat(partialPkgs);
}).reduce((arr, v) => {
return arr.concat(v);
}, []).join("&");
const fullURL = `https://example.com?${URLQuery}`;

Angularjs: convert string CSV format to Array

I don't know how can I convert my string data in $scope.fileContent ( I got it from my CSV file) in array. I printed my $scope.fileContent:
console.log($scope.fileContent) =
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
But I would like a function to convert it to a array like this:
[
{ heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" }
{ heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
Any ideia of how to implement it in Angularjs?
I saw some examples but I didn't get with that, I guess the most releant is this.
Using a CSV parsing library would probably be best. I've used Papa Parse before and it worked great. However, if you want to do it yourself...
function csvToArray(csvString) {
var lines = csvString.split('\n');
var headerValues = lines[0].split(',');
var dataValues = lines.splice(1).map(function (dataLine) { return dataLine.split(','); });
return dataValues.map(function (rowValues) {
var row = {};
headerValues.forEach(function (headerValue, index) {
row[headerValue] = (index < rowValues.length) ? rowValues[index] : null;
});
return row;
});
}
var x = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2";
console.log(csvToArray(x));
// OUTPUT
// [ { heading1: 'value1_1',
// heading2: 'value2_1',
// heading3: 'value3_1',
// heading4: 'value4_1',
// heading5: 'value5_1' },
// { heading1: 'value1_2',
// heading2: 'value2_2',
// heading3: 'value3_2',
// heading4: 'value4_2',
// heading5: 'value5_2' } ]

Resources