1

Warning: very new to python

I am trying to connect to a series of IP addresses stored in an array ${INSTANCE_IPS[@]}. I am trying to use a for loop to use a python script to call an API to each IP address in the array.

However, when trying to run the below script I get the error:

Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

I'm sure I could do a for loop in python but I haven't learnt that yet and for the moment just need to get this working. It runs fine if I only use one IP address from the array.

for instance in ${INSTANCE_IPS[@]}
do
  echo "Connecting to $instance"

  /usr/bin/python << END_OF_PYTHON

  import requests
  import json
  import sys
  import socket
  import fnmatch
  import os

  ipaddress = os.getenv('instance')
  print ipaddress

  port = ':80'
  updatedipaddress = ipaddress +port
  print 'updated ip address is ' + updatedipaddress

  add_node = updatedipaddress

  print 'add_node is ' + add_node

  url = 'https://' + os.getenv('instance') + ':9070/api/tm/1.0/config/active/pools/' + 'aol_http'
  print 'url is ' + url
  jsontype = {'content-type': 'application/json'}
  client = requests.Session()
  client.auth = ('username', 'password')
  client.verify = 0

  response = client.get(url)
  print response
  pools = json.loads(response.content)
  nodes = pools['properties']['basic']['nodes']

  data = nodes
  data.append(unicode(add_node))

  client.put(url,json.dumps(pools), headers=jsontype)
  END_OF_PYTHON
done  

Any help with figuring out where I am going wrong would be appreciated.

Cheers

1
  • END_OF_PYTHON may not be indented (unless by one or more tabs and you use <<-END_OF_PYTHON as the beginning of the here document). Commented May 4, 2014 at 14:27

1 Answer 1

5

The bash variable instance is not passed on to subprocesses. You have to export it before starting the python code. This can be seen in the error message about ipaddress + port as ipdadress is of NoneType meaning that os.getenv() did not work.

for instance in ${INSTANCE_IPS[@]}
do
  echo "Connecting to $instance"
  export instance

  /usr/bin/python << END_OF_PYTHON
   [...]
Sign up to request clarification or add additional context in comments.

1 Comment

Or he could use the shell variable directly in the heredoc, like url = 'https://${instance}:9070/....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.