Terminal - envsubst command
Contents
About
envsubst is a command-line utility in Unix-like operating systems, part of the GNU gettext package, designed for substituting environment variable values in text files. It reads from standard input or a file, replaces references to environment variables with their current values, and writes to standard output.
envsubst [option] [shell-format]
Usage and Examples
Basic Example
Given a file template.txt with the content:
- Hello, my name is $NAME.
You can replace $NAME with the actual name by setting the environment variable and using envsubst like so:
export NAME=John envsubst < template.txt
The output will be:
- Hello, my name is John.
Multiple Variables
Consider template.txt containing:
- $GREETING, my name is $NAME.
To replace both variables, use:
export GREETING=Hello export NAME=Jane envsubst < template.txt
Resulting in:
- Hello, my name is Jane.
Using envsubst with .yaml Files
envsubst is particularly useful for dynamically generating .yaml files, like those used in Kubernetes and Tilt, based on different environments.
Example with Kubernetes Deployment YAML
A template file, backend.yaml.template, might look like:
apiVersion: apps/v1 kind: Deployment metadata: name: myapp-$ENVIRONMENT spec: replicas: 3 # ... other configurations ...
Set the environment variable and generate the deployment file:
export ENVIRONMENT=dev envsubst < backend.yaml.template > backend.yaml
This will create backend.yaml with the deployment name myapp-dev.
Integration with Tiltfile
To integrate with Tilt, use the following in your Tiltfile:
local('export ENVIRONMENT=dev && envsubst < backend.yaml.template > backend.yaml') k8s_yaml('backend.yaml')
This script sets the environment, and generates the backend.yaml file, and instructs Tilt to deploy using the generated file. WARNING: Great in theory, but I've never got it working successfully as tilt has several things it tends to complain about.
Conclusion
envsubst is versatile for scenarios requiring dynamic text generation, particularly in configuration management and deployment automation in cloud-native environments. Its use with tools like Tilt enhances its utility in modern development workflows.