使用Ansible复制/移动文件

问题描述:

我正在使用Ansible,并且想使用Ansible作业本中的Ansible角色中的以下代码复制或移动文件。使用Ansible复制/移动文件

- name: Backing up existing ~/.zshrc 
    shell: if [ -f ~/.zshrc ]; then cp ~/.zshrc{,.orig}; fi 
    become: true 
    become_user: root 
    when: installation|success 

但是,当我运行它时出现此错误,我在做什么错?

fatal: [localhost]: FAILED! => 
{ 
    "changed":true, 
    "cmd":"if [ -f ~/.zshrc ]; then cp ~/.zshrc{,.orig}; fi", 
    "delta":"0:00:00.002640", 
    "end":"2017-04-11 12:32:35.886640", 
    "failed":true, 
    "rc":1, 
    "start":"2017-04-11 12:32:35.884000", 
    "stderr":"cp: missing destination file operand after '/root/.zshrc{,.orig}'\nTry 'cp --help' for more information.", 
    "stderr_lines":[ 
     "cp: missing destination file operand after '/root/.zshrc{,.orig}'", 
     "Try 'cp --help' for more information." 
    ], 
    "stdout":"", 
    "stdout_lines":[ 

    ] 
} 
+0

我想标准错误说清楚,缺少'cp'命令目的地: 'CP〜/ .zshrc {,原稿} DESTINATION' – oryades

+0

然而,当我试图在本地运行的命令,它的工作就好了,它按照预期为我复制了文件。 – dwardu

并非所有shell都支持括号扩展,你可以在错误信息cp: missing destination file operand after '/root/.zshrc{,.orig}'看到,它采取的论点从字面上。

添加以下作为参数传递给该shell模块运行在击的命令(当然前提是击安装在目标):

executable: /bin/bash 

不过总的来说这是不在Ansible中最优雅的方式。令人不安的是你为什么需要在Ansible剧本中完成这样的任务?如果要在其他任务(应该修改.zshrc文件)之前进行备份,那么修改文件的大多数(如果不是全部)Ansible模块都会提供一个backup切换器来自动保存以前的版本。

+0

谢谢你,我试了一下,它的工作,但是因为你提到支架扩展不是通用的,那么我会避免使用它的应该是普遍的脚本。谢谢! – dwardu