CodeShare
Have some code. Share some code.
cancel
Showing results for 
Search instead for 
Did you mean: 
PeteWhite
F5 Employee
F5 Employee

Problem this snippet solves:

This is a python module to simplify using iControl REST.

Install using pip:

pip install iCR


or retrieve from https://pypi.python.org/pypi?:action=display&name=iCR&version=2.1

As simple as:

#!/usr/bin/env python
from iCR import iCR
bigip = iCR("172.24.9.132","admin","admin")
virtuals = bigip.get("ltm/virtual")
for vs in virtuals['items']:
  print vs['name']

This prints out a list of Virtual Servers.

Supported methods:

  • init(hostname,username,password,[timeout,port,icontrol_version,folder,token,debug])
  • get(url,[select,top,skip,filter])
    -> returns data or False
  • getlarge(url,size,[select])
    -> Used to retrieve large datasets in chunks. Returns data or False
  • create(url,data)
    -> returns data or False
  • modify(url,data,[patch=True])
    -> returns data or False
  • delete(url)
    -> returns True or False
  • upload(file)
    -> file is a local file eg /var/tmp/test.txt, returns True or False
  • download(file)
    -> files are located in /shared/images, returns True or False
  • create_cert(files)
    -> files is an array containing paths to cert and key. Returns name of cert or False
  • get_asm_id(name)
    -> name is the name of a policy. Returns an array of IDs or False
  • create_hash(name)
    -> name is the name of the partition and policy. eg /Common/test_policy. This reduces the need to retrieve an array of hashes from the BIG-IP. Returns a string.
  • get_token()
    -> this retrieves a BIG-IP token based on the username and password and sets it as the token in use. Returns the token ID or False
  • delete_token()
    -> This deletes the object token from the BIG-IP and from the object
  • create_transaction() -> creates a transaction and returns the transaction number ID as a string, or False. Subsequent requests will be added to the  transaction until commit_transaction is called. Transaction ID is stored in object.transaction
  • commit_transaction() -> Commits the transaction stored in object.transaction. Returns True or False
  • command(args,[cmd]) -> Runs a command using the arguments string args. Returns the returned output or True on success or False on failure. 
  •  Note: Be sure to double-escape single quotes eg \\' and single escape double quotes eg \"  
  • cmd options are ping/save/load/restart/reboot

Module Variables:

  • icr_session - the link to the requests session
  • raw - the raw returned JSON
  • code - the returned HTTP Status Code eg 200
  • error - in the case of error, the exception error string
  • headers - the response headers
  • icontrol_version - set this to specify a specific version of iControl
  • debug - boolean True or False to set debugging on or off
  • port - set the port ( 443 by default )
  • folder - set this to create in a specific partition
  • token - use this to set a specific token. If this is set, it will be used instead of basic auth
  • select - use this with get to select the returned data
  • top - use this with get to return a set number of records
  • skip - use this to skip to a specific record number
  • transaction - stores the Transaction ID

How to use this snippet:

Examples

Setup a REST connection to a device

#!/usr/bin/env python
from iCR import iCR
bigip = iCR("172.24.9.132","admin","admin",timeout=10)

Create a Virtual Server

vs_config = {'name':'test_vs'}    
createvs = bigip.create("ltm/virtual",vs_config,timeout=5) 

Retrieve the VS we just created

virt = bigip.get("ltm/virtual/test_vs",select="name")
print "Virtual Server created: " + virt['name']

Set the timeout

bigip.timeout = 20

Now delete the VS we just created

delvs = bigip.delete("ltm/virtual/test_vs")

Retrieve ASM policy to ID mapping

policies = bigip.get("asm/policies",select="name,id")

Print a table of ASM policies with learning mode

print
print "Policy Name                  Learning Mode"
print "------------------------------------------"
for item in policies['items']:
    enabled = bigip.get("asm/policies/" + item['id'] + "/policy-builder",select="learningMode")
    print '{:32}'.format(item['name']) + enabled['learningMode']

File upload

fp = "/home/pwhite/input.csv"
if bigip.upload(fp):
    print "File " + fp + " uploaded"

File download

file="BIGIP-12.1.2.0.0.249.iso"
download = bigip.download(file)
if not download:
    print "File " + file + " download error"

SSL Certificate creation

In different folder

bigip.folder = "TestFolder"
files = ("TestCert.crt","TestCert.key")
cert = bigip.create_cert(files)
if cert:
    print "Certificate " + cert + " created" 

Turn on debugging

bigip.debug = True


Retrieve ASM policy IDs

asm = bigip.get_asm_id("dummy_policy")
print len(asm) + " IDs returned"
print "ID: " + str(asm[0])

Convert an ASM policy name to hash

hash = bigip.create_hash("/Common/test-policy")
enabled = bigip.get("asm/policies/" + hash + "/policy-builder",select="learningMode")
print '{:32}'.format(item['name']) + enabled['learningMode']

Retrieve and use a token

bigip.get_token()

Delete the token

bigip.delete_token()

Developed on Python 2.7 but works with v3. Works on TMOS 11.6 onwards though some features may not be implemented, such as tokens. If you use this and have found bugs, would like to discuss it or suggest features then please PM me on DevCentral.

Tested this on version:

13.0
Comments
no3am_307596
Nimbostratus
Nimbostratus

Hey Pete, I'm looking to upload SSL certificate and key, then add them to a virtual server, we're using the Python SDK, any thoughts?

 

PeteWhite
F5 Employee
F5 Employee

Yes, this is fairly simple - see here and here for uploading files via REST and adding of certs/keys are detailed at https://devcentral.f5.com/s/feed/0D51T00006i7Y3KSAU

 

Obviously you'd have to create the f5sdk commands for those URLs. Because f5sdk doesn't expose the http method directly but uses CURDLE methods so you would have to select the correct method to match your requirements. For instance you would probably use the create() method to use the POST HTTP method.

 

no3am_307596
Nimbostratus
Nimbostratus

fantastic your last comment helps clarify things.

 

it seems that the certificate should be on the host before I upload it, is there a way to upload it directly from my laptop?

 

Also.. THANK YOU for the prompt response.

 

PeteWhite
F5 Employee
F5 Employee

You can upload it to the BIG-IP using iControl REST or just use scp which may be simpler. Then create the SSL certs, SSL profile and add it to the VS.

 

I will think about adding a function to the iCR module to upload or download a file. Might come in handy

 

no3am_307596
Nimbostratus
Nimbostratus

thanks a lot, really really helpful

 

Cory_Blankenshi
Altostratus
Altostratus

Tried the "as simple as" code at the top that prints the virtual server names and I got the following error: TypeError: 'module' object is not callable. Debugging shows that the line of code throwing the error is "bigip = iCR("yadda", "yadda", "yadda")", with iCR being the module object that isn't callable.

 

Thoughts?

 

Also, I'm using Python 2.7. I have been using the f5-sdk package to date and doing what the sample script above does works without issue.

 

PeteWhite
F5 Employee
F5 Employee

TomServo3428 have you installed the iCR module successfully? Maybe you can PM me with some details and I can try it out myself.

 

Cory_Blankenshi
Altostratus
Altostratus

Hey Pete, For whatever reason, an error occurs every time I try to send you a direct message. Errors using iCR, errors trying to send messages on this site... maybe it's me? lol

 

Can you try sending me a message and I'll see if I can reply successfully to it?

 

Thanks

 

Cory_Blankenshi
Altostratus
Altostratus

Hey Pete, I decided to check out iCR once more and I used the "as simple as" example you posted above but I kept getting this error: "TypeError: 'module' object is not callable".

 

I did some digging on the error and per Stack Exchange, the error is caused because the iCR module you import and the iCR class you instantiate are the same name.

 

To instantiate the iCR class successfully, I updated your sample code to

 

bigip = iCR.iCR("172.24.9.132","admin","admin")

 

That is the only way I can run the code in Python 2.7.14 without error.

 

PeteWhite
F5 Employee
F5 Employee

Glad you've got it working Tom, i'll take a look into this. Feel free to let me know of any improvements that can be made.

 

PeteWhite
F5 Employee
F5 Employee

I've updated the module to add some functionality like uploading and downloading files as well as creating SSL certs and profiles, and retrieving an ASM ID from a policy name. Feel free to try it out and let me know what you think.

 

PeteWhite
F5 Employee
F5 Employee

Updated to fix a bug with modify not JSONifying the provided data

 

PeteWhite
F5 Employee
F5 Employee

Updated the module to 1.9 and added get_token and delete_token functions.

 

liuyi6324_37637
Nimbostratus
Nimbostratus

Hi Peter, does it only work on Python2 and Version13.0 or later?

 

PeteWhite
F5 Employee
F5 Employee

Hi liuyi6324, I have developed and tested this on Python 2 but i can't see why it wouldn't work on v3. The only issue might be the debug I guess - print is different in v3. If you can test it and let me know I will develop it so that it works in v3 as well. This will work in all versions after 11.5 as it uses the basic REST functionality.

 

PeteWhite
F5 Employee
F5 Employee

Hi liuyi6324, i've tested this with v3 and it seems to work OK - i've changed the print and except commands.

 

PeteWhite
F5 Employee
F5 Employee

Updated to v2.1 which adds transactions and is refactored to make more sense internally. Included examples etc as well.

tonygruz
Nimbostratus
Nimbostratus

typeerror: 'module' object is not callable

This error occurs when the python compiler gets confused between function name and module name and try to run a module name as a function. This error statement TypeError: 'module' object is not callable is raised as you are being confused about the Class name and Module name. The problem is in the import line . You are importing a module, not a class. This happend because the module name and class name have the same name .

If you have a class MyClass in a file called MyClass.py , then you should write:

from MyClass import MyClass

In Python , a script is a module, whose name is determined by the filename . So when you start out your file MyClass.py with import MyClass you are creating a loop in the module structure. Also, note that this usually happens when you import any kind of module as a function.

 

Version history
Last update:
‎05-Jun-2023 22:44
Updated by: