简体   繁体   English

Ansible:读取远程文件

[英]Ansible: read remote file

I generate files with ansible on remote host and after this generation, I would like to read theses files in another task.我在远程主机上使用 ansible 生成文件,在这一代之后,我想在另一个任务中阅读这些文件。

I don't find any module to read remote file with ansible (lookup seems only on local host).我没有找到任何模块来使用 ansible 读取远程文件(查找似乎只在本地主机上)。

Do you know a module like this?你知道这样的模块吗?

Thanks谢谢

EDIT:编辑:

Here is my use case:这是我的用例:

I generate ssh keys and I add it to github.我生成 ssh 密钥并将其添加到 github。 These keys are setting by an object in var files so I loop like this to generate it:这些键由 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}}"

It works very fine but how read these keys to send it to github via the API?它工作得很好,但如何读取这些密钥以通过 API 将其发送到 github?

Either run with the --diff flag (outputs a diff when the destination file changes)..使用 --diff 标志运行(当目标文件更改时输出差异)..

ansible-playbook --diff server.yaml

or slurp it up..或者把它吞掉..

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

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

Note that when this question was asked, the following solution was acceptable.请注意,当问到这个问题时,可以接受以下解决方案。 Later versions of Ansible may provide a better solution to solve this problem.更高版本的 Ansible 可能会提供更好的方案来解决这个问题。

As you said, all lookups are on localhost.正如您所说,所有查找都在本地主机上。 But all of them can be done on remote by using shell and register .但是所有这些都可以通过使用shellregister远程完成。 Can you tell what exactly you are trying to do?你能说出你到底想做什么吗? just an example.只是一个例子。

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

  - shell: ......
    with_xxxx:

You can try the 'fetch' module, which will retrieve the key file to a destination path on localhost :您可以尝试“获取”模块,它将密钥文件检索到localhost上的目标路径:

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

You can register the contents of the file in a variable using the register command.您可以使用 register 命令将文件的内容注册到变量中。 Here is what I would suggest,这是我的建议,

- 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}}"

This will display the contents of the file.这将显示文件的内容。

By using command module you can read or use that file in another task in remote node.通过使用命令模块,您可以在远程节点的另一个任务中读取或使用该文件。

like

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM