Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 29 ยท Practice and Review

Common Mistakes and Troubleshooting

Fix the Ansible problems everyone hits: YAML indentation and quoting errors, unreachable hosts, become failures, non-idempotent shell tasks, variable precedence surprises.

Almost every Ansible problem falls into a small number of families. The playbook does not parse. The host cannot be reached. The user cannot become root. A task reports changed forever. A variable has a value nobody expects. Once you can tell the families apart, most problems take minutes instead of hours, because the first line of the error tells you which family you are in.

This lesson goes through the mistakes in the order you will probably meet them, with the message you will see, why it happens and the fix. The commands and playbooks are read-only, because Ansible cannot run on this site. Two stand-ins are runnable: one traces a variable precedence bug to the layer that causes it, and one is a small mistake finder that reads playbook text the way a linter does. They are models of the idea, not real Ansible or ansible-lint.

First, read the error properly

Ansible errors look noisy, but they have a fixed shape. Before changing anything, answer two questions: at which stage did it fail, and for which host?

flowchart TD
  S["Run ansible-playbook"] --> A{"ERROR! before any<br/>TASK line?"}
  A -- yes --> Y["Parse or inventory problem<br/>syntax, YAML, missing file"]
  A -- no --> B{"Message says<br/>UNREACHABLE?"}
  B -- yes --> U["Connection problem<br/>SSH, address, user, keys"]
  B -- no --> C{"Message says<br/>FAILED! for a task?"}
  C -- yes --> F["The host answered, the module failed<br/>become, package, arguments, logic"]
  C -- no --> R["Run finished but the result is wrong<br/>precedence, idempotence, conditions"]

Where the message appears tells you which family of problem you have.

Three habits make every later step easier:

  • Run ansible-playbook site.yml --syntax-check before the first real run. It finds YAML and structure errors without touching a host.
  • Add -v for results, -vv for task paths and -vvv for connection details (the exact SSH command). Start with the lowest level that helps.
  • Read the last lines of a failure. The msg key usually contains the real operating-system error, such as "Permission denied" or "No package matching".

Mistake 1: YAML indentation and tabs

YAML uses indentation to express structure, and it allows spaces only. A tab character anywhere in the indentation is an error, and a task that is one space off becomes a different structure, or fails to parse.

YAML
tasks:
  - name: Install git
    ansible.builtin.package:
      name: git
     state: present      # one space too few

Typical messages are "mapping values are not allowed in this context" and "did not find expected key", followed by "The error appears to be in ... line N, column M, but may be elsewhere in the file". Two points about that sentence: the line number is where the parser noticed the problem, which can be one or two lines after the real mistake, and Ansible prints the offending line with a caret underneath, so look at the line above it too.

Fixes:

  • Configure your editor to insert spaces for tabs, show whitespace and use two-space indentation for YAML.
  • Run yamllint or ansible-lint, covered in Testing, Linting and Debugging.
  • Keep module arguments aligned: every key of one module sits at the same indent.

Mistake 2: quoting and YAML surprises

A value that starts with {{ must be quoted, because YAML would read the braces as the start of a mapping. Ansible even adds a hint to the error: always quote template expressions that begin a value.

YAML
# Broken: YAML sees a flow mapping
content: {{ banner_text }}

# Fixed
content: "{{ banner_text }}"

Other quoting traps:

  • A value that contains : (colon and space) or starts with a special character such as *, &, !, % or @ needs quotes.
  • File modes should be quoted strings: mode: "0644". A bare 644 is the decimal number 644, which is not octal 0644.
  • Words such as yes, no, on and off may be read as booleans. A version like 3.10 becomes the number 3.1. Quote anything that must stay text: version: "3.10".
  • In when:, do not wrap the whole expression in {{ }}. Write when: app_env == "production". The condition is already a template expression.

Mistake 3: unreachable hosts

UNREACHABLE! means Ansible could not even open the connection. No module ran. The msg says what SSH reported.

TEXT
fatal: [web1]: UNREACHABLE! => {"changed": false,
  "msg": "Failed to connect to the host via ssh: ... Permission denied (publickey,password).",
  "unreachable": true}

Work from the outside in:

  1. Can you SSH by hand with exactly the same user and address? If ssh [email protected] fails, Ansible will too. Ansible adds no magic.
  2. Is the address right? Check what Ansible believes with ansible-inventory -i inventory.ini --host web1: look at ansible_host and ansible_user.
  3. Which user and key? Set ansible_user and, if needed, ansible_ssh_private_key_file in the inventory, or remote_user in the play.
  4. Host key problems. A first connection asks for confirmation, and a non-interactive run cannot answer. Add the host to known_hosts, for example with ssh-keyscan. Disabling host key checking everywhere is convenient and unsafe; see SSH, Privilege Escalation and Hardening.
  5. Python on the target. A missing interpreter is reported as a failure, not as unreachable, but it often shows up at the same moment on a brand-new machine. Bootstrap it with the raw module, or set ansible_python_interpreter.
  6. Network. A firewall or a wrong port gives "Connection timed out" or "Connection refused". Use -vvv to see the exact command and the port.

Mistake 4: become fails

FAILED! with a message such as "Missing sudo password" or "sudo: a password is required" means the connection worked but privilege escalation did not.

  • No passwordless sudo. Either pass --ask-become-pass (-K) or give the Ansible user a sudoers rule that does not ask for a password. Prefer the second one for automation, with the narrowest permissions that work.
  • Wrong level. become: true at play level applies to every task. A task that must run as a normal user (for example cloning into a home directory) needs become: false or become_user.
  • Wrong method. sudo is the default; systems that use su or doas need become_method.
  • Unprivileged temp files. When you become a different unprivileged user, Ansible has to share its temporary files; the symptom is a permission error for the module file. Installing the acl package on the target is the usual cure.

Mistake 5: shell tasks that are not idempotent

The classic mistake is a task that works the first time and then reports changed forever, or breaks on the second run.

YAML
# Reports changed on every run, and appends a duplicate line each time
- name: Add the cron path
  ansible.builtin.shell: echo 'PATH=/opt/bin:$PATH' >> /etc/environment

# Idempotent: the module compares first
- name: Add the cron path
  ansible.builtin.lineinfile:
    path: /etc/environment
    line: 'PATH=/opt/bin:$PATH'

If there really is no module, say when the work is done with creates, removes or changed_when, as covered in Modules and Idempotence. A good habit is to run every playbook twice. The second recap must show changed=0; if it does not, find the task that keeps changing.

Mistake 6: variable precedence surprises

The same variable can be defined in many places, and the strongest layer wins. The painful version of this bug is a value that someone set for a quick test and forgot, which silently beats your carefully organised group_vars. The model below keeps a list of layers from weakest to strongest and shows which one wins. It also has a trace helper that lists every layer defining a variable, the same question you answer on a real system with ansible-inventory --host and a debug task.

JS Find the layer that causes a precedence bug

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The production group correctly says db.prod.internal, but the leftover play vars beat it, so production would talk to the staging database. Three rules prevent this class of bug:

  • Define each variable in one place unless you really want layering, and use the lowest layer that works (role defaults, then group_vars).
  • Never leave vars: or -e overrides in committed playbooks and scripts.
  • Prefix role variables with the role name, such as nginx_port, so they cannot collide with unrelated variables.

See the full ordering in Variables, Facts and Precedence.

Mistake 7: legacy and removed syntax

Old blog posts and Stack Overflow answers show syntax that has since changed. Learn to recognise it.

  • Short module names such as shell: and copy: still work through the built-in collection, but fully qualified names (ansible.builtin.shell) are unambiguous and are what linters expect.
  • with_items and the other with_* keywords are the older looping style. loop is the modern one and is easier to combine with when and filters.
  • The include: task keyword was replaced by include_tasks and import_tasks, and has been removed from recent versions of ansible-core. Choose between the two new keywords deliberately: import_* is processed when the playbook is parsed, include_* when the task runs.
  • yes and no for booleans work but are a trap for beginners; true and false are clearer.
  • Bare conditions in braces, such as when: "{{ some_var }}", produce warnings. Write the expression without the braces.

When a deprecation warning scrolls past, read it. It names the feature, the version in which it disappears and the replacement.

A mistake finder you can edit

This stand-in reads playbook text line by line and reports the mistakes from this lesson: tabs, odd indentation, an unquoted brace, a bare three-digit mode, a command with no idempotence guard, a short module name and with_items. Fix the playbook until it reports nothing. Real tools such as yamllint and ansible-lint parse the YAML properly and know hundreds of rules; this model only shows the idea.

JS Mistake finder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading a stubborn failure: a checklist

When none of the above matches, narrow it down on purpose.

  1. Reproduce on one host: --limit web1.
  2. Run one task: --start-at-task "Name of the task", or --step to confirm each task.
  3. Print the data: add a debug task with var: the_variable, or msg: "{{ the_variable }}", before the failing task.
  4. Raise verbosity with -vvv and read the command and the arguments the module received.
  5. Use --check --diff to see what would change without changing it.
  6. Make the smallest possible playbook that still fails, then ask for help with that file and the full error text.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A run prints UNREACHABLE! for web1. What is the best first step?

    UNREACHABLE means no connection could be made, so no module ran. If SSH by hand fails, Ansible will fail too.
  2. 2. Why does content: {{ banner_text }} fail to parse?

    Write content: "{{ banner_text }}". Always quote template expressions that begin a value.
  3. 3. A role default, group_vars and a play-level vars section all define the same variable. Which one wins on a host?

    Play vars rank above inventory group_vars, and group_vars rank above role defaults. Only extra vars would beat the play vars.
  4. 4. A shell task reports changed on every run. Which fix is best when no module exists for the job?

    Command-style modules assume a change by default. A guard tells Ansible what 'already done' looks like.
  5. 5. How should a file mode be written in YAML?

    A quoted string stays text and is read as octal by the module. A bare 644 is the decimal number 644.

Summary

  • Locate the stage first: errors before any TASK are parse or inventory problems, UNREACHABLE is a connection problem and FAILED means the host answered but the module failed.
  • Use spaces only, quote values that start with {{, quote modes and anything that must stay text, and run --syntax-check before every first run.
  • For unreachable hosts, test SSH by hand, then inspect ansible_host, ansible_user, keys and host keys with -vvv.
  • Become failures usually mean no passwordless sudo, the wrong level or the wrong method.
  • Replace blind shell tasks with modules, or guard them with creates, removes and changed_when; run every playbook twice and expect changed=0.
  • Precedence bugs come from forgotten overrides: define each variable in one layer and trace it with ansible-inventory --host and debug.
  • Prefer FQCN module names, loop and include_tasks/import_tasks, and read deprecation warnings.

Next: Interview Questions