Seá*_*eán 15 ansible ansible-playbook
我试图读取文件的内容,将它们存储在变量中,然后将它们插入到另一个文件中(如果它们尚不存在).
所以,我试图解决这个问题的方法如下:
# Create a variable that represents the path to the file that you want to read from
ssh_public_key_file: '../../jenkins_master/files/{{ hostvars[inventory_hostname]["environment"] }}/id_rsa.pub'
# Create a variable that represents the contents of this file:
ssh_public_key: "{{ lookup('file', '{{ ssh_public_key_file }}') }}"
Run Code Online (Sandbox Code Playgroud)
然后我在Ansible playbook中使用这些变量,如下所示:
- name: Install SSH authorized key
lineinfile: create=yes dest=~/.ssh/authorized_keys line=" {{ ssh_public_key }}" mode=0644
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行该剧本时,我收到以下错误消息:
could not locate file in lookup: {{ ssh_public_key_file }}
Run Code Online (Sandbox Code Playgroud)
任何人都可以推荐一个解决方案或建议我可能做错了什么?
谢谢,
SEAN
Byt*_*ger 25
您必须将行更改为:
# Create a variable that represents the contents of this file:
ssh_public_key: "{{ lookup('file', ssh_public_key_file) }}"
Run Code Online (Sandbox Code Playgroud)
如果你需要连接变量和字符串,你可以这样做:
# Example with two variables
ssh_public_key: "{{ lookup('file', var_1+var_2) }}"
# Example with string and variable
ssh_public_key: "{{ lookup('file', '~/config/'+var_1) }}"
Run Code Online (Sandbox Code Playgroud)
首先,我会确保您的ssh_public_key_file 变量设置正确。如果添加如下所示的任务,它会显示什么?
- name: display variable
debug: var=ssh_public_key_file
Run Code Online (Sandbox Code Playgroud)
如果输出看起来像这样,那么变量没有正确定义(例如,主机不存在“环境”事实):
ok: [localhost] => {
"ssh_public_key_file": "../../jenkins_master/files/{{ hostvars[inventory_hostname][\"environment\"] }}/id_rsa.pub"
}
Run Code Online (Sandbox Code Playgroud)
但是,如果所有内容都定义正确,那么您的输出应该显示变量替换为正确的值:
ok: [localhost] => {
"ssh_public_key_file": "../../jenkins_master/files/foo/id_rsa.pub"
}
Run Code Online (Sandbox Code Playgroud)
一旦你验证了这一点,我就会对你的ssh_public_key变量做同样的事情。只需使用调试模块输出其值即可。它应显示为公钥文件的内容。
我强烈建议的另一件事是完全避免使用 lineinfile。由于您正在使用 SSH 密钥,我建议您改用authorized_key模块。这是管理authorized_keys 文件的一种更简洁的方法。
| 归档时间: |
|
| 查看次数: |
17644 次 |
| 最近记录: |