0

I have an ansible task to create a user and instead of specifying UID class as shown below, it has to pick from the a free range between (1000-1099) and has to assign the next available UID in a sequential order, how to do this ?

- name: create user and group
    user:
     name: user
     shell: /bin/bash
     uid: 1000
     comment: system Admin
  • You usually want automation tasks to be predictable, repeatable and idempotent. Any _real_ reason for "floating" UID requirement? – Konstantin Suvorov Jun 28 '17 at 18:02
  • Doesn't `user` module work the way you described by default? Of course, with the exception of the upper limit, which makes the whole task impossible to implement, mainly because your specification is lacking details what should happen if no uids from the range are available. – techraf Jun 29 '17 at 00:22
  • One real reason may be that the systems have different functions and as a result different sets of existing users by the time Ansible tries to create this new user. – reinierpost Jun 18 '19 at 12:02

2 Answers2

0

with_sequences is what you are looking for:

- name: create user and group
  user:
    name: user
    shell: /bin/bash
    uid: "{{ item }}"
    comment: system Admin
  with_sequence: start=1000 end=1099
Chris Lam
  • 283
  • 1
  • 9
0

Absent any user directory, there is no central authority on user names and IDs. (Maybe consider implementing directory auth at some point.)

Maintain a list of users with their UIDs in a variable, overriding at the group_vars or host_vars levels where necessary. Perhaps for a group abc have vars file group_vars/abc/users.yml:

---
users:
  - uid: 1000
    name: user
    comment: "system Admin"
  - uid: 1001
    name: alice
    comment: "Alice Alvin"
  - uid: 1002
    name: beth
    comment: "Beth Biorn"
  - uid: 1003
    name: Chris
    comment: "Chris Civers"

The task looks something like:

---
- name: create users
  loop: "{{ users }}"
  user:
    name: "{{ item.name }}"
    shell: /bin/bash
    uid: "{{ item.uid }}"
    comment: "{{ item.comment }}"

Several tasks remain to make this playbook fit for your purpose:

  • Make a list of groups and create them in a similar way.
  • Create overrides for the users var for groups that have conflicting GIDs or UIDs.
John Mahowald
  • 32,050
  • 2
  • 19
  • 34