通过ansible运行Python脚本

通过ansible运行Python脚本,ansible,ansible-2.x,Ansible,Ansible 2.x,我正在尝试从ansible脚本运行python脚本。我想这是件容易的事,但我想不出来。我有这样一个项目结构: playbook-folder roles stagecode files mypythonscript.py tasks main.yml release.yml 我正在尝试在main.yml中的任务中运行mypythonscript.py(这是release.yml中使用的角色)。任务如下: - name: r

我正在尝试从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

那只是打印出来的“.”。非常有用…

如果您希望能够使用脚本的相对路径而不是绝对路径,那么您最好使用找到角色的路径并从中开始工作

根据您在问题中使用的结构,以下内容应适用:

- name: run my script!
  command: ./mypythonscript.py
  args:
    chdir: "{{ role_path }}"/files
  delegate_to: 127.0.0.1
  run_once: true
尝试使用指令,它对我有效

我的主要朋友

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

get pip.py文件应在文件中担任相同角色

一种替代/直接解决方案: 假设您已经在./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

这会破坏我打算在其中运行python脚本的目录,但我想我可以将其作为参数传递给python脚本。谢谢然后,如果需要从某个特定路径运行Python脚本,只需将
命令
行更改为
命令:./“{{role_path}}”/files/mypythonscript.py
(显然,将
chdir
参数更改为您想要的路径)我希望chdir的整个值应该是双引号,这样可以防止语法错误。我不知道什么是角色路径。我正在尝试运行ansible server/home/user上的python脚本。但如果我提供路径,它将不起作用。我得到了错误这是更好的答案,我甚至不知道我为什么不建议它,除了更密切地遵循OP的原始代码。使用角色,然后在角色周围使用语法糖,例如脚本/文件和模板的搜索路径等。此解决方案在远程主机上运行脚本@ydaetskcoR解决方案在本地运行(管理)如果我试图运行此脚本,我会得到错误名称:使用系统路径脚本中的可执行文件运行脚本:/home/user/sample.py args:executable:python2.7I创建另一个python脚本来编写一个运行良好的文件,但我不明白为什么我看不到打印报表