sops icon indicating copy to clipboard operation
sops copied to clipboard

Editing file in-place with data from stdin

Open elsbrock opened this issue 3 years ago • 3 comments

I would like to be able to edit an already encrypted file in-place using the data from stdin so that I can use it as part of a script to modify a file. I am using a .sops.yaml file with pattern matching and multiple KMSs.

One option I found is to do -d | -e /dev/stdin, but that has the drawback that I need to specify the KMS to be used explicitly, although that is already configured in .sops.yaml.

Another possibility I could imagine is that the KMS pattern is taken from --output should that be specified.

What I don't get is why -i seems to open the editor in any case – can't it simply read from stdin if connected to a pipe? Or am I maybe missing something?

elsbrock avatar Jul 16 '20 21:07 elsbrock

Can you explain exactly what kind of edit you want to make to the file? --set might work for you.

Another, more flexible way to do it is writing a custom editor.

-i has no bearing on whether the editor is open or not. Actually, -i should have no effect at all when using the editor mode.

autrilla avatar Jul 18 '20 08:07 autrilla

I am basically trying to do the following:

sops -d myfile.dev.yaml | yq w - my.key $value | sops --in-place-edit myfile.dev.yaml

The reason I am not using the native YAML editing capabilities is because I'd have to construct the my.key value in my shell script to conform to sops expectation (["my"]["key”]). Besides, I would like to have a general way of editing a file in place, because the files I am working with might not necessarily be YAML or JSON.

elsbrock avatar Jul 22 '20 08:07 elsbrock

I did a workaround to do something similar with json with jq.

I created a script able to edit the file "inplace":

#!/bin/bash

if [ "$#" -lt 2 ]; then
    cat <<EOF
Usage: $0 <args> <file>

Example:

    EDITOR="jq-inplace '...'" sops file.json
EOF
    exit 1
fi

file="${!#}"

# Remove the last argument from the positional parameters
set -- "${@:1:$(($#-1))}"

tmpfile="$(mktemp)"
trap 'rm -f $tmpfile' EXIT
cat "$file" | jq "$@" > "$tmpfile"
mv -f "$tmpfile" "$file"

And then I call it by setting $EDITOR

EDITOR="jq-inplace.sh 'to_entries | map(.value|=(to_entries|map(.key|=ascii_upcase)|from_entries))|from_entries'" sops secrets.tfvars.json 

keymon avatar Oct 11 '23 23:10 keymon