cancel
Showing results for 
Search instead for 
Did you mean: 
susilsi7
Cadet
Cadet
  • 5,808 Views

Import error while running custom python script using ansible script module

Jump to solution

Directory Structure:

    |-- Script
    |   |-- Name.py
    |   |-- Name.pyc
    |   |-- Test.py
    |   |-- __init__.py
    |   `-- __pycache__
    |       `-- Name.cpython-36.pyc
    |-- SimplePlaybook.yml
    |-- ansible.cfg
    |-- ansible_log.log
    |-- hosts

Script Folder:

Name.py

    student_name = "Jhon Doe"

Test.py

    import Name
        
    print("My Name is %s \n" % Name.student_name)
        
    sys.exit({"rc": 0, "changed": True})

Playbook:

---

-

  hosts: HOST
  gather_facts: True

  tasks:

    - name: Print Gathered Facts
      debug:
        var: hostvars

    - debug: 
        msg: "{{ playbook_dir }}"

    - name: Run Test Script
      script: "{{ playbook_dir }}/Script/Test.py"
      register: result
      args:
        executable: python3

    - debug:
        var: result

...

Issue:

import error of Name.py, module not found

Solution ??

Labels (1)
0 Kudos
1 Solution

Accepted Solutions
jthiatt
Flight Engineer Flight Engineer
Flight Engineer
  • 5,794 Views

Couple of things, your Python path is getting lost so you need to set an environment variable

    
---
- hosts: localhost
  gather_facts: True

  tasks:  
  - name: Run Test Script
      script: "{{ playbook_dir }}/Script/Test.py"
      register: result
      args:
        executable: /usr/local/bin/python3
      environment:
        - PYTHONPATH: "{{ playbook_dir }}/Script/"

And I'm not sure what you are trying to do with sys.exit. sys.exit should just take an integer. Exiting with a 0 means that program ran successfully.

import Name

print("My Name is %s \n" % Name.student_name)

print('{"rc": 0, "changed": True}')

exit(0)

View solution in original post

2 Replies
jthiatt
Flight Engineer Flight Engineer
Flight Engineer
  • 5,795 Views

Couple of things, your Python path is getting lost so you need to set an environment variable

    
---
- hosts: localhost
  gather_facts: True

  tasks:  
  - name: Run Test Script
      script: "{{ playbook_dir }}/Script/Test.py"
      register: result
      args:
        executable: /usr/local/bin/python3
      environment:
        - PYTHONPATH: "{{ playbook_dir }}/Script/"

And I'm not sure what you are trying to do with sys.exit. sys.exit should just take an integer. Exiting with a 0 means that program ran successfully.

import Name

print("My Name is %s \n" % Name.student_name)

print('{"rc": 0, "changed": True}')

exit(0)
susilsi7
Cadet
Cadet
  • 5,785 Views

when ansible excute Test.py , it thoughs an error in first line as it unble to find Name module. 

0 Kudos
Join the discussion
You must log in to join this conversation.