Friday, November 8, 2013

Using Saltstack to manage linux users

Saltstack makes it very easy to manage users. You can use pillars to predefine all of the users and add them later, or you can define them within a single sls state file.

By example here is an sls file that will add or remove any number of users to a system. If you want the user dropped from the system, change "present" to "absent" and run it again.

Thanks Will for fixes and pointing out that if you're not on a debian system you'll want to use something else for the "adm" group.

{% set users = {
  'someuser': {
    'state': 'present',
    'fullname': 'User One',
    'pub_key': 'ssh-rsa .... '
  },
  'someuser2': {
    'state': 'present',
    'fullname': 'User two',
    'pub_key': 'ssh-rsa .... '
  }
} %}
 
{% for name, user in users.items() %}
{{ name }}:
  {% set shell = user.shell | default('/bin/bash') %}
  {% set groups = user.groups | default(['sudo', 'adm']) %}
  user.{{ user.state }}:
    - fullname: {{ user.fullname }}
    - home: /home/{{ name }}
    - shell: {{ shell }}
    - groups:
    {% for group in groups %}
      - {{ group }}
    {% endfor %}
  {% if user.state == 'present' %}
ssh_key_{{ name }}:
  ssh_auth:
    - present
    - user: {{ name }}
    - names:
      - {{ user.pub_key }}
    - require:
      - {{ name }}
  {% endif %}
{% endfor %}

5 comments:

  1. I was about to write something very similar to this. Thank You!!! You just saved me an hour this weekend.

    ReplyDelete
    Replies
    1. Glad to be of service. Check back next week for version 2, which supports arbitrary resource control files for users (let them get their bashrc, vimrc, etc on each host).

      Delete
  2. Quick update: Ran the sls, and wanted to share an update.
    1. (slight oversight) There is a missing %} which will cause the sls file render to fail (after line 12)
    2. There is an ordering necessary. An ssh key requires a user account with home directory to exist first. I added a require statement for the user.
    3. I'm testing this on a centos box (which does not have a 'sudo' group - so I opted to swap this out for 'wheel' - - in a perfect world I'd abstract out based on the os via grains.

    My changes are in this gist: https://gist.github.com/wcannon/7401047

    Feel free to share / change and etc. And, please keep sharing the good info.

    ReplyDelete
    Replies
    1. Thanks, Will! I appreciate you coming back and letting me know that. I didn't do a very good job testing after I removed my personal public keys :) I made the updates and gave you a credit at the top.

      Delete
  3. Thanks for this post it's really interesting!
    But there is a problem because the ssh_auth is not set to absent when the user is.
    I think it can be improve by removing the if and use the same trick like this:
    ssh_key_{{ name }}.{{ user.state }}:
    ssh_auth:
    - user: {{ name }}
    - names:
    - {{ user.pub_key }}
    - require:
    - {{ name }}

    ReplyDelete