使用 Ansible 组合多个公钥 [英] Combine multiple public keys with Ansible
问题描述
如何将多个 ssh 公钥与 Ansible 的 authorized_key 模块结合使用?
How can I combine multiple ssh public keys to use with Ansible's authorized_key module?
我有包含用户和密钥的变量文件:
I have variables file containing users and keys:
ssh_users:
- name: peter
keys:
- 'ssh-rsa AAAAB3NzaC1yc2EAAA peter@key1'
- 'ssh-rsa AAAABsgsdfgyc2EAAA peter@key2'
root: yes
- name: paul
keys:
- 'ssh-rsa AAAAB3Nzaafac2EAAA paul@key1'
root: no
我想查看此列表,挑选出具有root: yes"的用户(及其密钥)并将它们组合起来以更新 root 用户的 authorized_keys 文件.
I'd like to go over this list, pick out users (and their keys) which have 'root: yes' and combine them to update root user's authorized_keys file.
这不起作用:
- name: lookup keys
set_fact:
keylist: "{{ item.keys }}"
with_items: "{{ ssh_users }}"
when: item.root == true
register: result
- name: make a list
set_fact:
splitlist: "{{ result.results |
selectattr('ansible_facts','defined') | map(attribute='ansible_facts.keylist') | list | join('\n') }}"
- name: update SSH authorized_keys
authorized_key:
user: root
key: "{{ splitlist }}"
state: present
exclusive: yes
推荐答案
您可以使用 Jinja selectattr
和 map
过滤器获得您想要的内容,如下所示:>
You can get what you want using the Jinja selectattr
and map
filters, like this:
---
- hosts: localhost
gather_facts: false
vars:
# Here's our data: two users with 'root' access,
# one without. We expect to see three public keys in
# the resulting authorized_keys file.
#
# Note that I've renamed the "keys" key to "pubkeys", because
# otherwise it conflicts with the "keys" method of dictionary
# objects (leading to errors when you try to access something
# like item.keys).
ssh_users:
- name: alice
pubkeys:
- 'ssh-rsa alice-key-1 alice@key1'
root: true
- name: peter
pubkeys:
- 'ssh-rsa peter-key-1 peter@key1'
- 'ssh-rsa peter-key-2 peter@key2'
root: true
- name: paul
pubkeys:
- 'ssh-rsa paul-key-1 paul@key1'
root: false
tasks:
- become: true
authorized_key:
user: root
key: "{{ '\n'.join(ssh_users|selectattr('root')|map(attribute='pubkeys')|flatten) }}"
state: present
exclusive: true
在authorized_key
任务中,我们首先使用selectattr
过滤器来提取那些具有root
访问权限的用户.我们将它传递给 map
过滤器以仅提取 pubkeys
属性,这将为我们提供两个列表(一个带有一个键,另一个带有两个键).最后,我们将其传递给 flatten
过滤器以创建单个列表,然后将结果键与换行符连接起来以匹配 authorized_key
模块所需的输入格式.生成的 .ssh/authorized_keys
文件如下所示:
In the authorized_key
task, we first use the selectattr
filter to extract those users with root
access. We pass that to the map
filter to extract just the pubkeys
attribute, which would give us two lists (one with one key, the other with two keys). Finally, we pass that to the flatten
filter to create a single list, and then join the resulting keys with newlines to match the input format expected by the authorized_key
module. The resulting .ssh/authorized_keys
file looks like:
ssh-rsa alice-key-1 alice@key1
ssh-rsa peter-key-1 peter@key1
ssh-rsa peter-key-2 peter@key2
这篇关于使用 Ansible 组合多个公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!