首页 文章

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

提问于
浏览
0

我使用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

exception

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 回答

  • 2

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

    - 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
    

    如果可能,请在playbook中插入“成为”,而不是在tasks / main.yml文件中,除非您只想使用for这两个任务,并且稍后会在同一个剧本中添加更多任务 .

    Note :调试消息行完全是可选的 . 它不会以任何方式影响playbook的结果,它只会显示由于shell "ls"命令而找到的文件夹/文件名 .

  • 1

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

相关问题