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, you can help support this site and get something for yourself by signing up for any of the services listed below through the provided links.

The following links are part of affiliate programs, and I will receive a referral payment from any of the services you sign-up for.

  • Get Faster Shipping: Perhaps you're about to order some stuff on 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.
  • Start Investing Now: Are you looking to start investing some of your disposable saved income? Get started by opening an account with Webull, where upon sign-up and opening a brokerage account with an initial deposit of at least $100 you will receive 1 stock valued (subject to change based on normal market movement) between $8 and $1600.

Thanks for reading and take care.