通过ansible运行Python脚本

Cor*_*han 20 ansible ansible-2.x

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

playbook-folder
  roles
    stagecode
      files
        mypythonscript.py
      tasks
        main.yml
  release.yml
Run Code Online (Sandbox Code Playgroud)

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

- 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
Run Code Online (Sandbox Code Playgroud)

我也试过../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
Run Code Online (Sandbox Code Playgroud)

那只是打印出".".非常有帮助......

小智 36

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

我的main.yml

---
- name: execute install script
  script: get-pip.py
Run Code Online (Sandbox Code Playgroud)

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

  • 该解决方案在远程主机上运行脚本。@ydaetskcoR 解决方案在本地(管理)主机上运行。 (2认同)

yda*_*coR 13

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

使用您在问题中使用的结构,以下内容应该有效:

- name: run my script!
  command: ./mypythonscript.py
  args:
    chdir: "{{ role_path }}"/files
  delegate_to: 127.0.0.1
  run_once: true
Run Code Online (Sandbox Code Playgroud)