Home > other >  pipe '|' doesn't seem to be liked on my ansible script
pipe '|' doesn't seem to be liked on my ansible script

Time:09-29

I have a task to count how many files exist. Is there something wrong with the syntax?

task:
- name: "Getting Local File Count"
  kubernetes.core.k8s_exec:
    namespace: "{{namespace}}"
    pod: "{{pod}}"
    command: "find '{{local_dir}}' -type f | wc -l"
  register: command_status

but after executing the playbook I get

"find: paths must precede expression: |",

CodePudding user response:

That's a common mistake coming from a world of CMD in docker, which has two forms: free text and exec -- but in kubernetes descriptors, it's always the exec form. If one wishes to have shell helpers, such as pipes or && or functions or redirection, one must do that explicitly via sh -c style constructs

The bad news is that the ansible module's command: argument doesn't accept a list[str] and instead they choose to use shlex.split so you have to either copy the complicated command into the pod and just use command: /path/to/my/script.sh or take your chances with shlex, which seems to understand sh -c quoting:

>>> shlex.split("""sh -c "find '{{local_dir}}' -type f | wc -l" """)
['sh', '-c', "find '{{local_dir}}' -type f | wc -l"]

making your ansible parameter look like:

    command: >-
      sh -ec "find '{{local_dir}}' -type f | wc -l"

as always when using jinja2 templates in a shell context, the safer choice is to use | quote versus just wrapping your thing in single-quotes and hoping no one uses a single-quote in local_dir, although in this case one will need to be extra cautious since it is a shell literal inside a shell literal :-(

  • Related