Ansible:读取远程文件

Ansible: read remote file

我在远程主机上使用 ansible 生成文件,生成之后,我想在另一个任务中阅读这些文件。

我没有找到任何模块来使用 ansible 读取远程文件(查找似乎只在本地主机上)。

你知道这样的模块吗?

谢谢

编辑:

这是我的用例:

我生成 ssh 密钥并将其添加到 github。这些键由 var 文件中的一个对象设置,所以我像这样循环生成它:

    tasks:
  - name: Create ssh key
    user:
      name: "{{sshConfigFile.user}}"
      generate_ssh_key: yes
      ssh_key_file: ".ssh/{{item.value.file}}"
      state: present
    with_dict: "{{sshConfiguration}}"

它工作得很好,但是如何读取这些密钥以通过 API 将其发送到 github?

注意,问这个问题的时候,下面的解决方案是可以接受的。以后版本的Ansible可能会提供更好的方案来解决这个问题。

如您所说,所有查找都在本地主机上。但是所有这些都可以通过使用 shellregister 远程完成。你能说出你到底想做什么吗?举个例子。

  - shell: cat "{{remote_file}}"
    register: data

  - shell: ......
    with_xxxx:

您可以尝试 'fetch' 模块,它将密钥文件检索到 localhost 上的目标路径:

fetch: 
  src: ".ssh/{{item.value.file}}" 
  dest:"/tmp/ssh_keys/{{item.value.file}}"
  flat: yes
with_dict: "{{sshConfiguration}}" 

或者 运行 带有 --diff 标志(目标文件更改时输出差异)..

ansible-playbook --diff server.yaml

slurp它起来..

- name: Slurp hosts file
  slurp:
    src: /etc/hosts
  register: slurpfile

- debug: msg="{{ slurpfile['content'] | b64decode }}"

您可以使用注册命令将文件内容注册到变量中。这是我的建议,

- name: get contents of file
  command: cat /path/to/file
  register: filename
  become: true # use case specific option

- name: viewing the contents
  debug:
    msg: "{{filename.stdout}}"

这将显示文件的内容。

通过使用命令模块,您可以在远程节点的另一个任务中读取或使用该文件。

喜欢

-command: cp /tmp/xxx/example.sh /usr/local/yyy