LoginSignup
13
12

More than 5 years have passed since last update.

Ansibleでユーザ毎に任意の公開鍵を作成する

Last updated at Posted at 2015-05-12
  • ホスト側で公開鍵を作成したくない
  • ユーザ毎に公開鍵の内容を変えたい
  • rolesの配下に公開鍵を置きたくない(今回はrole無しで作成)

上記条件を満たす為に考えたのが以下。
(とっくに誰かが考えてる気もしますが)

環境

Ansible: 1.9.0.1

構成

/projet-root
|- /public_keys
|   |- userA
|   |- userB
|   |- …
|- add_user.yml
add_user.yml
---
- hosts: all
  sudo: yes
  vars:
    users:
      - 
        name: "userA"
      -
        name: "userB"
  tasks:
    - name: Add users
      user:
        state: present
        name: "{{ item.name }}"
        append: yes
      with_items:
        - "{{ users }}"

    - name: Get public keys of each user as a variable
      set_fact:
        keys: "{{ item }}"
      with_fileglob:
        - public_keys/*

    - name: Add public keys to the authorized key for each user
      authorized_key:
        user: "{{ item[0].name }}"
        key: "{{ lookup('file', item[1]) }}"
      with_nested:
        - users
        - keys
      when: item[1] | search("/" + item[0].name + "/")

当初with_itemswith_fileglobを同時に使えないかと(意味不明な事を)考えたのですが、無理でした。
その為set_factで公開鍵のパスを拾ってきた後、lookupで内容を取得しています。

その内容を全ユーザに適用されても困るので、searchフィルターでユーザ名と公開鍵パスを比較しています。
公開鍵パスにユーザ名が含まれていた場合のみ、authorized_keysを適用。

無事に任意の公開鍵を設置することが出来ました。

13
12
2

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
13
12