Converting YAML Arrays and Lists to ENV Format
Learn different strategies for converting YAML arrays to environment variables. Covers indexed keys, comma-separated values, and JSON-encoded array patterns.
Detailed Explanation
YAML arrays present a unique challenge when converting to ENV format because environment variables are simple key-value strings with no native concept of ordered lists. Several strategies exist, each with trade-offs.
A YAML file with arrays:
app:
name: MyService
ports:
- 3000
- 3001
- 3002
allowed_hosts:
- localhost
- example.com
- "*.staging.example.com"
cors:
origins:
- https://app.example.com
- https://admin.example.com
methods:
- GET
- POST
- PUT
- DELETE
Strategy 1: Indexed keys
APP_NAME=MyService
APP_PORTS_0=3000
APP_PORTS_1=3001
APP_PORTS_2=3002
APP_ALLOWED_HOSTS_0=localhost
APP_ALLOWED_HOSTS_1=example.com
APP_ALLOWED_HOSTS_2=*.staging.example.com
APP_CORS_ORIGINS_0=https://app.example.com
APP_CORS_ORIGINS_1=https://admin.example.com
APP_CORS_METHODS_0=GET
APP_CORS_METHODS_1=POST
APP_CORS_METHODS_2=PUT
APP_CORS_METHODS_3=DELETE
Strategy 2: Comma-separated values
APP_NAME=MyService
APP_PORTS=3000,3001,3002
APP_ALLOWED_HOSTS=localhost,example.com,*.staging.example.com
APP_CORS_ORIGINS=https://app.example.com,https://admin.example.com
APP_CORS_METHODS=GET,POST,PUT,DELETE
Strategy 3: JSON-encoded values
APP_NAME=MyService
APP_PORTS='[3000,3001,3002]'
APP_ALLOWED_HOSTS='["localhost","example.com","*.staging.example.com"]'
APP_CORS_ORIGINS='["https://app.example.com","https://admin.example.com"]'
APP_CORS_METHODS='["GET","POST","PUT","DELETE"]'
Comparison of strategies:
| Strategy | Pros | Cons |
|---|---|---|
| Indexed keys | Unambiguous, easy to add items | Verbose, requires knowing the count |
| Comma-separated | Compact, widely supported | Cannot contain commas in values |
| JSON-encoded | Handles any value, type-safe | Requires JSON parsing, less readable |
Which to choose:
- Use indexed keys when the consuming framework supports them (e.g., Spring Boot, ASP.NET Core).
- Use comma-separated for simple string lists where values never contain commas.
- Use JSON-encoded when values are complex or you need type preservation.
Most YAML-to-ENV converters default to comma-separated for simplicity, but you should verify compatibility with your target runtime.
Use Case
Converting a YAML configuration with multiple CORS origins, allowed IP addresses, and feature flags into environment variables for a Node.js application that parses them at startup.