Home > Blockchain >  Sed to replace a script variable by certificate
Sed to replace a script variable by certificate

Time:10-29

I'd like to replace a variable in a script template by a public and private certificate.

For example, I've generated a harbor.crt public certificate and a harbor.key private key with the following command:

sudo openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout /data/harbor.key -out /data/harbor.crt -subj "/CN=$LOCAL_IP" -addext "subjectAltName=IP:127.0.0.1,IP:$LOCAL_IP"

In a template script, I've the following variables I'd like to replace with the above files:

CFG_HARBOR_CRT="CRT"                    # Harbor registry certificate
CFG_HARBOR_KEY="KEY"                    # Harbor registry key

To replace those values, I've tried to do something like that:

HARBOR_CRT=`sudo cat /data/harbor.crt`
HARBOR_KEY=`sudo cat /data/harbor.key`
sudo sed -i "s/CFG_HARBOR_CRT\=\"[^\"]*\"/CFG_HARBOR_CRT\=\"$HARBOR_CRT\"/g" ./template-script.sh
sudo sed -i "s/CFG_HARBOR_KEY\=\"[^\"]*\"/CFG_HARBOR_KEY\=\"$HARBOR_KEY\"/g" ./template-script.sh

But both commands failed on: sed: -e expression #1, char 70: unterminated s' command`

Is there a way to use sed command with unescaped variables ?

CodePudding user response:

I suspect there's info missing here. Why use sed at all?

For the simple case, just replace the markers with file reads.

CFG_HARBOR_CRT="$(</data/harbor.crt)"
CFG_HARBOR_KEY="$(</data/harbor.key)"

That might mean you need to run the whole script with elevated priv's though, so I understand why you might not want to do that.

...do you need root to read those files?

If so, and if you don't want the whole script run as root, maybe this:

$: sed 's,^CFG_HARBOR_CRT="CRT",CFG_HARBOR_CRT="$(sudo cat /data/harbor.crt)",
        s,^CFG_HARBOR_KEY="KEY",CFG_HARBOR_KEY="$(sudo cat /data/harbor.key)",' tmpf
CFG_HARBOR_CRT="$(sudo cat /data/harbor.crt)"                    # Harbor registry certificate
CFG_HARBOR_KEY="$(sudo cat /data/harbor.key)"                    # Harbor registry key

Switching / to , as the demarcation reduces leaning toothpick syndrome.

Switching `...` to $(...) improves flexibility, stability, readability, etc.

CodePudding user response:

Pulling out of comments to get better visibility ...

Consider running the files through base64 and embedding the result into the script, then on the other end run base64 -d to decrypt the data and store in the target files.

Using base64 encoded data should eliminate most (all?) of the sed headaches of dealing with special characters and/or trying to find a sed script delimiter that's not in the data.

  • Related