What does the YAML to Env Converter do?
The YAML to Env / Dotenv Converter on blueutils.com flattens hierarchical, nested YAML configurations into standard .env (dotenv) environment variable files. It recursively traverses nested maps and lists, joins keys with customizable delimiters (_, __, .), handles casing (UPPERCASE, lowercase, preserve), adds optional prefixes, and formats clean output for Docker Compose, Kubernetes, and Node.js dotenv loaders.
Core Concepts
Understanding key flattening and delimiter conventions ensures seamless environment variable generation:
- Nested Object Flattening: Deeply nested keys (e.g.
server.database.port: 5432) are flattened into composite environment variables (SERVER_DATABASE_PORT=5432). - Array Value Handling: Arrays of primitive values (e.g.
allowed_origins: [localhost, example.com]) are formatted as comma-separated values (ALLOWED_ORIGINS=localhost,example.com). - Export Statements: When enabled, prepends
exportbefore each key-value pair for direct sourcing in POSIX shell environments (export SERVER_PORT=8080).
How to use the tool?
- Paste or Upload YAML: Paste your YAML configuration file into the Raw YAML Configuration editor, upload a
.yamlfile, or click Sample. - Configure Generator: Customize key casing (
UPPERCASE,lowercase,preserve), nested delimiters (_,__,.,-), key prefixes (e.g.APP_), or toggle value quoting andexportprefixes. - Review & Export: The converted
.envoutput generates in real time in the Generated .env File Content pane. Click Copy or Download to save your.envfile.
Related Developer Utilities
If you work with environment variables, YAML configs, and container deployments, explore these related tools:
- Docker Compose to .env: Extract environment variables from Docker Compose YAML files.
- YAML to JSON Converter: Convert YAML manifests into standard JSON payloads.
- YAML Formatter & Beautifier: Format and re-indent messy YAML configuration documents.
- YAML Syntax Validator: Validate YAML syntax and inspect line/column error offsets.
- YAML Minifier & Compressor: Minify YAML configurations into compact flow syntax.
REST API Integration
blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/yaml/to-env) to programmatically convert raw YAML configurations into flattened .env key-value pairs.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
rawText / yaml |
String / Object | Raw YAML document string or parsed object to convert to .env. |
"server:\n port: 8080" |
delimiter |
String | Delimiter for nested keys ("_", "__", "."). Defaults to "\n". |
"_" |
keyCase |
String | Casing strategy ("UPPERCASE", "lowercase", "preserve"). Defaults to "UPPERCASE". |
"UPPERCASE" |
prefix |
String | Optional prefix prepended to all keys. | "APP" |
quoteValues |
Boolean | Whether to wrap output values in double quotes. Defaults to false. |
false |
exportPrefix |
Boolean | Whether to prepend export to each output line. Defaults to false. |
false |
API Request Payload Examples
cURL (Using Raw String)
curl -X POST https://blueutils.com/api/yaml/to-env \
-H "Content-Type: application/json" \
-d '{
"rawText": "server:\n port: 8080\n host: localhost",
"delimiter": "_",
"keyCase": "UPPERCASE"
}'cURL (Using Direct Object)
curl -X POST https://blueutils.com/api/yaml/to-env \
-H "Content-Type: application/json" \
-d '{
"yaml": {
"server": {
"port": 8080,
"host": "localhost"
}
},
"delimiter": "_"
}'Python
import requests
url = "https://blueutils.com/api/yaml/to-env"
payload = {
"rawText": "server:\n port: 8080\n host: localhost",
"delimiter": "_",
"keyCase": "UPPERCASE"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = """
{
"rawText": "server:\\n port: 8080\\n host: localhost",
"delimiter": "_",
"keyCase": "UPPERCASE"
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/yaml/to-env"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether the conversion succeeded. | true |
message |
String | Success confirmation message. | "YAML successfully converted to .env / Environment Variables." |
result |
String | Flattened .env key-value pairs text string. |
"SERVER_PORT=8080\nSERVER_HOST=localhost" |
data |
Object / Array | Parsed native object/array representation of the input YAML. | {"server":{"port":8080}} |
keyCount |
Number | Total count of environment variable keys generated. | 2 |
originalSize |
Number | Byte size of raw input payload in UTF-8. | 36 |
resultSize |
Number | Byte size of generated .env output in UTF-8. |
40 |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"message": "YAML successfully converted to .env / Environment Variables.",
"result": "SERVER_PORT=8080\nSERVER_HOST=localhost",
"data": {
"server": {
"port": 8080,
"host": "localhost"
}
},
"keyCount": 2,
"originalSize": 36,
"resultSize": 40
}Validation Failure Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "YAML syntax error (Line 2, Column 5): Unexpected token",
"details": {
"line": 2,
"col": 5
}
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to convert YAML to .env?
Integrating the YAML to .env Converter API into Docker deployment tooling, Kubernetes secret generators, or CI/CD pipelines provides key benefits:
- Rapid Script Validation: Enables automated CI/CD runners to convert environment-specific YAML configuration files directly into
.envruntime files. - Optimized Token Efficiency for AI Agents: Flattens deeply nested configuration hierarchies via a deterministic endpoint rather than spending hundreds of LLM tokens on manual tree unrolling.
- Deterministic Accuracy Without Hallucinations: Ensures consistent key delimiter joining, casing rules, and quote escaping without dropped keys or altered environment values.
Native Usage
How to convert YAML files into .env environment files locally using terminal CLI utilities, code editors, and programming runtimes without external web services:
Visual Studio Code & JetBrains Shortcuts
- VS Code: Use Dotenv and YAML extensions or run command palette (
Ctrl+Shift+P/Cmd+Shift+P) to flatten properties. - JetBrains IDEs: Inspect environment variables directly in Run/Debug configuration dialogs.
Windows (CMD / PowerShell)
# Convert YAML to .env using Python in PowerShell
python -c "
import yaml
def flatten(d, p=''):
r = {}
for k, v in d.items():
nk = f'{p}_{k}'.upper() if p else k.upper()
if isinstance(v, dict): r.update(flatten(v, nk))
else: r[nk] = str(v)
return r
data = yaml.safe_load(open('config.yaml')) or {}
print('\n'.join(f'{k}={v}' for k, v in flatten(data).items()))
" > .envLinux / Unix (Bash & yq)
# Convert simple YAML key-value pairs using yq
yq eval '. | to_entries | .[] | .key + "=" + .value' config.yaml > .env
# Flatten nested maps from stdin pipeline
cat config.yaml | yq -o=props '.' | tr '.' '_' > .envPython
Using PyYAML to recursively flatten dictionary keys:
import yaml
def flatten_yaml_to_env(data, prefix="", delimiter="_"):
items = []
for k, v in data.items():
key = f"{prefix}{delimiter}{k}".upper() if prefix else k.upper()
if isinstance(v, dict):
items.extend(flatten_yaml_to_env(v, key, delimiter).items())
else:
items.append((key, str(v)))
return dict(items)
with open("config.yaml", "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
env_vars = flatten_yaml_to_env(config)
for key, val in env_vars.items():
print(f"{key}={val}")Java
Using Jackson (YAMLMapper) in Java 17+:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
public class YamlToEnvExample {
public static void flatten(JsonNode node, String prefix, StringBuilder sb) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
String key = prefix.isEmpty() ? field.getKey().toUpperCase() : (prefix + "_" + field.getKey()).toUpperCase();
if (field.getValue().isObject()) {
flatten(field.getValue(), key, sb);
} else {
sb.append(key).append("=").append(field.getValue().asText()).append("\n");
}
}
}
public static void main(String[] args) throws Exception {
YAMLMapper mapper = new YAMLMapper();
JsonNode root = mapper.readTree(new File("config.yaml"));
StringBuilder env = new StringBuilder();
flatten(root, "", env);
System.out.println(env.toString());
}
}