Multiline YAML Values to ENV Conversion
Learn how to handle YAML multiline strings (literal and folded blocks) when converting to ENV format. Covers escaping strategies, quoting rules, and newline preservation.
Detailed Explanation
Multiline values are one of the trickiest aspects of YAML-to-ENV conversion. YAML supports elegant multiline string formatting with literal (|) and folded (>) block scalars, but ENV files are line-oriented -- each line is a separate variable.
YAML with multiline values:
ssl_cert: |
-----BEGIN CERTIFICATE-----
MIIBxTCCAWugAwIBAgIJALP2kEZ0gN3vMA
oGCCqGSM49BAMCMDkxCzAJBgNVBAYTAlVT
-----END CERTIFICATE-----
welcome_message: >
Welcome to our application.
Please read the documentation
before getting started.
query: |
SELECT u.name, u.email
FROM users u
WHERE u.active = true
ORDER BY u.created_at DESC;
ENV conversion strategy 1: Escaped newlines in double quotes
SSL_CERT="-----BEGIN CERTIFICATE-----\nMIIBxTCCAWugAwIBAgIJALP2kEZ0gN3vMA\noGCCqGSM49BAMCMDkxCzAJBgNVBAYTAlVT\n-----END CERTIFICATE-----"
WELCOME_MESSAGE="Welcome to our application. Please read the documentation before getting started."
QUERY="SELECT u.name, u.email\nFROM users u\nWHERE u.active = true\nORDER BY u.created_at DESC;"
ENV conversion strategy 2: Single quotes with actual newlines
SSL_CERT='-----BEGIN CERTIFICATE-----
MIIBxTCCAWugAwIBAgIJALP2kEZ0gN3vMA
oGCCqGSM49BAMCMDkxCzAJBgNVBAYTAlVT
-----END CERTIFICATE-----'
How each YAML block style affects the output:
Literal block (
|) preserves every newline. Each line break becomes\nin the ENV value. This is critical for certificates, SSH keys, and SQL queries where line breaks matter.Folded block (
>) joins lines with spaces, producing a single-line value. This is simpler for ENV conversion since the result is naturally a single line.Chomping modifiers (
|-,|+,>-,>+) control trailing newlines.|-strips the final newline (usually what you want for ENV values), while|+keeps all trailing newlines.
Compatibility concerns:
- Docker/docker-compose supports multi-line ENV values with escaped newlines in double quotes.
- systemd environment files do NOT support multi-line values at all.
- dotenv libraries vary: Node.js dotenv supports multi-line in double quotes, Python dotenv supports them in both quote styles.
- Shell
exportsupports$'...'syntax with literal\non Bash, but not all shells.
Recommendation: For maximum portability, use escaped \n within double-quoted values. For certificates and keys, consider Base64-encoding the entire value instead.
Use Case
Storing SSL certificates, SSH private keys, or multi-line SQL queries as environment variables in a Docker container, converting them from a YAML-based secrets management system.