3

I'm trying to create a set of users in Ansible using with_dict. The problem is sometimes the user already exists and I don't have the password. In that case I'd like to simply skip setting the password, but manage the rest of the user attributes. Here is an ugly workaround, but there must be a better way to do this:

- name: create FTP users (password known)
  user:
    name: "{{ item.key }}"
    comment: "{{ item.value.comment | default('') }}"
    password: "{{ item.value.password }}"
    shell: "{{ item.value.shell | default('/sbin/nologin') }}"
    home: "{{ item.value.home | default('/var/ftp/' + item.key) }}"
    createhome: "{{ item.value.createhome | default('no') }}"
  with_dict: "{{ ftp_users }}"
  when: item.value and item.value.password is defined

- name: create FTP users (password unknown)
  user:
    name: "{{ item.key }}"
    comment: "{{ item.value.comment | default('') }}"
    shell: "{{ item.value.shell | default('/sbin/nologin') }}"
    home: "{{ item.value.home | default('/var/ftp/' + item.key) }}"
    createhome: "{{ item.value.createhome | default('no') }}"
  with_dict: "{{ ftp_users }}"
  when: item.value.password is not defined

I've also found I can just pull the password for every user in to ansible from /etc/shadow, but that is kind of ugly as well. Is there a way to simply not try to manage the password attribute if the dict value is unset?

ebarrere
  • 330
  • 1
  • 3
  • 15

2 Answers2

6

Excerpt from the user module docs:

update_passwordalways/on_createalways will update passwords if they differ. on_create will only set the password for newly created users.

To skip unknown parameter, use omit:

password: "{{ item.value.password | default(omit) }}"
Konstantin Suvorov
  • 3,996
  • 1
  • 12
  • 13
0

Run all accounts through the 'password unknown' playbook.

Use a separate playbook to set the passwords of the new accounts.

Jeter-work
  • 845
  • 4
  • 15
  • Not sure that your answer really adds much beyond what is already part of the question. You are more or less suggesting the OP do exactly what they are doing. – Zoredache Aug 02 '17 at 23:28
  • My suggestion is to move the password setting step(s) out of the account creation process, then he only needs to have the one playbook. Then you run the accounts that do not have passwords through the password process. Trying to combine the two adds complexity. Personally, I see nothing wrong with the way he's doing it above. – Jeter-work Aug 04 '17 at 19:35