首页 > 解决方案 > Ansible 最佳实践 - 如何使用文件目录中的角色/文件?

问题描述

根据最佳实践,我将脚本文件保存在角色/X/文件结构中。所以我有:

角色/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)]

标签: ansible

解决方案


我的解决方案:

角色/X/files/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/files/lib/library.sh

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

角色/X/tasks/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

推荐阅读