Using shell script to parse lines from a consul template file

977 views Asked by At

As you can see the in the template file below , I have few variables declared (like MYSQL_ACCOUNT_PASSWORD , MYSQL_ACCOUNT_USERNAME etc) between "if" and "end" and I am looking forward to write a shell script to get all the variables in such file.

With the format of the consul template using "Golang's text/template package", I am afraid that basic tools like cut,sed or awk wont do my job. How can I do this.

{{- template "findService" "mysql-master-acc" }}
{{- if scratch.Key "mysql-master-acc-service" }}
{{-   $mysql_account_db_name := printf "service/%s/mysql-master-acc/%s/config/acc_mysql_db_name" $dc ( scratch.Get "mysql-master-acc-tag" ) | key }}
{{    range scratch.Get "mysql-master-acc-service"}}
MYSQL_ACCOUNT_URL=jdbc:mysql://{{- .Address }}:{{- .Port }}/{{ $mysql_account_db_name }}?useSSL=false&autoReconnect=true&serverTimezone=America/Chicago&rewriteBatchedStatements=true
{{-   end }}
{{-   if eq (env "SECRETS_BACKEND") "vault" }}
{{      $vault_secret_path := printf "secret/service/%s/kos-mysql-acc/%s" $dc ( scratch.Get "mysql-master-acc-tag" ) -}}
{{      with printf "%s/%s" $vault_secret_path $mysql_account_db_name | secret -}}
MYSQL_ACCOUNT_PASSWORD={{ .Data.password }}
MYSQL_ACCOUNT_USERNAME={{ .Data.username }}
{{-     end }}
{{-   else if eq ( env "SECRETS_BACKEND" ) "consul" }}
{{-     $secretPath := printf "secret/%s/mysql-master-acc/%s/acc_mysql_db_user_password" $dc ( scratch.Get "mysql-master-acc-tag" ) }}
{{-     $keyPath := printf "service/%s/mysql-master-acc/%s/config/acc_mysql_db_user" $dc ( scratch.Get "mysql-master-acc-tag" ) }}
MYSQL_ACCOUNT_PASSWORD={{ key $secretPath }}
MYSQL_ACCOUNT_USERNAME={{ key $keyPath }}
{{-   end }}
{{- end }}
1

There are 1 answers

0
TCulp On

Could you just use grep?

To get all lines that don't start with {{ you could use

grep -v "^{{" inputfile

If you want all lines starting with MYSQL..., use

grep "^MYSQL" inputfile

In this case, these both return:

MYSQL_ACCOUNT_URL=jdbc:mysql://{{- .Address }}:{{- .Port }}/{{ $mysql_account_db_name }}?useSSL=false&autoReconnect=true&serverTimezone=America/Chicago&rewriteBatchedStatements=true
MYSQL_ACCOUNT_PASSWORD={{ .Data.password }}
MYSQL_ACCOUNT_USERNAME={{ .Data.username }}
MYSQL_ACCOUNT_PASSWORD={{ key $secretPath }}
MYSQL_ACCOUNT_USERNAME={{ key $keyPath }}