31

我正在尝试从 ansible 脚本运行 python 脚本。我认为这将是一件容易的事,但我无法弄清楚。我有一个这样的项目结构:

playbook-folder
  roles
    stagecode
      files
        mypythonscript.py
      tasks
        main.yml
  release.yml

我正在尝试在 main.yml 的任务中运行 mypythonscript.py(这是 release.yml 中使用的角色)。这是任务:

- name: run my script!
  command: ./roles/stagecode/files/mypythonscript.py
  args:
    chdir: /dir/to/be/run/in
  delegate_to: 127.0.0.1
  run_once: true

我也试过../files/mypythonscript.py。我认为 ansible 的路径与剧本有关,但我猜不是?

我还尝试调试以找出我在脚本中间的位置,但也没有运气。

- name: figure out where we are
  stat: path=.
  delegate_to: 127.0.0.1
  run_once: true
  register: righthere
    
- name: print where we are
  debug: msg="{{righthere.stat.path}}"
  delegate_to: 127.0.0.1
  run_once: true

那只是打印出“。”。很有帮助...

4

3 回答 3

59

尝试使用脚本指令,它适用于我

我的 main.yml

---
- name: execute install script
  script: get-pip.py

get-pip.py文件应该在同一个角色的文件中

于 2016-11-11T13:49:56.427 回答
14

如果您希望能够使用脚本的相对路径而不是绝对路径,那么您最好使用role_path魔法变量来找到角色的路径并从那里开始工作。

使用您在问题中使用的结构,以下应该可以工作:

- name: run my script!
  command: ./mypythonscript.py
  args:
    chdir: "{{ role_path }}"/files
  delegate_to: 127.0.0.1
  run_once: true
于 2016-02-01T20:48:09.887 回答
2

另一种/直接的解决方案:假设您已经在 ./env1 下构建了虚拟环境,并使用 pip3 安装了所需的 python 模块。现在编写剧本任务,例如:

 - name: Run a script using an executable in a system path
  script: ./test.py
  args:
    executable: ./env1/bin/python
  register: python_result
  
  - name: Get stdout or stderr from the output
    debug:
      var: python_result.stdout
于 2021-06-08T15:21:12.083 回答