shell 我可以使用Ansible剧本将文本从远程复制到本地吗?

kyxcudwk  于 2022-12-19  发布在  Shell
关注(0)|答案(1)|浏览(146)

我知道Ansible fetch-module可以将文件从远程复制到本地,但是如果我只需要将内容(在我的例子中是保存IP地址的tmp文件)附加到本地文件中,该怎么办?
获取模块执行以下操作:

- name: Store file into /tmp/fetched/
  ansible.builtin.fetch:
    src: /tmp/somefile
    dest: /tmp/fetched

我需要它来做这样的事情:

- name: Store file into /tmp/fetched/
  ansible.builtin.fetch:
    src: /tmp/somefile.txt
    dest: cat src >> /tmp/fetched.txt
50few1ms

50few1ms1#

简而言之:

- name: Get remote file content
  ansible.builtin.slurp:
    src: /tmp/somefile.txt
  register: somefile

- name: Append remote file content to a local file
  vars:
    target_file: /tmp/fetched.txt
  ansible.builtin.copy:
    content: |-
      {{ lookup('file', target_file) }}
      {{ somefile.content | b64decode }}
    dest: "{{ target_file }}"
  # Fix write concurrency when running on multiple targets
  throttle: 1
  delegate_to: localhost

注:

  • 第二个任务不是幂等的(每次运行时都会修改文件,即使要追加的内容相同)
  • 这适用于小的目标文件,如果文件变得很大,并且您遇到了很高的执行时间/内存消耗,您可能需要切换到shell来执行第二个任务:
- name: Append remote file content to a local file
  ansible.builtin.shell:
    cmd: echo "{{ somefile.content | b64decode }}" >> /tmp/fetched
  # You might still want to avoid concurrency with multiple targets
  throttle: 1
  delegate_to: localhost

或者,您可以一次性写入从所有目标获取的所有文件的所有内容,以避免并发问题并节省一些时间。

# Copy solution
- name: Append remote files contents to a local file
  vars:
    target_file: /tmp/fetched.txt
    fetched_content: "{{ ansible_play_hosts
      | map('extract', hostvars, 'somefile.content') 
      | map('b64decode')
      | join('\n') }}"
  ansible.builtin.copy:
    content: |-
      {{ lookup('file', target_file) }}
      {{ fetched_content }}
    dest: "{{ target_file }}"
  delegate_to: localhost
  run_once: true

# Shell solution
- name: Append remote files contents to a local file
  vars:
    fetched_content: "{{ ansible_play_hosts
      | map('extract', hostvars, 'somefile.content') 
      | map('b64decode')
      | join('\n') }}"
  ansible.builtin.shell:
    cmd: echo "{{ fetched_content }}" >> /tmp/fetched
  delegate_to: localhost
  run_once: true

相关问题