Francis
Francis

Reputation: 173

Conditional group membership with Ansible

I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.

- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins    

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775  

The debug task returns this when the group doesn't exist:

ok: [host] => {
    "getent_group.webadmins": ""
}

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.

The group may exists in AD domain, so I cannot parse /etc/group.

Upvotes: 0

Views: 799

Answers (2)

techraf
techraf

Reputation: 68609

The following condition should work for you:

group="{{ (getent_group.webadmins is defined) | ternary('webadmins', 'root') }}"

If you displayed the value of getent_group in your debug task, you'd notice the value of webgroup key is actually set to null, not an empty string.

"getent_group": {
    "webgroup": null
}

Upvotes: 1

Chris Lam
Chris Lam

Reputation: 3614

Try this without using the ternary filter:

{{ 'webadmins' if getent_group.webadmins != '' else 'root' }}

Upvotes: 0

Related Questions