Add systemd_escape algorithm as Jinja2 filter
From @Zocker1999NET on May 10, 2020 17:14
SUMMARY
Add a Jinja2 filter allowing to escape strings following the systemd escape algorithm. Then the user would not require to mimic the escaping by combining other existing filters because the full implementation is not trivial.
ISSUE TYPE
- Feature Idea
COMPONENT NAME
filters
ADDITIONAL INFORMATION
The usage is shown below. It allows to use the algorithm without implementing a mimic itself using other existing filters. For example the path escaping is required to generate the name a .mount must have for systemd to work (see here).
escaped_name: {{ service_name | systemd_escape }} # For unit names for example
mount_name: {{ mount_path | systemd_escape(path=True) }} # For absolute paths (special behavior for path separator
# Example escaping
test_result: {{ ("/media/user/drive" | systemd_escape(path=True)) == "media-user-drive" }} # Should be True
Copied from original issue: ansible/ansible#69415
From @wu-lee on May 22, 2021 17:12
Someone has implemented this, but nevertheless it should probably be in core:
https://github.com/estheruary/ansible-plugin-systemd_escape/
Would IMO also fit in ansible.posix, though it's probably easier to get something included in community.general...
I implemented such filter for my own projects, currently only published as part of a playbook, see here on my git repo or as github gist, licensed under MIT, so use it as you like.
@Zocker1999NET Would you be interested in raising a PR against this repo with a GNU GPLv3 license?
What's the requirement for filter security regarding subprocess? I know modules require the use of run_command, but this would invoke systemd_escape on the controller so not sure what the guidance is.
I don't think there currently are requirements, at least not that I'm aware of.
(Except, of course, the general ones, such as "don't pass sensitive data through the command line".)
I would do - without shell=True
def run_command(args):
p = Popen(args, stderr=PIPE, stdout=PIPE)
(stdout, stderr) = p.communicate()
return (p.returncode, stdout, stderr)
@Zocker1999NET Are you OK if I open a new PR with your code with some modifications and do the re-licensing (MIT -> GNU GPLv3 or later)? Thanks in advance.
@Akasurde Sure, use my code as you like.