Ansible中如何使用lookup插件获取目录路径和文件

How to use the lookup plugin to get the directory path and file in Ansible

我有两本剧本,其中一本创建 SSH 密钥,另一本创建新用户并为创建的新用户部署 public ssh 密钥。

我的问题是我创建了一个任务,该任务创建了一个带有时间戳的新目录来存储相关数据,我能够获得变量的路径,并将其添加为虚拟主机,这样我就可以在我的所有游戏中调用该路径,但似乎我无法在查找中使用相同的变量,以便我能够部署 ssh 密钥。请协助,以下是相关任务。

# Create the directory with timestamp
- name: Create Directory with timestamp to store data that was run multiple times that day
  when: inventory_hostname in groups['local']
  file:
    path: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}"
    state: directory
    mode: "0755"
  register: dir_path
# Add the directory path to dummy host called save so that I can call it from other plays
- name: Add dir path:"{{dir_path.path}}" as a 'save' host
  when: inventory_hostname in groups['local']
  add_host:
    name: "save"
    dir: "{{dir_path.path}}"
# Deploying SSH Key I tried this -->
- name: Deploy Public Key to the server
  when: inventory_hostname in groups['Servers']
  authorized_key:
    user: "{{hostvars['new-user']['user']}}"
    state: present
    key: "{{dir_path.path}}/SSH-Key.pub"
# ...this -->
- name: Deploy Public Key to the server
  when: inventory_hostname in groups['Servers']
  authorized_key:
    user: "{{hostvars['new-user']['user']}}"
    state: present
    key: "{{ lookup('file','{{dir_path.path}}/SSH-Key.pub') }}"
# .... and this -->
- name: Deploy Public Key to the server
  when: inventory_hostname in groups['Servers']
  authorized_key:
    user: "{{hostvars['new-user']['user']}}"
    state: present
    key: "{{ lookup('file','{{hostvars['save']['dir']}}/SSH-Key.pub') }}"

None 成功了,我做错了什么?

如果您将 Jinja 表达式放入 Jinja 表达式中的字符串中,那么您确实会得到一个未被解释的变量。

一个基本的例子是:

- hosts: all
  gather_facts: no
      
  tasks:
    - debug: 
        msg: "{{ '{{ foo }}' }}"
      vars:
        foo: bar

给出:

ok: [localhost] => {
    "msg": "{{ foo }}"
}

何时

- hosts: all
  gather_facts: no
      
  tasks:
    - debug: 
        msg: "{{ foo }}"
      vars:
        foo: bar

达到预期:

ok: [localhost] => {
    "msg": "bar"
}

所以为了在这里实现你想要的,你应该使用 Jinja 的连接运算符:~,为了让 Jinja 解释你的变量并将它与你的“硬编码”字符串的其余部分连接起来.

以指令有效结束:

key: "{{ lookup('file', hostvars['save']['dir'] ~ '/SSH-Key.pub') }}"