Skip to content

marcelocorreia/go-template-engine

Repository files navigation

go-template-engine


LOGO

shield shield shield Go Report Card

Easy tool to apply Go Templates in BAU jobs.

Based on Golang templates text SDK.

TLDR;

  • Install
    • Mac OS X
      • $ brew tap marcelocorreia/homebrew-taps; brew install go-template-engine
    • Other Platforms
    • Docker way
      • cmd $ docker run --rm -it -v $\(pwd\):/app -w /app marcelocorreia/go-template-engine\"
      • alias $ alias go-template-engine="docker run --rm marcelocorreia/go-template-engine"
      • automated_alias_install $ curl -L https://github.com/marcelocorreia/go-template-engine/releases/download/{REPLACE_WITH_LASTEST_VERSION}/docker-alias-install.sh | sh
  • Added support AWS Secrets Manager
    • Supports field Lookup
    • Tags
      • {{ secretsManagerField "myJsonSecret" "username"}}
      • {{ secretsManagerField "myJsonSecret" "password"}}
      • {{ secretsManager "myOtherSecret" }}
  • Added support to HCL formart for variables file input
  • Added support to all Masterminds Sprig functions
  • Added static file include. Tag {{staticInclude "path/to/file.txt"}}
  • Added replace tag. Tag {{replace .var "FROM_THIS" "TO_THIS"}}
  • Accepts JSON and YAML variables files
  • Lookup on file extension and parses accordingly, accepts .json .yml .yaml extensions
  • Custom variable delimeter can be set using flags. Default: {{ , }}. Left and Right respectively. Check help menu.
  • If --source points to a directory, it will run recursively, keeping the directory structure. Good for scaffolding
  • Accepts multiple variables files, merging them. YAML only. (It will override duplicated variables if the exits in more than one file)
  • These examples are pretty vanilla, go templates are actually pretty powerful, check the links for more info.
  • Can be extended
    • $> go get github.com/marcelocorreia/go-template-engine/template-engine

Custom functions

Function Source Desc
secretsManager GTE na
secretsManagerField GTE na
abbrev spring na
abbrevboth spring na
add spring na
add1 spring na
ago spring na
append spring na
atoi spring na
b32dec spring na
b32enc spring na
b64dec spring na
b64enc spring na
base spring na
biggest spring na
buildCustomCert spring na
camelcase spring na
cat spring na
ceil spring na
clean spring na
coalesce spring na
compact spring na
contains spring na
date spring na
dateInZone spring na
dateModify spring na
date_in_zone spring na
date_modify spring na
default spring na
derivePassword spring na
dict spring na
dir spring na
div spring na
empty spring na
env spring na
expandenv spring na
ext spring na
fail spring na
first spring na
float64 spring na
floor spring na
genCA spring na
genPrivateKey spring na
genSelfSignedCert spring na
genSignedCert spring na
has spring na
hasKey spring na
hasPrefix spring na
hasSuffix spring na
hello spring na
htmlDate spring na
htmlDateInZone spring na
indent spring na
initial spring na
initials spring na
int spring na
int64 spring na
isAbs spring na
join spring na
keys spring na
kindIs spring na
kindOf spring na
last spring na
list spring na
lower spring na
max spring na
merge spring na
min spring na
mod spring na
mul spring na
nindent spring na
nospace spring na
now spring na
omit spring na
pick spring na
pluck spring na
plural spring na
prepend spring na
push spring na
quote spring na
randAlpha spring na
randAlphaNum spring na
randAscii spring na
randNumeric spring na
regexFind spring na
regexFindAll spring na
regexMatch spring na
regexReplaceAll spring na
regexReplaceAllLiteral spring na
regexSplit spring na
repeat spring na
replace GTE na
rest spring na
reverse spring na
round spring na
semver spring na
semverCompare spring na
set spring na
sha1sum spring na
sha256sum spring na
shuffle spring na
snakecase spring na
sortAlpha spring na
split spring na
splitList spring na
squote spring na
staticInclude GTE na
sub spring na
substr spring na
swapcase spring na
ternary spring na
title spring na
toDate spring na
toJson spring na
toPrettyJson spring na
toString spring na
toStrings spring na
trim spring na
trimAll spring na
trimPrefix spring na
trimSuffix spring na
trimall spring na
trunc spring na
tuple spring na
typeIs spring na
typeIsLike spring na
typeOf spring na
uniq spring na
unset spring na
until spring na
untilStep spring na
untitle spring na
upper spring na
uuidv4 spring na
without spring na
wrap spring na
wrapWith spring na

Options

$> go-template-engine --help
  usage: go-template-engine --source=SOURCE [<flags>]

  Flags:
        --help                   Show context-sensitive help (also try --help-long and --help-man).
    -s, --source=SOURCE          Template Source File
        --var=VAR ...            Params & Variables. Example --var hey=ho --var lets=go
        --var-file=VAR-FILE ...  Variables File
        --exclude-dir=EXCLUDE-DIR ...
                                 Variables File
    -o, --output=OUTPUT          File output full path
        --delim-left="{{"        Left Delimiter
        --delim-right="}}"       Right Delimiter
    -v, --version                App Version

Usage

files in the examples are located at template-engine/test_fixtures/

$> go-template-engine --source template-engine/test_fixtures/cfn.tpl.yml \
        --var-file template-engine/test_fixtures/cfn-vars.yml \
        --output cfn.yml

$> go-template-engine --source template-engine/test_fixtures/cfn.tpl.yml \
        --var-file template-engine/test_fixtures/cfn-vars.json \
        --output cfn.yml

Install

Mac OS

$> brew tap marcelocorreia/homebrew-taps
   brew install go-template-engine

Other Systems Download latest binary from https://github.com/marcelocorreia/go-template-engine/releases

Docker

$ docker run --rm marcelocorreia/go-template-engine ...

Examples

Simple CFN Template

AWSTemplateFormatVersion: 2010-09-09
Description: VPC's sample

Resources: {{range .network.vpcs}}{{$vpc_name := .name}}
  {{.name}}:
    Type: 'AWS::EC2::VPC'
    Properties:
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      CidrBlock: {{.cidr}}
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'
{{range .subnets}}
  {{.name}}:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref {{$vpc_name}}
      CidrBlock: {{.cidr}}
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'
{{end}}{{end}}
Outputs: {{range .network.vpcs}}
  {{.name}}:
    Description: VPC ID of {{.name}}
    Value: !Ref {{.name}}
{{range .subnets}}
  PrivateSubnet:
    Description: Subnet ID of {{.name}}
    Value: !Ref {{.name}}
{{end}}
{{end}}

YAML Variables

network:
  vpcs:
    - name: VPCA
      cidr: 10.11.0.0/16
      subnets:
        - name: SubnetA1
          cidr: 10.11.1.0/24
        - name: SubnetA2
          cidr: 10.11.2.0/24
    - name: VPCB
      cidr: 10.12.0.0/16
      subnets:
        - name: SubnetB1
          cidr: 10.12.1.0/24
        - name: SubnetB2
          cidr: 10.12.2.0/24

JSON Variables

{
  "network": {
    "vpcs": [
      {
        "cidr": "10.11.0.0/16",
        "name": "VPCA",
        "subnets": [
          {
            "cidr": "10.11.1.0/24",
            "name": "SubnetA1"
          },
          {
            "cidr": "10.11.2.0/24",
            "name": "SubnetA2"
          }
        ]
      },
      {
        "cidr": "10.12.0.0/16",
        "name": "VPCB",
        "subnets": [
          {
            "cidr": "10.12.1.0/24",
            "name": "SubnetB1"
          },
          {
            "cidr": "10.12.2.0/24",
            "name": "SubnetB2"
          }
        ]
      }
    ]
  }
}

Output

AWSTemplateFormatVersion: 2010-09-09
Description: VPC's sample

Resources:
  VPCA:
    Type: 'AWS::EC2::VPC'
    Properties:
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      CidrBlock: 10.11.0.0/16
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

  SubnetA1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPCA
      CidrBlock: 10.11.1.0/24
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

  SubnetA2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPCA
      CidrBlock: 10.11.2.0/24
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

  VPCB:
    Type: 'AWS::EC2::VPC'
    Properties:
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      CidrBlock: 10.12.0.0/16
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

  SubnetB1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPCB
      CidrBlock: 10.12.1.0/24
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

  SubnetB2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPCB
      CidrBlock: 10.12.2.0/24
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackName'

Outputs:
  VPCA:
    Description: VPC ID of VPCA
    Value: !Ref VPCA

  PrivateSubnet:
    Description: Subnet ID of SubnetA1
    Value: !Ref SubnetA1

  PrivateSubnet:
    Description: Subnet ID of SubnetA2
    Value: !Ref SubnetA2


  VPCB:
    Description: VPC ID of VPCB
    Value: !Ref VPCB

  PrivateSubnet:
    Description: Subnet ID of SubnetB1
    Value: !Ref SubnetB1

  PrivateSubnet:
    Description: Subnet ID of SubnetB2
    Value: !Ref SubnetB2

Static Include

---
list:
{{staticInclude "test_fixtures/list1.txt"}}
Result
---
list:
  - hey
  - ho
  - lets
  - go

whatever else...

# {{.package_name}}

{{.phrase1}}
{{.phrase1}}

They're forming in a straight line
They're going through a tight wind
The kids are losing their minds
The Blitzkrieg Bop

They're piling in the back seat
They're generating steam heat
Pulsating to the back beat
The Blitzkrieg Bop.

{{.phrase1}}
Shoot'em in the back now
What they want, I don't know
They're all reved up and ready to go

{{.the.end}}
package_name: Blitzkrieg Bop
phrase1: Hey ho, let's go
the: {end: Tommy & Dee Dee Ramone}
# Blitzkrieg Bop

Hey ho, let's go
Hey ho, let's go

They're forming in a straight line
They're going through a tight wind
The kids are losing their minds
The Blitzkrieg Bop

They're piling in the back seat
They're generating steam heat
Pulsating to the back beat
The Blitzkrieg Bop.

Hey ho, let's go
Shoot'em in the back now
What they want, I don't know
They're all reved up and ready to go

Tommy & Dee Dee Ramone

Simple vars passed on call

$> go-template-engine --source template-engine/test_fixtures/simple.txt.tpl \
    --var easy=simple \
    --var who=we

Development

$> go get github.com/marcelocorreia/go-template-engine/template-engine
var engine template_engine.Engine
engine = template_engine.TemplateEngine{}
file, _ := ioutil.ReadFile("test_fixtures/bb.json")
var varsJson interface{}
json.Unmarshal(file, &varsJson)
outJson, _ := engine.ParseTemplateFile("test_fixtures/bb.txt.tpl", varsJson)

TODO's

  • Accept multiple variable files
  • Recursive processing
  • Custom Delimeters
  • Static Include tag
  • Replace tag
  • Extra functions(tons.... thanks to Masterminds Spring


🔨Created with a Hammer🔨