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

Ansible中能否用register动态指定文件源?报错求助

Ansible动态指定copy模块源文件的正确方法

Ansible完全支持使用变量动态指定文件源,你遇到的报错是YAML语法规则导致的:当值以{{开头时,必须用引号将整个字符串包裹,否则YAML解析器会误将其识别为字典结构,引发语法错误。

正确写法

把src的值用双引号或单引号括起来即可,修改后的copy任务如下:

- name: copy file with number
  copy:
    src: "{{ host_output.stdout }}.txt"
    dest: /tmp/reg_role.txt

修改后的完整Playbook

- name: conf_files
  hosts: all

  tasks:
    - name: tracing
      shell: |
        date +%F_%T >> /tmp/ansible_record.log

    - name: get host role
      shell: |
        /opt/userlib/getrolename|sed "s/rolename://"
      register: host_output
      # 可选:如果获取角色名失败,直接终止任务
      failed_when: host_output.stdout == ""

    - name: check output
      debug:
        msg: "{{host_output.stdout}}"

    - name: copy file with number
      copy:
        src: "{{ host_output.stdout }}.txt"
        dest: /tmp/reg_role.txt
        # 可选:如果源文件不存在时不报错,可加上ignore_errors: yes
        # ignore_errors: yes

额外注意事项

  • 确保控制节点上存在对应角色名的文件(比如获取到web1,则控制节点需要有web1.txt),否则copy模块会抛出文件不存在的错误。
  • 可以添加failed_when条件,在角色名获取失败时直接终止任务,避免后续无效执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:31:03