ansible - 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') }}"
他们都没有工作,我做错了什么?
解决方案
如果您将 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') }}"
推荐阅读
- r - 如何仅根据小数点后的最大值保留观察结果?
- php - 联盟路线、集装箱和 PDO
- javascript - 如何大写和删除句子/字符串中的空格?
- python - 将geopandas shapely 多边形转换为geojson
- python - 如何在不暂停正在运行的程序的情况下使用 python 发出警报?
- kubernetes - SSH 到本地 IBM 私有云集群中的主节点?
- excel - Excel公式计算仅包含单个日期的所有单元格
- hive - 在配置单元查询中获取不同的字段
- javascript - 当我尝试缩短链接时,Bitly 返回 MISSING_ARG_LOGIN
- mysql - MySQL如何更新另一个表中同一行的多个列