ThorneLabs

Ansible Fix Colon Syntax Error for sudoers File

• Updated January 21, 2019


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'"

If you found this post useful and would like to help support this site - and get something for yourself - sign up for any of the services listed below through the provided affiliate links. I will receive a referral payment from any of the services you sign-up for.

Get faster shipping and more with Amazon Prime: About to order something from Amazon but want to get more value out of the money you would normally pay for shipping? Sign-up for a free 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.

Thanks for reading and take care.