Extra kubectl configmap/secret to .env file

Posted on 2021-03-21 in Trucs et astuces

You can extract data from your kubernetes config maps into a .env file with the commands below (requires you to have jq installed):

# Get the data in JSON.
kubectl get configmap my-map --output json |
    # Extract the data section.
    jq '.data' |
    # Replace each "key": "value" pair with "key=value"
    jq -r 'to_entries | map(.key + "=" + (.value)) | .[]' >> .env

You can also do that with secrets:

# Get the data in JSON.
kubectl get secret my-secret --output json |
    # Extract the data section.
    jq '.data' |
    # Decode the value of each keys.
    jq 'map_values(@base64d)' |
    # Replace each "key": "value" pair with "key=value"
    jq -r 'to_entries | map(.key + "=" + (.value)) | .[]' >> .env

Or with configmap data from helm templates:

# Extract the values with a `awk` script: we print everything starting from the line that contains only `configmap` until the first empty line.
awk '{if ($0 ~ /^configmap:$/) {triggered=1;}if (triggered) {print; if ($0 ~ /^$/) { exit;}}}' "./project/values.yaml" |
    # Keep only the indented lines that contains our configuration values.
    grep '^  ' |
    # Transform key: value into key=value
    sed 's/  //;s/: /=/' >> .env