我試圖從不同目錄中的另一個腳本調用 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
提交
取消