Boilerplate Templates
Gruntwork Boilerplate generates files and folders from templates. Runbooks takes two things from it: the boilerplate.yml schema that <Inputs> and <Template> build their forms from, and the Go template syntax that <Template>, <TemplateInline>, <Command>, and <Check> render.
This page covers the parts of Boilerplate that runbook authors use. The Boilerplate repo has the complete documentation.
Boilerplate in a nutshell
Section titled “Boilerplate in a nutshell”Boilerplate is a template engine, similar to Jinja, Nunjucks, or Cookiecutter.
Why Boilerplate
Section titled “Why Boilerplate”Boilerplate is built for DevOps and infrastructure work:
- As a CLI, it prompts for the variables defined in
boilerplate.yml, or takes them from command-line options so it can run in automated tests. - Templates are Go templates, with conditionals, loops, and helpers for loading another file, running a shell command (off in Runbooks; see Helper functions), and including partial templates.
- A template can depend on other templates and include them conditionally on variable values.
- Variables are typed and can have validations.
- Hooks run arbitrary scripts.
- It is a standalone binary for macOS, Linux, and Windows.
Quick example
Section titled “Quick example”Say you want to generate a README for new projects. Create a template folder:
Directorymy-template/
- boilerplate.yml
- README.md
boilerplate.yml defines the variables:
variables: - name: ProjectName type: string description: Name of the project
- name: Author type: string description: Who is the author? default: AnonymousREADME.md is the template file:
# {{ .ProjectName }}
Created by {{ .Author }}.Run Boilerplate on the command line:
boilerplate \ --template-url ./my-template \ --output-folder ./output \ --var ProjectName="My Cool App" \ --var Author="Jane Doe"The result is output/README.md:
# My Cool App
Created by Jane Doe.The boilerplate.yml file
Section titled “The boilerplate.yml file”Every template directory needs a boilerplate.yml file that defines its variables. Runbooks renders a form from it.
Basic structure
Section titled “Basic structure”variables: - name: ProjectName type: string description: What would you like to call your project? default: my-project validations: - required
- name: Environment type: enum description: Which environment is this for? options: - dev - staging - prod default: devThis generates a form with a text input for ProjectName and a dropdown for Environment.
Variable properties
Section titled “Variable properties”Each variable supports these properties:
| Property | Required | Description |
|---|---|---|
name |
Yes | Variable name, referenced as {{ .inputs.Name }}, or as {{ .Name }} in the files a <Template> renders |
type |
No | Data type: string, int, float, bool, enum, list, map (defaults to string). Write it in lowercase. The form shows a field of any other type as text, but Boilerplate rejects it, so a <Template> that uses it fails |
description |
No | Help text shown under the field. It can use markdown. See Field descriptions |
default |
No | Default value. Once a field’s value differs from it, a Reset button next to the field’s name puts it back |
options |
For enum |
The dropdown’s options: a list, or a block output that holds one. See Options |
validations |
No | Validation rules |
sensitive |
No | For a string, masks the field like a password input, with a button to show the value |
order |
No | An integer that places the field in the form, lowest first. See Field order |
Field descriptions
Section titled “Field descriptions”A field’s description is markdown. It can use bold, italic, code, links, line breaks, and bulleted or numbered lists. A YAML block scalar (description: |) keeps its line breaks, so a list can be written as one:
variables: - name: SubscriptionLayout type: enum options: [single, caf] description: | How many subscriptions the platform uses: - **single**: one subscription for everything. - **caf**: four subscriptions, as Microsoft's [Cloud Adoption Framework](https://learn.microsoft.com/azure/cloud-adoption-framework/ready/landing-zone/) recommends.Links open in your browser. A description shows in the same small, muted text whether it uses markdown or not, so a one-line description without any looks as it always has.
Only that markdown renders. HTML, such as <name>, shows as you wrote it, and so does a line that markdown would make a heading, quote, horizontal rule or code block. Images are left out.
Field order
Section titled “Field order”The form shows fields in the order boilerplate.yml declares them. To place a field elsewhere, give it an order, the integer Boilerplate also prompts for variables by. Fields appear lowest order first, a variable without one counts as 0, and fields with the same order keep the order they’re declared in:
variables: - name: Region type: string default: us-east-1
- name: AccountName type: string order: -1
- name: Tags type: map default: {} order: 10This form shows Account Name, then Region, then Tags.
In a form with sections, order sorts the fields within each section, and a section appears where its first field would. Fields without an x-section stay at the top.
Defaults that use other variables
Section titled “Defaults that use other variables”A default can use other variables, with the same template syntax as your template files:
variables: - name: ProjectName type: string default: acme
- name: Environment type: enum options: [dev, prod] default: dev
- name: BucketName type: string default: "{{ .ProjectName }}-state"
- name: InstanceSize type: string default: '{{ if eq .Environment "prod" }}large{{ else }}small{{ end }}'
- name: CatalogRepositories type: list default: - github.com/gruntwork-io/terraform-aws-service-catalog - "github.com/{{ .ProjectName }}/modules"
- name: DefaultTags type: map default: "{{ .ProjectName }}:Team": DevOpsRunbooks fills these in, using whatever the other fields hold at that moment, in two places: when it renders the body of a <Template> or <TemplateInline> block, and when a <Command> or <Check> script reads the variable through inputsId.
Other block props that use the variable through {{ .inputs.X }}, like <GitClone>’s prefilledUrl or <TemplateInline>’s outputPath, get the expression as written, not the value it resolves to. Give those props a variable with a plain default.
The form doesn’t show the {{ }} syntax. It shows a linked default as its text, with a chip for each variable or block output it uses. A chip shows the value it links to, with a link icon, and follows that field as you edit it. Here BucketName shows an acme chip followed by -state. A default that does more than insert a variable or an output shows as one chip with the value it comes to, so InstanceSize shows small until you pick prod. In a <Template>, a default can also use the values the block gets through inputsId.
Until a chip’s value is known, it names what it links to instead: a variable, labelled the way its field is, or an output, as create_account.account_id. A chip for a default that does more says what it’s based on, like Based on Environment. A chip for a block output that hasn’t been produced yet is yellow; hover over it to see which block has to run first. If no block on the page has the id the default names, the value can never be filled in: the chip is red, the field shows an error, the block is red and won’t generate until you replace the value, and the error is counted in the runbook’s error summary.
A sensitive field shows one chip that names the variables its default uses, never its text or its value. A chip for a sensitive variable shows only its name, and one for a sensitive output shows <redacted>.
To change a linked value:
- Enter a value for a chip. Click the chip and it turns into a field, in its place, where you can type another value. Press Enter, or click away after changing it, to use it. Press Escape to get the chip back. The field then uses that value everywhere it used the chip’s variable or output, and the rest stays linked. A value entered for an output means the field no longer waits for, or needs, the block that produces it.
- Reset goes back to the link. A value you entered stays in its field, where you can change it, with a reset button next to it that brings the chip back.
- Click the X to clear the whole value and type your own.
- Click Reset next to the field’s name to go back to the default, as the runbook wrote it, chips and all.
- Hover over the value to see its expression.
A value you enter for a sensitive field, variable or output is hidden as you type it. A resumed session brings back the values you entered.
The template-defaults demo runbook uses each kind.
Variable types
Section titled “Variable types”string
Section titled “string”Text input field.
- name: BucketName type: string description: Name for the S3 bucket default: my-bucketNumeric input field.
- name: InstanceCount type: int description: Number of instances to deploy default: 3Numeric input field that accepts decimals.
- name: ScalingThreshold type: float description: CPU utilization that triggers scaling default: 0.75Checkbox toggle. Without a default, the checkbox starts unchecked, which is the value false.
- name: EnableLogging type: bool description: Enable CloudWatch logging? default: trueDropdown select from predefined options. Without a default, the dropdown starts empty and the variable has no value until the user picks one. With the required validation, the form asks for a pick before it can be submitted. Boilerplate itself needs a value for every variable without a default, so give an optional enum a default ("" works if "" is one of the options).
- name: Region type: enum description: AWS region for deployment options: - us-east-1 - us-west-2 - eu-west-1 default: us-east-1Options
Section titled “Options”An option is a string, shown and stored as it is, or, from Runbooks 0.31, a value with a label, shown as its label and stored as its value. A list can mix the two:
- name: InstanceSize type: enum options: - value: small label: Small (2 vCPU, 4 GiB) - value: large label: Large (8 vCPU, 32 GiB) - xlarge default: smallTemplates get the value, so {{ .InstanceSize }} renders small. Labels work the same way in a list’s x-options, where the picker’s search matches both labels and values.
Options from a block’s output
Section titled “Options from a block’s output”When the options live somewhere that changes, such as the regions a cloud account can use, a script can list them and the field can read them. Write the options as a reference to a block’s output, instead of a list:
- name: Location type: enum options: "{{ fromJson .outputs.list_regions.regions }}" default: eastusThe output must be a JSON array of options: strings, { "value": ..., "label": ... } objects, or both. A <Command> with the id list-regions could write it like this:
echo 'regions=[{"value":"eastus","label":"East US"},{"value":"westus2","label":"West US 2"}]' >> "$RUNBOOK_OUTPUT"The reference is {{ fromJson .outputs.<block_id>.<output_name> }} or {{ .outputs.<block_id>.<output_name> }}, alone. The field then behaves like a default that uses a block output:
- Until the block has run, the field says it’s waiting for that block, with a link to it, and the block’s Generate or Submit button stays disabled. When the block runs again with another list, the options follow.
- A value that isn’t one of the options, such as a
defaultthe list doesn’t have, is an error on the field until you pick one that is. - If the output isn’t a JSON array of options, the field shows an error that names the block and the output. A sensitive output can’t be shown as options, so it’s an error too.
- If no block on the page has the id, the field shows an error and the block is red, as for a default.
A <Template> renders with the Boilerplate CLI, which takes only a list of strings as options. Runbooks checks the value against the options, then gives Boilerplate the field as a string and labelled options as their values, so the template renders the same way. The Boilerplate CLI on its own can’t render a template whose options come from an output. runbooks test reads the output once the block that produces it has run, and fails the test if an input isn’t one of the options.
The output-options demo runbook has a dropdown and a multi-select picker that read a script’s output.
List of values. Users can add and remove items.
- name: AllowedIPs type: list description: IP addresses to allow default: []Key-value pairs. Users can add and remove entries.
- name: Tags type: map description: Resource tags default: {}For structured values, see x-schema.
Validations
Section titled “Validations”Add validation rules to a variable:
- name: ProjectName type: string validations: - required
- name: ContactEmail type: string validations: - email
- name: WebsiteURL type: string validations: - url
- name: Identifier type: string validations: - alphanumeric
- name: CountryCode type: string validations: - countrycode2
- name: Version type: string validations: - semver
- name: ManyValidations type: string validations: - "required" - "email"Custom error messages
Section titled “Custom error messages”Use the object form with type and message:
variables: - name: Email type: string validations: - type: required message: Email is required - type: email message: Must be a valid email addressOnly an <Inputs> block’s boilerplate.yml can use this form. Boilerplate itself accepts only the string form, so a <Template> whose boilerplate.yml uses the object form fails with “validation rule at index 0 must be a string”.
Validation types
Section titled “Validation types”| Validation | Description |
|---|---|
required |
Field cannot be empty |
email |
Must be a valid email address |
url |
Must be a valid URL |
alpha |
Only letters allowed (no numbers or special characters) |
digit |
Only digits allowed (0-9) |
alphanumeric |
Only letters and numbers allowed |
countrycode2 |
Must be a valid two-letter country code (ISO 3166-1 alpha-2) |
semver |
Must be a valid semantic version (e.g., 1.0.0, 2.1.3-beta) |
length(min, max) |
Value must be between min and max characters long |
regex("pattern") |
Value must match the given regular expression pattern |
Parameterized validations
Section titled “Parameterized validations” - name: ProjectSlug type: string validations: - regex("^[a-z][a-z0-9-]+$")
- name: Description type: string validations: - length(0, 256)The form checks these rules as you type and shows the one a value breaks on the field, with a message such as “Must be 1 to 64 characters long” or “Must match ^[a-z][a-z0-9-]+$”. Generate and Submit stay blocked until the value passes. runbooks test checks the values it sets the same way.
length(min, max)counts bytes, as Boilerplate does, so a character such asécounts as two. On alistit counts the items, and on amapthe entries. A bound of0sets no limit.regex(...)takes the pattern in double quotes, where\"is a quote and\\a backslash and other backslashes are kept, so\dworks as written. In backticks, as inregex(`^"[a-z]+"$`), the pattern is taken as is. The pattern uses Go’s syntax and matches anywhere in the value, so add^and$to match all of it.- A malformed rule, such as
length(5, 1), or a pattern Go can’t compile, such as one with a lookahead, is reported as an error in the block.
In an <Inputs> block, the object form can give either rule its own message:
validations: - type: regex("^[a-z0-9]{3,24}$") message: Use 3 to 24 lowercase letters and digitsTemplate syntax
Section titled “Template syntax”Template files use Go template syntax. In the files a <Template> renders, reference a variable from boilerplate.yml with dot notation, as in {{ .BucketName }}, or as {{ .inputs.BucketName }}. Everywhere else in a runbook, such as a <TemplateInline> template, a <Command> or <Check> script, or a block’s props, only {{ .inputs.BucketName }} works. See Inputs and outputs.
Variable substitution
Section titled “Variable substitution”resource "aws_s3_bucket" "main" { bucket = "{{ .BucketName }}-{{ .Environment }}"}Conditionals
Section titled “Conditionals”{{- if .EnableLogging }}resource "aws_cloudwatch_log_group" "main" { name = "/app/{{ .ProjectName }}"}{{- end }}Comparisons
Section titled “Comparisons”instance_type = "{{ if eq .Environment "prod" }}t3.large{{ else }}t3.micro{{ end }}"{{- range .AllowedIPs }} - {{ . }}{{- end }}tags = {{{- range $key, $value := .Tags }} {{ $key }} = "{{ $value }}"{{- end }}}Whitespace control
Section titled “Whitespace control”Use - to trim whitespace around template directives:
{{-trims whitespace before-}}trims whitespace after
{{- if .Description }}description = "{{ .Description }}"{{- end }}Helper functions
Section titled “Helper functions”Boilerplate includes helper functions for common transformations. With ProjectName set to my-project:
# String case transformations{{ .ProjectName | snakeCase }} # my_project{{ .ProjectName | camelCase }} # MyProject{{ .ProjectName | camelCaseLower }} # myProject{{ .ProjectName | dasherize }} # my-project{{ .ProjectName | upper }} # MY-PROJECT{{ .ProjectName | lower }} # my-project
# String checks{{ hasPrefix "prod" .Environment }} # true if starts with "prod"{{ hasSuffix "-dev" .Name }} # true if ends with "-dev"Runbooks turns off the shell helper. In a runbook, {{ shell "..." }} doesn’t run its command and gives replace-me instead. Boilerplate renders variable values as templates, including the values people type and the outputs of earlier blocks, so with shell on, a value could run a command. Run commands in a <Command> block, and pass what they produce to the template as a block output.
Dynamic file names
Section titled “Dynamic file names”File and folder names can use template syntax:
Directorytemplates/
- boilerplate.yml
{{ .ProjectName }}.tfDirectory
{{ .Environment }}/- config.yaml
With ProjectName: "vpc" and Environment: "prod", this generates:
- vpc.tf
Directoryprod/
- config.yaml
Runbooks extensions
Section titled “Runbooks extensions”Runbooks reads extra YAML properties, prefixed with x-, that change how the form renders. The Boilerplate CLI ignores them.
Together with order, they lay the form out for the person filling it in: x-section groups fields under headings, x-sections folds the groups they rarely need, x-locked and x-hidden keep them from changing values the runbook sets itself, and x-show-when shows a field only when it applies. The form-layout demo runbook uses each of the others.
x-section
Section titled “x-section”x-section groups fields under a named heading. This form renders two sections, Basic Settings and Advanced Settings:
variables: - name: FunctionName type: string x-section: Basic Settings
- name: Runtime type: enum options: [python3.12, nodejs20.x] x-section: Basic Settings
- name: MemorySize type: int default: 128 x-section: Advanced Settings
- name: Timeout type: int default: 30 x-section: Advanced SettingsVariables without x-section appear in an unnamed section at the top. The other sections follow in the order of their first field, which order can change.
x-sections
Section titled “x-sections”A top-level list of settings for the sections that x-section names. collapsed: true folds a section under its heading until someone clicks it open, so fields whose defaults rarely need changing stay out of the way:
x-sections: - name: Advanced Settings collapsed: true
variables: - name: FunctionName type: string x-section: Basic Settings
- name: MemorySize type: int default: 128 x-section: Advanced Settings
- name: Timeout type: int default: 30 x-section: Advanced SettingsThe fields of a folded section keep their values, and the block uses them as it does any other field’s. If one of them has an error, such as a required field that is still empty when you click Generate, the section opens to show it. So give the fields of a folded section defaults that work.
x-locked
Section titled “x-locked”x-locked: true shows a field read-only, marked (locked). Its value is the variable’s default, or in a <Template>, the value the block imports through inputsId. Nobody filling in the form can change it.
A locked default that uses other variables or block outputs still follows them. This field shows the provider that the <GitAuth> block with the id git-auth signed in to, from its GIT_PROVIDER output:
- name: GitProvider type: enum options: [github, gitlab] default: "{{ .outputs.git_auth.GIT_PROVIDER }}" x-locked: trueWhen a session is resumed, a locked field starts from the runbook’s value, not from the one the session saved, because the runbook may have changed it since. If a locked field’s value is invalid, for example because its default uses a block that isn’t on the page, the field shows the error, and the runbook itself has to be fixed.
x-hidden
Section titled “x-hidden”x-hidden: true leaves a field out of the form. A hidden field is locked too: the block uses its default, or the value it imports, as is. Use it for values the runbook works out by itself, such as the provider above when there’s no need to show it:
- name: GitProvider type: enum options: [github, gitlab] default: "{{ .outputs.git_auth.GIT_PROVIDER }}" x-hidden: trueA hidden field is still validated. If its value is invalid, for example because it’s required and empty, the form shows the field, locked, with its error, so the block never fails on something you can’t see. A section whose fields are all hidden doesn’t appear.
x-show-when
Section titled “x-show-when”x-show-when shows a field only while other fields have certain values. It maps each of those variables to a value, or to a list of values any of which matches. The field shows while every condition holds, and the form updates as you change the other fields.
In this form, Subscription Layout is single or caf. The identity subscription applies only to caf, so it shows only then:
- name: SubscriptionLayout type: enum options: [single, caf] default: single
- name: IdentitySubscriptionId type: string x-show-when: SubscriptionLayout: cafA list matches any of its values, and several conditions must all hold:
- name: FirewallSku type: enum options: [Standard, Premium] default: Standard x-show-when: SubscriptionLayout: [caf, custom] DeployFirewall: trueA value is compared as text, so true matches a checked bool, and a list with x-options matches when any of its selected values does.
While a field is hidden, the form doesn’t ask for it:
- It isn’t validated, so a
requiredfield doesn’t stop you generating. - The block uses its
default, not a value you entered before it was hidden. Without adefault, it gets an empty value:"",falsefor abool,0for a number, or an empty list or map. Boilerplate rejects anenumvalue that isn’t one of its options, so give a conditionalenumadefault. - A section whose fields are all hidden doesn’t appear.
If the field shows again, it has the value you entered. In instruction mode, each conditional field states when it applies, such as “Only when Subscription Layout is caf”. runbooks test does the same as the form: it skips validating a hidden field and gives it its default, whatever the test sets for it.
The block reports a configuration error for a condition that names a variable the form doesn’t have, gives a value that isn’t one of an enum’s options, or depends on itself through other conditions. The conditional-fields demo runbook shows x-show-when in a <Template> and an <Inputs> block.
x-options
Section titled “x-options”Lists the allowed values for a list variable. The form then renders a multi-select picker. The Boilerplate CLI doesn’t check the values against the list.
- name: Regions type: list description: Regions to deploy to x-options: - us-east-1 - us-west-2 - eu-west-1Like an enum’s options, an option can have a label, and the list can come from a block’s output:
- name: AllowedLocations type: list x-options: "{{ fromJson .outputs.list_regions.regions }}"The picker then waits for that block, and each value picked must be one of the options it output.
x-schema
Section titled “x-schema”A map variable collects key-value pairs where each value is a string. When each key needs several values, such as an email address, account ID, and name for each AWS account, give the map an x-schema. Runbooks then renders a structured form for each entry:
- name: AWSAccounts type: map description: AWS account configuration x-schema: email: string name: string id: stringEach map entry renders with those three fields. A field’s type sets its control: bool renders a true/false dropdown, int, float and number render a number input, and any other type renders a text input.
On a list variable, x-schema makes the list a fixed-length tuple. Its keys are the element positions, "0", "1" and so on, and its values are the element types, with the same controls as a map’s fields:
- name: Endpoint type: list description: Host and port x-schema: "0": string "1": intThe form renders one input per element, in position order.
x-schema-instance-label
Section titled “x-schema-instance-label”Sets the label for each entry of a schema-based map. It defaults to “Entry name”:
- name: AWSAccounts type: map description: AWS account configuration x-schema-instance-label: AWS Account Name x-schema: email: string environment: string id: stringAuthoring templates with the CLI
Section titled “Authoring templates with the CLI”You can run the Boilerplate CLI directly to test templates during development.
Install Boilerplate
Section titled “Install Boilerplate”# macOSbrew install gruntwork-io/tap/boilerplate
# Or download from GitHub releases# https://github.com/gruntwork-io/boilerplate/releasesGenerate files
Section titled “Generate files”boilerplate \ --template-url ./templates/vpc \ --output-folder ./output \ --var VpcName="my-vpc" \ --var Environment="dev"Interactive mode
Section titled “Interactive mode”Without --var flags, Boilerplate prompts for values interactively:
boilerplate \ --template-url ./templates/vpc \ --output-folder ./outputNon-interactive mode
Section titled “Non-interactive mode”Use --non-interactive with a vars file for CI/CD:
boilerplate \ --template-url ./templates/vpc \ --output-folder ./output \ --var-file vars.yml \ --non-interactiveExample template
Section titled “Example template”A template directory for a Lambda function:
Directorytemplates/
Directorylambda/
- boilerplate.yml
- main.tf
- variables.tf
- outputs.tf
boilerplate.yml:
variables: - name: FunctionName type: string description: Name for the Lambda function validations: - required x-section: Basic Settings
- name: Runtime type: enum description: Lambda runtime options: - python3.12 - nodejs20.x default: python3.12 x-section: Basic Settings
- name: MemorySize type: int description: Memory in MB (128-10240) default: 128 x-section: Advanced Settings
- name: EnableLogging type: bool description: Create CloudWatch log group? default: true x-section: Advanced Settings
- name: Tags type: map description: Resource tags default: {} x-section: Advanced Settingsmain.tf:
resource "aws_lambda_function" "main" { function_name = "{{ .FunctionName }}" runtime = "{{ .Runtime }}" memory_size = {{ .MemorySize }} handler = "index.handler" role = aws_iam_role.lambda.arn
tags = {{{- range $key, $value := .Tags }} {{ $key }} = "{{ $value }}"{{- end }} }}
{{- if .EnableLogging }}
resource "aws_cloudwatch_log_group" "lambda" { name = "/aws/lambda/{{ .FunctionName }}" retention_in_days = 14}{{- end }}Using templates in runbooks
Section titled “Using templates in runbooks”Reference a template directory from a runbook with <Template>:
# Deploy a Lambda Function
Configure your Lambda function below:
<Template id="lambda-config" path="templates/lambda" />
After generating, review the files in the file tree on the right.For a template that doesn’t need its own directory, pair <Inputs> with <TemplateInline>:
<Inputs id="config">```yamlvariables: - name: BucketName type: string```</Inputs>
<TemplateInline id="bucket-preview" inputsId="config" outputPath="bucket.tf">```hclresource "aws_s3_bucket" "main" { bucket = "{{ .inputs.BucketName }}"}```</TemplateInline>