0

I am wanting to generate a secret key for a django project, that runs using podman run --new, so it generates a new container from scratch when the machine is restarted. I have the following bash code, which runs correctly in a terminal, but I cannot get it to work inside a systemd unit file.

sed -i "s/SECRET_KEY=.*/SECRET_KEY='$(echo $(chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'; python -c "import secrets; print(''.join(secrets.choice('${chars}') for i in range(50)))") | sed -e 's/[\/&]/\\&/g')'/" /filepath/env_file

I get the same error which is

sed: -e expression #1, char 111: unterminated `s' command

I am guessing that I might need to escape the replacement string a bit better in the sed -e command, such that the replacement string to the earlier sed -i won't have conflicting characters that signal an end of string or similar, but I am stumped on how to get it working. I have been escaping apostrophes and quotation marks all afternoon.... :( It is always character 111 that seems to be awry, so maybe I am wrong. I have tried the command systemd-escape but with no luck.

So, any help gratefully appreciated.

miller the gorilla
  • 860
  • 1
  • 7
  • 19
  • 1
    Maybe the tip: _You can still do what you want, but you'll need more backslashes_ from https://stackoverflow.com/a/45850218/757777 could work? – Erik Sjölund Apr 29 '22 at 16:02
  • thanks, but I am still seeing backslashes and apostrophes everytime I close my eyes. It is worth understanding properly though, so I'll give it a go as soon as I get a spare moment... – miller the gorilla May 01 '22 at 17:29

1 Answers1

0

I don't think it is possible to do, because systemd doesn't run the execstart command in bash, so one has to put the command in a bash -c but then the environment isn't set for the python import, I don't think.

I ended up placing the command in a script with locked down permissions, and calling it from the unit.

miller the gorilla
  • 860
  • 1
  • 7
  • 19