You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible复制远程主机文件排序内容时出现异常结果求助

解决Ansible按行排序文件内容并写入目标文件的问题

问题根源

原Playbook里的lookup('file', '/tmp/test')|sort直接对字符串使用sort过滤器,Ansible会把整个文件内容拆成单个字符逐一排序,这就是你得到一堆零散字符列表的原因。

正确解法

需要先把文件内容按行拆分成列表,对行列表排序,再拼接成带换行的字符串,最后写入目标文件。同时要修正copy模块的错误参数:

修改后的Playbook:

- hosts: all
  gather_facts: yes
  become: true
  vars:
    # 1. 读取文件内容并按行拆分
    # 2. 对行列表进行排序
    # 3. 用换行符拼接成完整字符串
    sorted_file_content: "{{ lookup('file', '/tmp/test').splitlines() | sort | join('\n') }}"

  tasks:
    - name: 将排序后的内容写入目标文件
      copy:
        content: "{{ sorted_file_content }}"
        dest: /tmp/test_sort
        # 移除remote_src: yes,因为我们是用content生成内容,不是复制远程文件

验证结果

执行修改后的Playbook后,/tmp/test_sort的内容会是按行排序后的结果:

@chicken
ananas
apple
banana
car
juice

内容的提问来源于stack exchange,提问作者medisamm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:57:17