大网数据广告活动
服务器运维问答

Ansible deploy multiple authorized_keys on multiple hosts

· 52CE 我爱测

We need deploy keys on the servers, but trick is that the keys are many and do not all of them must have deploy on all servers. Now we do it follows: in vars roles/authorized_keys/vars/main.yml ssh_users: - name: bob key: "{{ loo…

问题原文

原帖链接 · artful · CC BY-SA 3.0

We need deploy keys on the servers, but trick is that the keys are many and do not all of them must have deploy on all servers. Now we do it follows:

in vars roles/authorized_keys/vars/main.yml

ssh_users:
  - name: bob
    key: "{{ lookup('file', 'roles/authorized_keys/vars/bob.pub') }}" 
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/user.pub') }}"
    state: absent

in task: roles/authorized_keys/tasks/main.yml

- name: Add ssh key.
    authorized_key: user={{ item.name }} key="{{ item.key }}" state={{ item.state }}
    with_items: ssh_users

in playbook: authorized_keys.yml

---
- hosts: '{{ hosts }}'
  vars_files:
    - '{{ vars }}'
  roles:
    - { role: authorized_keys }

Before start playbook change roles/authorized_keys/vars/main.yml (present or absent). When start playbook add hosts and hosts group:

ansible-playbook -i production --extra-vars "hosts=web:pg:1.2.3.4" authorized_keys.yml

Previously, it was all good, but now increased the number of keys and servers. And now I do not remember whose key is to be on what server.

Tell me please how I can set up the list of hosts for each key? For example something like this:

- name: bob
    key: "{{ lookup('file', 'roles/authorized_keys/vars/bob.pub') }}" 
    servers: web,database,12.12.12.12
    state: present
- name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    servers: api,pg,30.30.30.30
    state: present

已采纳解答

原帖链接 · Christopher Karel · CC BY-SA 3.0

I would use a host variable "ssh_users", which states the users that need their host keys added.

- ssh_users:
   - bob
   - root
   - alice

Then, you have a seperate variable file that defines the name, key and state for each SSH user. Import that variable file, then call your original task pretty much as is.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-07-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。