简体   繁体   中英

How do I get Ansible to pass a variable into Python Script that has an Input Function?

I have tried to run a Python script in Ansible. The script works by itself. When I run it in the playbook it gives me the following error:

line 14, in <module>\n    revisionamount = input(\"Please enter how much you want to increase VTP revision by times 2: \")\nEOFError: EOF when reading a line\n"
---
- hosts: CML_DR_01
  gather_facts: no
  connection: network_cli

  - name: Run Python Script to Increase Revision Number
    script: ./Scripts/DR_VTP_Revision_Ver_2.py
    args:
      executable: python3

DR_VTP_Revision_Ver_2.py Script:

from netmiko import ConnectHandler

DR_01 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.200',
    'username': 'cisco',
    'password': 'cisco123'
}

all_devices = [DR_01]

n = 999

revisionamount = input("Please enter how much you want to increase VTP revision by times 2: ")
revisionamount = int(revisionamount)

for devices in all_devices:
    net_connect = ConnectHandler(**devices)
    for count in range (revisionamount):
       print ("Creating VLAN " + "999")
       config_commands = ['vlan ' + str(n), 'name Ansible_' + str(n)]
       output = net_connect.send_config_set(config_commands)
       print(output) 
       print ("Deleting VLAN " + "999")
       config_commands = ['no vlan ' + str(n)]
       output = net_connect.send_config_set(config_commands)
       print(output)

Don't use input() ; the code runs on a remote node in a non-interactive session.

Use sys.argv or, better argparse

Then you can pass in Ansible like this with a templated variable (or a constant)

You could also have Ansible itself ask for the prompt, then assign that to the value for the script task - https://docs.ansible.com/ansible/latest/user_guide/playbooks_prompts.html

script: ./Scripts/DR_VTP_Revision_Ver_2.py --revisions={{ some_value }}

Also, you'll need to ensure that netmiko module exists on the host(s) you are running the script on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM