LoginSignup
7
6

More than 5 years have passed since last update.

Create user from user list by Ansible -ユーザを一括登録する方法-

Posted at

Overview

 Ansibleにはuser moduleが有るのでユーザ登録自体は簡単に操作できる。
しかしながら、一括で複数ユーザを登録したい場合は以下のようなやり方だと、単一のパラメータでしか作成できず、例えばパスワード等は指定できなくなってしまう。


- user: name={{item}}
  with_items:
    - taro
    - jiro
    - saburo

Hashリストを活用する

 最も単純な方法は以下のようにHashリストを使って、パラメータを渡す。


- user: name={{item.name}} uid={{item.uid}} comment="{{item.comment}}" group={{item.group}}
  with_items:
    - { name: 'taro', uid: 1001, group: 'users', comment: '1st' }
    - { name: 'jiro', uid: 1002, group: 'users', comment: '2nd' }
    - { name: 'saburo', uid: 1003, group: 'users', comment: '3rd' }

ただし、これだとplaybookへのハードコーディングになるので使い回しには全く適さない。
ユーザ登録は頻繁に行うのでハードコーディングなどもってのほか。
ましてや「追加」「変更」「削除」に対応させるためにもパラメータは外出ししたい。

vars_filesを使う

 要はパラメータを渡せればいいのでこんな風にしてみる。


----- task -----
- name: Create user
  user: 
    name: "{{ item.name }}"
    groups:  "{{ item.group }}"
    shell: /sbin/nologin
  with_items:
    - "{{ users }}"
  when: "{{ users }}"

---- playbook ---
- hosts: Hosts
  roles:
    - create_user
  vars_files:
    - var.yml

--- var.yml ---
users:
  - { name: 'taro', uid: 1001, group: 'users', comment: '1st' }
  - { name: 'jiro', uid: 1002, group: 'users', comment: '2nd' }
  - { name: 'saburo', uid: 1003, group: 'users', comment: '3rd' }

このようにすると、var.ymlを書き換えるだけでいくらでも使い回せるのでいい具合。
ちなみにwhen句は、保険。var.ymlが空の時にエラーにならないようにするおまじない。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6