ansible rsync 或将随机命名的文件复制到远程计算机

ansible rsync or copy a randomly named file to a remote machine

我正在使用 ansible 2.1 将文件从主机同步或复制到远程主机。该文件位于一个目录中,但其名称中包含一个随机字符串。我尝试使用 ls -d 通过 shell 命令获取名称并尝试注册此值,但显然,我使用的语法导致角色失败。关于我可能做错了什么的任何想法?

---
- name: copying file to server 
- local_action: shell cd /tmp/directory/my-server/target/
- local_action: shell ls -d myfile*.jar
  register: test_build
- debug: msg={{ test_build.stdout }}
- copy: src=/tmp/directory/my-server/target/{{ test_build.stdout }}  dest=/home/ubuntu/ owner=ubuntu group=ubuntu mode=644 backup=yes
  become: true
  become_user: ubuntu 
  become_method: sudo

异常

fatal: [testserver]: FAILED! => {"failed": true, "reason": "no action detected in task. This often indicates a misspelled module name, or incorrect module path.\n\nThe error appears to have been in '/home/user/test/roles/test-server/tasks/move.yml': line 2, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n---\n- name: transferring file to server\n  ^ here\n\n\nThe error appears to have been in '/home/user/test/roles/test-server/tasks/synchronize.yml': line 2, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n---\n- name: transferring artifact to server\n  ^ here\n"}

您需要简化命令。您也不想在模块名称前加上连字符。这将导致语法错误,因为它无法将该模块识别为操作。每个任务只能调用一个模块。例如,这将不起作用;

- name: task one
  copy: src=somefile dest=somefolder/
  copy: src=somefile2 dest=somefolder2/

这两个需要分成两个单独的任务。你的剧本也一样。执行以下操作:

  - name: copying file to server 
    local_action: "shell ls -d /tmp/directory/my-server/target/myfile*.jar"
    register: test_build
  - debug: msg={{ test_build.stdout }}

  - name: copy the file
    copy: src={{ test_build.stdout }}  dest=/home/ubuntu/ owner=ubuntu group=ubuntu mode=644 backup=yes

如果可能,请将 "become" 插入您的剧本而不是您的 tasks/main.yml 文件,除非您只想将 become 用于这两个任务并将向同一个剧本添加更多任务稍后。

注意:调试消息行是完全可选的。它不会以任何方式影响剧本的结果,它所做的只是向您显示 folder/file 名称,该名称是通过 shell "ls" 命令找到的。

您应该尽可能避免使用 shell 命令,这是 Ansible 反模式。
在您的情况下,您可以使用 fileglob lookup 如下所示:

- name: Copy file 
  copy:
    src: "{{ lookup('fileglob','/tmp/directory/my-server/target/myfile*.jar', wantlist=true) | first }}"
    dest: /home/ubuntu/
    owner: ubuntu
    group: ubuntu
    mode: 644
    backup: yes

如果你 100% 确定只有一个这样的文件,你可以省略 wantlist=true| first – 我用它作为安全网只过滤第一个条目,如果有很多.