首页 > 解决方案 > Ansible中如何使用lookup插件获取目录路径和文件

问题描述

我有两个剧本,其中一个创建 SSH 密钥,另一个创建一个新用户并为创建的新用户部署公共 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') }}"

他们都没有工作,我做错了什么?

标签: ansibleansible-2.x

解决方案


如果您将 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') }}"

推荐阅读