Ansible最佳实践 - 如何使用文件目录中的角色/文件?

时间:2018-05-09 12:04:27

标签: ansible

根据Best Practices我将脚本文件保存在角色/ X /文件结构中。所以我有:

  • 角色/ X /文件/
    • script.sh
    • library.sh
    • library2.sh

roles / X / tasks / main.yml 中,我调用脚本: - name: Do something script: script.sh --options

但是脚本中有一个库的来源。我想知道只有script.sh文件被复制到 remote_tmp /ansible-tmp-xxx/script.sh。 对于每个任务,将文件复制到另一个目录(另一个临时目录)。

这是正常行为吗?我想避免手动复制文件。

$ ansible --version ansible 2.4.0.0 ... python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

1 个答案:

答案 0 :(得分:1)

我的解决方案:

<强>角色/ X /文件/ test_lib.sh

#!/usr/bin/env bash
LIB="$HOME/.ansible/tmp/lib"
if [[ -f "$LIB/library.sh" ]]; then
    source "$LIB/library.sh"
    do_it
else
    echo "ERROR library.sh not found"
fi

<强>角色/ X /文件/ LIB / library.sh

do_it() {
    echo "I'm the library"
}

<强>角色/ X /任务/ main.yml

---
- name: Creates directory
  file:
    path: $HOME/.ansible/tmp
    state: directory
    recurse: yes
- name: Check if required files exist
  stat:
    path: $HOME/.ansible/tmp/lib/library.sh
  register: stat_lib_directory
- name: Copy library
  # this copies lib from $HOME!!!
  #command: cp -r lib/. $HOME/.ansible/tmp/
  copy:
    src: lib
    dest: $HOME/.ansible/tmp
    directory_mode: 0755
    mode: 0644
  when: stat_lib_directory.stat.exists == False
- name: Run the script on remote host
  script: test_lib.sh
  register: out
- debug: var=out.stdout_lines
- name: Cleaning
  file:
    path: $HOME/.ansible/tmp/lib
    state: absent

它终于奏效了:

$ ansible-playbook copy-dir.yml

PLAY [host] ****************************************************************************

TASK [copy-dir : Creates directory] ****************************************************
ok: [host]

TASK [copy-dir : Check if required files exist] ****************************************
ok: [host]

TASK [copy-dir : Copy library] *********************************************************
changed: [host]

TASK [copy-dir : Run the script on remote host] ****************************************
changed: [host]

TASK [copy-dir : debug] ****************************************************************
ok: [host] => {
    "out.stdout_lines": [
        "\u001b[?1034hI'm the library"
    ]
}

TASK [copy-dir : Cleaning] *************************************************************
changed: [host]

PLAY RECAP *****************************************************************************
host                       : ok=6    changed=3    unreachable=0    failed=0