我试图从不同目录中的另一个脚本调用 python 函数。有一个剧本来执行此操作。这在本地主机上工作正常,但在远程服务器上失败,并显示“ModuleNotFoundError:没有名为“script2”的模块”这是我的脚本:[root@server Test]# lshosts playbook python1 python2[root@server Test]# cat playbook/playbook.yml - hosts: "{{ host }}" gather_facts: yes become: yes vars: ansible_python_interpreter: /usr/bin/python3 tasks: - name: Connect to MongoDB script: ../python1/script1.py args: executable: python3[root@server Test]# cat python1/script1.py #!/usr/bin/pythonimport osimport syssys.path.append("../python2")from script2 import dbServerdef main(): cursor = dbServer() print(cursor.count())if __name__ == '__main__': main()[root@server Test]# cat python2/script2.py #! /usr/bin/pythonfrom pymongo import MongoClientdef connectToMongoDB(): global db try: conn = MongoClient("myserver.com") db = conn.CMDB except Exception as e: print("\nUnable to fetch details from MongoDB..!!!\n%s\n" % e) sys.exit()def dbServer(): connectToMongoDB() collection = db.dbServer cursor = collection.find() return cursor
1 回答
青春有我
TA贡献1784条经验 获得超8个赞
正如模块script文档中所解释的:path中的本地脚本将被传输到远程节点然后执行。
脚本中的任何导入文件都不会,您必须先使用 module 将它们复制到远程copy。
示例(根据需要调整访问模式和路径):
- hosts: "{{ host }}"
gather_facts: yes
become: yes
vars:
ansible_python_interpreter: /usr/bin/python3
tasks:
- name: Create directory
copy:
path: /tmp/python1
state: directory
mode: 0755
- name: Copy scripts
copy:
src: ../python1
dest: /tmp/python1
- name: Connect to MongoDB
script: ../python1/script1.py
args:
chdir: /tmp/python1
executable: python3
然而,通常最好编写 Ansible 模块而不是推送脚本。
您的脚本在本地运行,因为所有需要的导入文件都已存在
添加回答
举报
0/150
提交
取消