'Systemd unit file escaping issue

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 miller the gorilla