While writing an Ansible Task to add a user to the sudoers file on a Linux distribution, I encountered an error that kept the Ansible Task from completing.
The error encountered was:
ERROR: Syntax Error while loading YAML script, playbooks/bootstrap.yml Note: The error may actually appear before this position: line 29, column 44 regexp="^james ALL" line='james ALL=(ALL) NOPASSWD: ALL'
The particular Ansible Task looked similar to the following:
- name: Add user james to sudoers action: lineinfile dest=/etc/sudoers state=present regexp="^james ALL" line='james ALL=(ALL) NOPASSWD: ALL'
This particular error happens because of the way the Python YAML parser works with colons within attributes (see the YAML Syntax Gotchas).
If the space between NOPASSWD: and ALL is removed, and the line looks like line='james ALL=(ALL) NOPASSWD:ALL’, the error does not occur. However, this is incorrect sudoers syntax.
Commenter bcoca on an Ansible GitHub issue page provided a fix for this, and based on bcoca’s comment, a working version of the Ansible Task above would look like the following:
- name: Add james to sudoers action: 'lineinfile dest=/etc/sudoers state=present regexp="^james ALL" line="james ALL=(ALL) NOPASSWD: ALL"'
The following is another fix, found on the Ansible lineinmodule Examples page:
- name: Add james to sudoers lineinfile: "dest=/etc/sudoers state=present regexp='^james ALL' line='james ALL=(ALL) NOPASSWD: ALL'"