我可以复制文本从远程到本地与Ansible剧本?



我知道Ansible fetch模块可以将文件从远程复制到本地,但是如果我只需要将内容(在我的情况下是tmp文件,包含ip地址)附加到本地文件中怎么办?

Fetch模块这样做:

- 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

一句话:

- 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

最新更新