File: empty_string_compare.md

package info (click to toggle)
ansible-lint 25.6.1%2Breally25.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,628 kB
  • sloc: python: 18,973; sh: 66; makefile: 7
file content (44 lines) | stat: -rw-r--r-- 1,052 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# empty-string-compare

This rule checks for empty string comparison in playbooks.
To ensure code clarity you should avoid using empty strings in conditional statements with the `when` clause.

- Use `when: var | length > 0` instead of `when: var != ""`.
- Use `when: var | length == 0` instead of `when: var == ""`.

This is an opt-in rule.
You must enable it in your Ansible-lint configuration as follows:

```yaml
enable_list:
  - empty-string-compare
```

## Problematic Code

```yaml
---
- name: Example playbook
  hosts: all
  tasks:
    - name: Shut down
      ansible.builtin.command: /sbin/shutdown -t now
      when: ansible_os_family == "" # <- Compares with an empty string.
    - name: Shut down
      ansible.builtin.command: /sbin/shutdown -t now
      when: ansible_os_family !="" # <- Compares with an empty string.
```

## Correct Code

```yaml
---
- name: Example playbook
  hosts: all
  tasks:
    - name: Shut down
      ansible.builtin.shell: |
        /sbin/shutdown -t now
        echo $var ==
      when: ansible_os_family
```