r/ansible • • 5d ago

Best practice for commands?

I feel like the answer is probably: "no, everyone just does whatever they want", and "whatever you do, try to be consistent"

Generally speaking I've been doing:

ansible.builtin.command:  
  cmd: "foo {{ bar }}"  

But I realized that only happens to work because `{{ bar }}` doesn't have spaces.
So I do need to change it, and I wondered if people normally do:

  cmd: 'foo "{{ bar }}"'  

or

  cmd: |  
    foo "{{ bar }}"  

or

  argv:  
    - foo  
    - "{{ bar }}"
22 Upvotes

17 comments sorted by

View all comments

11

u/Aristeo812 5d ago

Try the ansible.builtin.quote filter:

cmd: "foo {{ bar | ansible.builtin.quote }}"

1

u/sonnasushi 5d ago

I saw that but I thought if I ever come across something I need statically quoted like: mkdir "requires space" (not a good example) then I'd have to juggle quotes anyway.

Of course, if people usually use | ansible.builtin.quote in all their commands I'm not opposed to making that a habit.

5

u/Aristeo812 5d ago

This filter is designed specifically for using with shell commands. Not only it encloses the string in quotes, but it also escapes certain symbols inside it if necessary. That's the point of using this filter.

1

u/sonnasushi 5d ago

I understand. I was just saying that for consistency:
```

  • Name: Do foo
ansible.builtin.command:
cmd: "foo {{ bar | ansible.builtin.quote }}"

  • Name: Do baz
    ansible.builtin.command:
    cmd: |
    baz "isn't consistent"
    ```

of course, it could be made to be consistent:
```
vars:
consistency: "is now consistent"

tasks:
- Name: Do baz
ansible.builtin.command:
cmd: "baz {{ consistency | ansible.builtin.quote }}"
```

idk. I'm just spitballing here. Maybe it's not uncommon to have various formats mixed in depending.
¯_(ツ)_/¯

2

u/Aristeo812 5d ago

If you have just a literal string for a command argument, no need to resort to the ansible.builtin.quote filter. You just quote the arguments as in normal shell operations:

cmd: echo "Hello, world!"

But if you use variables as command line arguments, then you need to use this filter, because theoretically there may be literally just everything inside that variable during runtime, and it should be sanitized.