trying to parse a dict to add users: missing something easy...

Hi, I’m trying to update user accounts on a number of linux hosts vi a dict containing the users. Here’s a sample vars:

“user_accounts”: [
{
“testusr”: {
“gecos”: “Test User”,
“grp”: “wheel”,
“pass”: “123abc”,
“status”: “enabled”,
“username”: “testusr”
}
}
]

Here’s the play:

  • name: Sync User Accounts (create)
    user:
    name: “{{ item[‘username’] }}”
    comment: “{{ item[‘gecos’] }}”
    password: “{{ item[‘pass’] | default(‘notavalidpassword’) }}”
    group: “{{ item[‘grp’] | default(‘’) }}”
    shell: “{{ item[‘shell’] | default(‘/bin/bash’) }}”
    update_password: always
    state: present
    when: “{{ item[‘status’] }}” == ‘enabled’
    with_items:
  • “{{ user_accounts }}”
    tags: users

I’m getting a syntax error:

The offending line appears to be:

state: present
when: “{{ item[‘status’] }}” == ‘enabled’
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

Any ideas?

Dan

Hi Dan,

1. If you use a quote at the start, you should close it only at the end. So this should work:

  when: "{{ item['status'] }} == 'enabled'"

2. In line above, you don't need {{ and thus quotes, when using when: 'always use {{ }} except when when:'<http://docs.ansible.com/ansible/faq.html#when-should-i-use-also-how-to-interpolate-variables-or-dynamic-variable-names&gt;

3. You are missing "testusr" when accessing an item's elements, or better said, "testusr" part in var definition is an extra.
This would work better:

        "user_accounts": [
          {
            "gecos": "Test User",
            "grp": "wheel",
            "pass": "123abc",
            "status": "enabled",
            "username": "testusr"
          }
        ]

If you really need "testusr" data, you could put it as an additional element:

        "user_accounts": [
          {

            "id": "testusr",

            "gecos": "Test User",
            "grp": "wheel",
            "pass": "123abc",
            "status": "enabled",
            "username": "testusr"
          }
        ]

So, with the variable declared as above, this would be a cleaner way to accomplish what you want:
  when: item.status == 'enabled'

Cheers,
Marko