首页 > 解决方案 > 如何使用 Ansible Playbook 导入 python 文件?

问题描述

这是在 Linux 机器上。我有一个这样的 run.yml

---
- name: Appspec
  hosts: localhost
  become: true

  tasks:
  - name: test 1
    script: test.py

test.py 通过“import helper”使用了一个 python 文件(helper.py),该文件与 ansible-playbook 位于同一路径中,并且在运行 playbook.yml 时它仍然给我一个“导入错误:无法导入名称助手”。我该怎么做?

标签: pythonlinuxansible

解决方案


将两者复制test.py并复制helper.py到远程计算机上的同一目录(可能复制到临时目录)并python test.py作为command任务运行。像这样的东西:

- name: Create temporary directory
  tempfile:
    state: directory
  register: tmpdir

- name: Copy test.py
  copy:
    src: /wherever/test.py
    dest: "{{tmpdir.path}}/test.py"

- name: Copy helper.py
  copy:
    src: /wherever/helper.py
    dest: "{{tmpdir.path}}/helper.py"

- name: Run test.py
  command: python test.py
  args:
    chdir: "{{tmpdir.path}}"

推荐阅读