Hello BoltOps Community,
I managed to figure out how to use a helper function/method/module to read e.g. a JSON file for input and generate terraform code using ERB templating. I am wondering if we are able to store the output from terraform back into the JSON file?
Here’s an example use case…
Let’s say I have this data populated in config/vpc_config.json
{
"network": {
"vpcs": {
"main": {
"name": "main",
"vpc_cidr": "10.98.20.0/22",
"subnets": {
"public": {
"az1": {
"subnet_type": "external",
"subnet_name": "public",
"subnet_az" : "1",
"subnet_cidr": "10.98.20.0/26"
},
"az2": {
"subnet_type": "external",
"subnet_name": "public",
"subnet_az" : "2",
"subnet_cidr": "10.98.20.64/26"
}
},
"private": {
"az1": {
"subnet_type": "internal",
"subnet_name": "private",
"subnet_az" : "1",
"subnet_cidr": "10.98.21.0/26"
},
"az2": {
"subnet_type": "internal",
"subnet_name": "private",
"subnet_az" : "2",
"subnet_cidr": "10.98.21.64/26"
}
},
"database": {
"az1": {
"subnet_type": "internal",
"subnet_name": "database",
"subnet_az" : "1",
"subnet_cidr": "10.98.22.0/26"
},
"az2": {
"subnet_type": "internal",
"subnet_name": "database",
"subnet_az" : "2",
"subnet_cidr": "10.98.22.64/26"
}
}
}
}
}
}
}
In my helper file, I have
require 'json'
module Terraspace::Project::CustomHelpers
def vpc_config_file
"config/vpc_config.json"
end
def vpc_data
file = File.read(vpc_config_file)
data_hash = JSON.parse(file)
end
end
In my vpc.tf
file, I am creating a VPC. e.g.
resource "aws_vpc" "vpc" {
cidr_block = <%= vpc_data['network']['vpcs']['main']['vpc_cidr'] %>
}
Now, I would like to store the value of the vpc_id
(which is only known after the VPC is created) in config/vpc_config.json
.
I know I can update the config/vpc_config.json
by using a method like below
def vpc_id_writeback(vpc, vpcid)
data_hash = read_json(vpc_config_file)
data_hash['network']['vpcs'][vpc]['vpc_id']=vpcid
File.write(vpc_config_file, JSON.pretty_generate(data_hash))
end
But I guess, where I’m coming from is… The ERB templating in the .tf files are applied during the generation of .tf files (when we do terraspace build
)… Whereas, the value of vpc_id is only known after we run terraspace up
…
I understand that we would also be able to query the vpc_id
through the use of terraform’s data "aws_vpc"
(without having to store the information in the JSON file), but am still interested to know if we’d be able to store the information back into the JSON file - just thinking that if we have to deal with multiple VPCs/looping, it might be easier to loop through using ERB template over terraform’s loop
Many thanks,
James