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

时间:2016-10-06 20:44:05

标签: ansible ansible-playbook ansible-2.x

我使用ansible 2.1来rsync或将文件从主机复制到远程机器。该文件位于目录中,但随机字符串作为其名称的一部分。我尝试使用 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"}

2 个答案:

答案 0 :(得分:2)

如果可能,你应该避免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 - 我把它用作安全网,只过滤第一个条目,如果有很多。< / p>

答案 1 :(得分:1)

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

- 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

如果可能,请插入&#34;成为&#34;在你的playbook中,而不是在你的tasks / main.yml文件中,除非你只想用于这两个任务,并且稍后会在同一个剧本中添加更多的任务。

注意:调试消息行完全是可选的。它不会以任何方式影响剧本的结果,它只会显示由于shell而导致的文件夹/文件名&#34; ls&#34;命令。