带有引用字典的子元素的 Ansible [英] Ansible with subelements referencing a dict

查看:23
本文介绍了带有引用字典的子元素的 Ansible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请耐心等待.我从来没有用 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 帐户和公钥部署到我们的服务器上.我想重新使用这个 dict 来将某些员工密钥部署到某些网站用户帐户.一个例子可能比我能解释的更好.

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

基本上,如果可能的话,我无法确切地弄清楚我需要做什么才能将子元素插入到关键变量中.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆