Troubleshooting Ansible Issues
1. Debugging Connection Issues
| Issue | Possible Cause | Solution |
|---|---|---|
| Connection timeout | Network latency or firewall blocking | Check network connectivity and ensure port 22 (SSH) is open |
| Permission denied (publickey) | Incorrect SSH key or permissions | Verify SSH keys, ensure correct user and permissions (600 for private key) |
| Host key verification failed | Host fingerprint changed or unknown host | Use ssh-keygen -R hostname to remove old key or set host_key_checking = False |
| Authentication failed | Wrong username/password or SSH key | Confirm credentials and test with ssh user@host |
Note: Use
-vvv for verbose output in Ansible to get more details on connection issues.
Workflow: Troubleshooting Steps
- Test SSH access manually from the control node to the target host
- Ensure
ansible_connection = sshis set in inventory if not default - Check SSH config and key permissions
- Run
ansible -m ping -i inventory.yml allto test connectivity
2. Resolving Authentication Errors
| Error Type | Description | Resolution Steps |
|---|---|---|
| SSH Permission Denied | Ansible cannot authenticate via SSH due to incorrect credentials or permissions. |
|
| Authentication Failed (SSH) | SSH authentication fails due to key mismatch or invalid credentials. |
|
| Invalid Host Key | SSH host key has changed or is not trusted. |
|
Example: Inventory Configuration with SSH Key
all:
hosts:
webserver:
ansible_host: 192.168.1.10
ansible_user: deploy
ansible_ssh_private_key_file: /home/user/.ssh/id_rsa
Note: Ensure that the SSH key file has correct permissions:
chmod 600 /home/user/.ssh/id_rsa.
Warning: Disabling
host_key_checking can expose the system to man-in-the-middle attacks.
3. Troubleshooting Module Errors
| Error Type | Description | Common Causes | Solution |
|---|---|---|---|
| Module not found | Ansible cannot locate the module in its module path. | Module name typo, missing plugin, incorrect module path | Verify module name, ensure plugin is installed, check ANSIBLE_LIBRARY path |
| Invalid parameter | Provided parameter is not supported by the module. | Using deprecated or incorrect parameter names | Check documentation for correct parameters, update module version |
| Permission denied | Module execution fails due to insufficient permissions. | Insufficient privileges, file access issues | Run with appropriate user permissions or use become |
| Connection timeout | Module execution times out due to network or host issues. | Network connectivity, unreachable hosts | Verify host reachability, increase ansible_timeout |
| Module execution error | Module fails during runtime due to internal errors. | Script or command failure, invalid return values | Debug module logs, check for syntax errors in scripts |
Example: Module not found error
ansible-playbook site.yml -i inventory
[WARNING]: Could not find module 'nonexistent_module' in the library path.
PLAY [all] *********************************************************************
TASK [debug] *******************************************************************
fatal: [localhost]: FAILED! => {
"msg": "Could not find module 'nonexistent_module' in the library path."
}
Example: Invalid parameter error
- name: Use invalid parameter
command:
cmd: "ls -l"
invalid_param: "value"
Note: The
command module does not support invalid_param.
Example: Permission denied error
- name: Attempt to write to protected file
copy:
src: "local_file"
dest: "/etc/protected_file"
Warning: This will fail unless run with elevated privileges.
Common Troubleshooting Steps
- Check module documentation for correct syntax and parameters
- Verify that all required dependencies are installed
- Ensure correct user permissions for module execution
- Use
-vvvflag to get verbose output for debugging - Validate inventory and connection settings
4. Debugging Variable Issues
| Issue | Description | Solution |
|---|---|---|
| Undefined variable | Variable not defined in any scope | Use default() filter or set a default value in vars |
| Variable override | Variable value changed unexpectedly | Use debug task to print variable values at runtime |
| Host vs group vars | Confusion between host and group variable precedence | Use ansible-playbook --extra-vars to override or inspect variables |
Example: Debugging undefined variable
- name: Debug undefined variable
debug:
msg: "Variable value is {{ my_var | default('default_value') }}"
Example: Inspecting all variables
- name: Print all host variables
debug:
var: hostvars[inventory_hostname]
Note: Use
ansible-playbook --extra-vars to override variables for testing.
Warning: Avoid using
set_fact for complex variable logic as it can be hard to trace.
5. Resolving Template Errors
| Error Type | Description | Common Causes | Solution |
|---|---|---|---|
| Undefined variable in template | Variable referenced in Jinja2 template is not defined | Missing variable in inventory, host_vars, or group_vars | Ensure variable is defined in proper scope or use default value with {{ var|default('value') }} |
| Invalid Jinja2 syntax | Template contains invalid Jinja2 syntax or malformed expressions | Mismatched braces, incorrect filter usage, or invalid control structures | Validate syntax using ansible-lint or ansible-playbook --syntax-check |
| Template not found | Ansible cannot locate the template file specified in template module |
Incorrect path, missing template file, or incorrect directory structure | Verify the template file exists in templates/ directory and path is correct relative to playbook |
| Variable interpolation issues | Variables not properly interpolated in template content | Incorrect use of {{ }}, missing quotes, or special characters in values |
Escape special characters using Jinja2 filters like |escape or |regex_replace |
Example: Undefined Variable Handling
- name: Use default value for undefined variable
template:
src: config.j2
dest: /etc/myapp/config.conf
vars:
app_port: 8080
Example: Template with Error Handling
- name: Render config with fallback
template:
src: app_config.j2
dest: /etc/app/config.ini
vars:
server_port: "{{ port | default(8080) }}"
Note: Use
ansible-playbook --check to preview template rendering without applying changes.
Warning: Avoid using
{{ item }} inside templates without proper context; it may lead to unexpected behavior or errors.
6. Debugging Inventory Issues
| Issue | Description | Solution |
|---|---|---|
| Host not found in inventory | Ansible cannot locate a host specified in playbook or ad-hoc command. | Verify host name exists in inventory file. Use ansible-inventory -i <inventory> --list to list all hosts. |
| Invalid inventory format | Inventory file contains syntax errors or invalid structure. | Validate using ansible-inventory -i <inventory> --validate. Ensure proper YAML or INI format. |
| Host unreachable | Ansible can reach the host but cannot connect via SSH. | Check SSH connectivity manually. Ensure SSH keys are configured correctly and user permissions allow access. |
| Missing host variables | Host-specific variables are not defined or accessible. | Define variables in inventory or group_vars. Use ansible-inventory -i <inventory> --host <hostname> to inspect host vars. |
7. Resolving Privilege Escalation
| Option | Values | Description |
|---|---|---|
| become | true |
Enable privilege escalation for the task |
| become_method | sudo |
Method used to escalate privileges (e.g., sudo, su) |
| become_user | root |
User to escalate to (default is root) |
| become_flags | -H |
Flags passed to the privilege escalation command (e.g., -H for home directory) |
Example: Using become to run a task as root
- name: Run a command as root
command: /usr/bin/systemctl restart nginx
become: true
become_user: root
Note: Ensure that the user running the playbook has the necessary permissions to escalate privileges, typically via
sudo or su.
Warning: Misconfiguring privilege escalation can lead to security vulnerabilities. Always test in a safe environment before deploying.
8. Debugging Performance Issues
| Issue | Description | Solution |
|---|---|---|
| Slow task execution | Tasks take longer than expected to complete. | Use ansible-playbook --profile to identify slow tasks. |
| High memory usage | Ansible consumes excessive RAM during playbook runs. | Use --forks to limit concurrent processes and --check to simulate runs. |
| Network latency | Playbooks are slow due to network delays. | Enable ansible_connection: local for local tasks or use delegate_to to reduce network overhead. |
Note: Use
--check to simulate playbook runs and identify bottlenecks without making changes.
Warning: Running with
--forks too high can lead to resource exhaustion on the control node.
9. Troubleshooting Idempotence
| Issue | Description | Solution |
|---|---|---|
| Non-idempotent tasks | Tasks that produce different results on subsequent runs | Ensure tasks are stateless and only change system state if needed |
| State changes in loops | Loops that modify state each iteration | Use loop_control to manage loop behavior and state |
| Conditional task execution | Tasks that run conditionally based on previous state | Use when conditions to ensure consistent task execution |
Example: Non-Idempotent Task
- name: Increment counter file
copy:
content: "{{ (counter_file | default(0)) + 1 }}"
dest: /tmp/counter.txt
Note: Idempotence is a core principle in Ansible. Tasks should produce the same result regardless of how many times they are run.
10. Resolving Python Dependency Issues
| Issue | Description | Solution |
|---|---|---|
| ansible_python_interpreter | Ansible cannot find the correct Python interpreter | Set ansible_python_interpreter in inventory or host vars to point to the correct Python path |
| missing dependencies | Required Python packages not installed on target hosts | Use pip or apt to install missing packages on target hosts |
| version mismatch | Target hosts use different Python versions than the control node | Ensure consistent Python versions across all nodes or use ansible_python_interpreter to specify version |
Example: Setting Python Interpreter
# In inventory file or host vars
ansible_python_interpreter: /usr/bin/python3
Note: Ensure the specified Python interpreter is available and has required modules installed.
Warning: Using
ansible_python_interpreter with a non-system Python can cause issues if the interpreter is not properly configured.
11. Debugging Custom Modules
| Aspect | Description | Notes |
|---|---|---|
| debugger | ansible.builtin.debug |
Used to print variables or messages during playbook execution |
| vars | debug.var=variable_name |
Prints the value of a variable at runtime |
| msg | debug.msg=message_text |
Prints a custom message to stdout |
Example: Using debug module to inspect variables
- name: Debug custom module variables
ansible.builtin.debug:
var: my_custom_var
Example: Using debug to print message
- name: Print debug message
ansible.builtin.debug:
msg: "Custom module is running with these parameters"
Note: The
debug module is useful for inspecting variable values and understanding the flow of execution in custom modules.
Warning: Avoid excessive use of
debug in production playbooks as it may expose sensitive data.
12. Using Ansible Logs
| Log Level | Description | Command Flag |
|---|---|---|
| -v | Verbose mode (default) | -v |
| -vv | More verbose | -vv |
| -vvv | Debug mode | -vvv |
| -vvvv | Connection debugging | -vvvv |
Note: The
-vvv flag enables debug logging which includes detailed information about each task execution and variable values.