我正在尝试从 ansible 脚本运行 python 脚本。我认为这很容易做到,但我想不通。我有一个这样的项目结构:
playbook-folder
roles
stagecode
files
mypythonscript.py
tasks
main.yml
release.yml
我正在尝试在 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
我也试过../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
这只是打印出“.”。很有帮助...
尝试使用script指令,它对我有用
我的 main.yml
---
- name: execute install script
script: get-pip.py
和 get-pip.py 文件应该在 files 中以相同的角色
替代/直接解决方案: 假设您已经在 ./env1 下构建了虚拟环境,并使用 pip3 安装了所需的 python 模块。 现在编写 playbook 任务,如:
- 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
如果你想在没有单独的脚本文件的情况下执行内联脚本(例如,作为
molecule
测试)你可以这样写:
- name: Test database connection
ansible.builtin.command: |
python3 -c
"
import psycopg2;
psycopg2.connect(
host='127.0.0.1',
dbname='db',
user='user',
password='password'
);
"
您甚至可以在此字符串中插入 Ansible 变量。
要通过 Ansible 运行 Python 脚本,您可以使用 Ansible 中的命令或脚本模块。
- name: Execute Python script
hosts: target_hosts
gather_facts: false
tasks:
- name: Run Python script
command: python /path/to/script.py
或者,如果你想在目标主机上执行本地脚本文件,你可以使用脚本模块。这是一个例子:
- name: Execute Python script
hosts: target_hosts
gather_facts: false
tasks:
- name: Run Python script
script: /path/to/local_script.py
如果您的脚本逻辑可以表示为一行代码,那么下面的代码呢?
- name: " Attempt to acquire hw vendor "
shell: |
sudo /usr/sbin/dmidecode | /usr/bin/grep Vendor > /var/tmp/machine_Vendor.txt
become: true