Reputation: 79
I am hoping someone can help me with some text manipulation, it's not my strong point and I'm coming up against an issue when trying to replace text in a file.
I have a Terraform file, what I wish to do is run a BASH script which collects user input and fills in the Terraform file. The format is as follows:
Terraform.tf
variable "master_cpu" {default = }
variable "master_mem" {default = }
variable "master_count" {default = }
variable "master_template" {default = ""}
variable "master_datastore" {default = ""}
variable "master_secondary_disk_size" {default = }
variable "master_network_label" {default = ""}
variable "master_gateway" {default = ""}
variable "master_netmask" {default = ""}
Provisioner.sh
echo -n "How many vCPU's should these VM's have? [ENTER]:"
read master_cpu
echo -n "How much RAM would you like to allocate? [ENTER]:"
read master_ram
echo -n "Template name? Format: Folder/template [ENTER]:"
read master_template
echo -n "Please provide the datastore name. [ENTER]:"
read master_dstore
...
There are 2 issues here, first one is numbers aren't wrapped in double quotes but text is, so simply searching for default = "" in the Terraform file is of no use.
The other issue I've faced is with variables not expanding, for example:
awk '{gsub("default = \"\"", "default = \"$vc_address\"", $0); print > FILENAME}' terraform.tf
Will produce: default = "$vc_address" and not use the IP captured on the command line.
If anyone could give me some pointers on how to efficiently do this in BASH, for both numbers and text I'd be really grateful.
Upvotes: 0
Views: 1212
Reputation: 1199
What you want is a template engine, and this can be achieved using bash here-doc:
#!/bin/bash
echo -n "How many vCPU's should these VM's have? [ENTER]:"
read master_cpu
echo -n "How much RAM would you like to allocate? [ENTER]:"
read master_ram
echo -n "Template name? Format: Folder/template [ENTER]:"
read master_template
echo -n "Please provide the datastore name. [ENTER]:"
read master_dstore
# Use heredoc to generate the file, use EOF and not "EOF" since we want bash substitution
cat > Terraform.tf << EOF
variable "master_cpu" {default = $master_cpu}
variable "master_mem" {default = $master_ram}
variable "master_count" {default = }
variable "master_template" {default = ""}
variable "master_datastore" {default = ""}
variable "master_secondary_disk_size" {default = }
variable "master_network_label" {default = ""}
variable "master_gateway" {default = ""}
variable "master_netmask" {default = ""}
EOF
You can read more about heredoc here: http://tldp.org/LDP/abs/html/here-docs.html
As for variables not expanding, there's a difference between ' and " in bash. Basically ' means literal (do not expand). See bash manual for:
Upvotes: 1