【问题标题】:Running Python script via ansible通过 ansible 运行 Python 脚本
【发布时间】:2016-05-10 10:42:14
【问题描述】:

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

这只是打印出“。”。太有帮助了...

【问题讨论】:

    标签: ansible ansible-2.x


    【解决方案1】:

    尝试使用 script 指令,它对我有用

    我的 main.yml

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

    get-pip.py 文件应该在 files 中具有相同的角色

    【讨论】:

    • 这是更好的答案,我什至不确定为什么我没有建议它,而是更密切地遵循 OP 的原始代码。使用角色,然后使用它们周围的语法糖,例如脚本/文件和模板的搜索路径等。
    • 此解决方案在远程主机上运行脚本。 @ydaetskcoR 解决方案在本地(管理)主机上运行。
    • 如果我试图运行它,我会收到错误名称:使用系统路径脚本中的可执行文件运行脚本:/home/user/sample.py args:可执行文件:python2.7跨度>
    • 我创建了另一个 python 脚本来编写一个运行良好的文件,但不明白为什么我没有看到打印语句
    【解决方案2】:

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

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

    - name: run my script!
      command: ./mypythonscript.py
      args:
        chdir: "{{ role_path }}"/files
      delegate_to: 127.0.0.1
      run_once: true
    

    【讨论】:

    • 这会搞砸我打算在其中运行 python 脚本的目录,但我想我可以将它作为参数传递给 python 脚本。谢谢!
    • 如果您的 Python 脚本需要从某个特定路径运行,只需将 command 行更改为 command: ./"{{ role_path }}"/files/mypythonscript.py(显然将 chdir 参数更改为您想要的路径)
    • 我希望 chdir 的整个值都应该用双引号引起来,这样可以防止语法错误。
    • 我无法理解角色路径是什么。我正在尝试运行 ansible 服务器 /home/user 上的 python 脚本。但如果我提供路径它不起作用。我收到错误
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多