Ansible与引用字典的子元素 [英] Ansible with subelements referencing a dict
问题描述
请和我在一起.我从来不需要与Ansible一起做这么复杂的事情,而且我真的很难将它拼凑在一起.
Bear with me, please. I've never had to do something this complex with Ansible and I'm really struggling to piece it together.
总而言之,我已经有一个命令和一项任务,将员工的SSH帐户和公共密钥部署到我们的服务器上.我想重复使用此命令来将某些员工密钥部署到某些网站用户帐户.一个例子可能比我能解释的更好.
To sum it up, I already have a dict and a task to deploy our employee's SSH accounts and public keys to our servers. I would like to re-use this dict to also deploy certain employee keys to certain website user accounts. An example probably explains better than I can.
employee_ssh_users:
user1: 'user1key'
user2: 'user2key'
user3: 'user3key'
user4: 'user4key'
- name: Add employee SSH users
user:
name: "{{ item.key }}"
state: present
with_dict: "{{ employee_ssh_users }}"
- name: Add employee public keys to employee accounts
authorized_key:
user: "{{ item.key }}"
state: present
key: "{{ item.value }}"
with_dict: "{{ employee_ssh_users }}"
上述配置和任务可以很好地将我们的员工及其密钥添加到服务器.现在,我想重新使用这些密钥,以便可以将某些雇员添加到某些其他用户,而不必复制和粘贴该雇员的密钥.这是我想要做的:
The above configuration and tasks work fine for adding our employees and their keys to the servers. Now, I want to re-use these keys so that I can add certain employees to certain other users without having to copy and paste the employee's keys. Here is what I'm trying to do:
website_keys:
- name: site1
authorized:
- user1
- user3
- name: site2
authorized:
- user1
- user2
- name: Add employee public keys to website accounts
authorized_key:
user: "{{ item.0.name }}"
key: "{{ hostvars[inventory_hostname]['employee_ssh_users'][' + item.1 '] }}"
with_subelements:
- "{{ website_keys }}"
- authorized
基本上,即使有可能,我也无法弄清楚将子元素插值到key变量中到底需要做些什么.
Basically, I can't figure out exactly what I need to do to interpolate the subelement into the key variable, if it's even possible at all.
推荐答案
这很简单:
- name: Add employee public keys to website accounts
authorized_key:
user: "{{ item.0.name }}"
key: "{{ employee_ssh_users[item.1] }}"
with_subelements:
- "{{ website_keys }}"
- authorized
您可以按名称查询employee_ssh_users
,并使用item.1
不带引号,因为它本身就是变量.
You can query employee_ssh_users
by name and use item.1
without quotes, as it is a variable itself.
这篇关于Ansible与引用字典的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!