31
29

More than 5 years have passed since last update.

複数の公開鍵を一括でサーバに登録

Last updated at Posted at 2015-07-07

誰かがやってそうな話だけど、メモとして残しておこう

やりたかったこと

  1. リモートログイン可能なユーザの公開鍵を管理して、ansible で各サーバに配布する

利用したもの

  • 公開鍵を登録するには authorized_key を利用する
  • authorzied_key.key には lookup を利用してパスを渡すの簡単( Examples を参考に)
  • 公開鍵のパスは with_fileglob: <path> でマッチしたものをそれぞれ渡す

作ったもの

roles/authorized_key/main.yml
---
# file: roles/authorized_key/main.yml

- name: REMOVE  | public keys from all hosts
  authorized_key: 
    user: "{{ target }}"
    key: "{{ lookup('file', item) }}"
    state: absent
  sudo: yes 
  with_fileglob: "{{ publickeys }}/removed/*.pub"

- name: APPEND  | public keys into all hosts
  authorized_key: 
    user: "{{ target }}"
    key: "{{ lookup('file', item) }}"
    state: present
  sudo: yes 
  with_fileglob: "{{ publickeys }}/*.pub"

各サーバの testusr の公開鍵を集約して、それを一括で登録する例

playbooks/update_authorized_keys.yml

- name: SETUP | public keys for testusr
  hosts: all
  user: root
  roles:
    - role: authorized_key
      target: testusr
      publickeys: ~/.ssh/public_keys/testusr
  pre_tasks:
    - name: FETCH | public keys from all hosts
      fetch:
        src: "/home/testusr/.ssh/id_rsa.pub"
        dest: "~/.ssh/public_keys/testusr/{{ ansible_hostname }}.pub"
        fail_on_missing: yes 
        flat: yes

playbook 実行後の authorized_keys

$ tree .ssh
.ssh
├── id_rsa
├── id_rsa.pub
├── known_hosts
└── public_keys
    └── testusr
        ├── hostname01.pub
        ├── hostname02.pub
        └── hostname03.pub
~/.ssh/authorized_keys
ssh-rsa (略) ansible-generated on hostname01
ssh-rsa (略) ansible-generated on hostname02
ssh-rsa (略) ansible-generated on hostname03
31
29
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
31
29