Contents


Streamline your operations with IBM SoftLayer tagging

Use Softlayer APIs with Python to tag and list devices

Comments

In this tutorial, we show you how to use IBM SoftLayer APIs to tag and list devices using the Python programming language. Tagging enables you to identify your cloud infrastructure assets, which helps facilitate other business processes like reporting and billing. We provide detailed instructions for installing the required Python and SoftLayer packages, and we describe several use cases that cover various scenarios, such as setting and deleting tags and listing devices associated with tags by calling the respective APIs.

The tagging service available through SoftLayer gives you the ability to tag devices with keywords that can later be used in searching. Tagging is an important concept in the cloud world, and an increasing number of developers are using it to address key business requirements. Basically, the business need is two-fold:

  • Clients need to identify their cloud assets, such as virtual machines, bare metal storage nodes, and so on. A client who has hundreds of such assets would need a convenient way to identify them.
  • Many clients are troubled by billing requirements, which can become complicated depending upon an organization's structure—which may be split into business lines, cost centers, divisions, etc. By enabling devices to be tagged with keywords for convenient searching, tagging can often provide a helpful solution.

We will provide a practical demonstration of how SoftLayer tagging works. We'll cover use cases related to implementing tags with cloud assets (such as virtual instances and bare metals), and show you how to retrieve assets based on the type of user (normal or master) or tag name. The result can then be used for reporting and billing purposes. The code examples used here are written in Python.

Basic terms

Let's define a few basic terms used in this context:

Virtual Server Instance (VSI)—SoftLayer VSIs deliver a higher degree of customization, transparency, predictability, and automation than other cloud services providers; they integrate seamlessly with SoftLayer bare metal servers.

SoftLayer tagging service—As noted above, the tagging service gives users the ability to tag devices with keywords that can later be used to search. It provides methods that can be called using APIs.

API User Name—The API user name is the user who has access to the devices and sets the tags.

API Key Name—An API key is a hexadecimal string of characters that is unique to each user. This key acts as authentication for performing operations using APIs. If a wrong key is provided, then SoftLayer APIs will not allow the requested operation.

Key information related to tags

  • A tag can contain a maximum of 128 characters.
  • The upper limit for the number of tags that can be added to a device is not documented, however we have added up to 100 tags successfully.
  • Tags can only be added to devices in lowercase. If an uppercase tag name is passed, then it will be automatically converted to lowercase.
  • Underscores in a tag are allowed, but other special characters are ignored. For example, the name "a*b&c" would be converted to "abc" before being tagged; the special characters present in the tag would be ignored.
  • A master user can list devices for tags that belong to users created under the master user.
  • The tagging API does not support deletion of tags. Individual tags for devices can be deleted using a GUI. Alternatively, the SetTags method can be used to delete all tags by passing the tag name as a blank.

Get the code: ServerTagging.pyGet the code: SetServerTags.py

What you'll need

  • Access to the SoftLayer API key:
    1. Access the SoftLayer portal and log in with valid credentials.
    2. Navigate to Account > Users. You will then see a list of available users.
    3. To view the API key for any user, click on View Link on the respective row under the API Key column.
  • Python 2.7 or above—Python is a simple and easy-to-learn object-oriented language that is ideal for scripting. SoftLayer provides a Python-based API package that can be used to make API calls.
  • get-pip.py—pip is a package management system that's used to install packages written in Python. By downloading and installing the get-pip.py file, you install pip, which in turn can be used to install the SoftLayer package (see below).
  • ServerTagging.py and SetServerTags.py—These are Python scripts. SetServerTags.py sets the tags on devices, and ServerTagging.py retrieves the devices associated with tags based on the arguments passed to it.

In the remainder of this tutorial, we begin by listing the software that you need to install and run in order to explore various uses of the SoftLayer tagging service. We then show you a series of commands for creating and using tags, followed by some sample code listings for associating devices with tags.

Install the software

Step 1. Install Python 2.7 or above

  1. Log in as the root user on the system.
  2. Make sure the following packages are installed on the system:
    • gcc
    • openssl
    • openssl-devel
  3. Download Python 2.7:
    wget -c https://www.python.org/ftp/python/2.7.10/Python-2.7.10.tgz
  4. Untar the Python 2.7 binaries:
    tar xzf Python-2.7.10.tgz
  5. Configure and install Python:
    cd Python-2.7.10
    ./configure
    make altinstall
  6. Check if Python 2.7 has been successfully installed:
    python2.7 -V

Step 2. Install pip

Download the get-pip.py file and install it:

wget -c https://bootstrap.pypa.io/get-pip.py
python2.7 get-pip.py

Step 3. Install the SoftLayer package

python2.7 -m pip install SoftLayer

Step 4. Install the argument parser

python2.7 -m pip install argparse

Use cases

Use cases for tagging can be classified into three categories:

  • Add tags to devices
  • List devices based on tags
  • Remove tags from devices

Add tags to devices

Add a tag to a single device

#python2.7 SetServerTags.py -user masteruser1 -apiKey  
<Api Key>  -tag 'tagA' -fqdn sepbmi1.ibm.com

This command results in the following output. The commands that follow result in similar output.

Add multiple tags to a given device

python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag 'tag1,tag2,tag3' -fqdn hostbmi1.example.com

Add multiple tags to multiple devices

#python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag 'tag1,tag2,tag3' -fqdn 'hostbmi1.example.com,sepbmi1.ibm.com'

Add tags to all the devices belonging to a user

#python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag 'tagB'

List all devices with a given tag

#python2.7 ServerTagging.py -user masteruser1 -apiKey <Api Key>  -tag 'tag1'

Remove tags from devices

Delete tags from a given device

python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag '' -fqdn hostbmi1.example.com

Delete tags from multiple devices

#python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag '' -fqdn 'hostbmi1.example.com,sepbmi1.ibm.com'

Delete all tags from all devices

# python2.7 SetServerTags.py -user masteruser1 -apiKey <Api Key>  -tag ''

Sample code

This section contains Python-based application code that demonstrates the use of SoftLayer APIs for tagging. These code samples pass the username (‑user), API key (‑apiKey), tag (‑tag), and host name of the device (‑fqdn) as arguments to the SetServerTags.py and ServerTagging.py scripts discussed above. SetServerTags.py sets the tags on devices, and ServerTagging.py retrieves the devices associated with tags based on the arguments passed. The scripts then import the SoftLayer package and parse the arguments. The username and API key are used to perform authentication and create a client object, after which appropriate APIs are called to set the tags on devices or retrieve devices associated with specific tags.

Python code to get devices associated with tags

#Importing required libraries
import argparse
import SoftLayer
import sys
#Set up the argument parser to accept the command line arguments passed to the Python script. 
parser = argparse.ArgumentParser(description='Welcome !! This script fetches Server details based on Tagging')
parser.add_argument('-user',action='append', type=str,  help='Input for User name')
parser.add_argument('-apiKey',action='append', type=str,  help='Input for API Key')
parser.add_argument('-tag',action='append', type=str,  help='Input for tag name')
parser.add_argument('-fqdn',action='append', type=str,  help='Input for Device fqdn')
args = parser.parse_args()
apiUsername =  args.user[0]
apiKey = args.apiKey[0]
tagName =  args.tag[0]
#Pass Username and apiKey to the SoftLayer.client method to get Client details 
client = SoftLayer.Client(username=apiUsername, api_key=apiKey)
#Check if the authentication is successful using the client object
userId = client['Account'].getCurrentUser(mask='id')
#Get the tag data from the client object by calling getTagByTagName method
tagData = client['Tag'].getTagByTagName(tagName,filter={'references':{'usrRecordId':userId}})
# Get the ID of the tag and store all the references of the tag in the devices variable
tagId = tagData[0]['id']
devices = client['Tag'].getReferences(id=tagId,mask='resourceTableId')
#Use a for loop to browse through all the devices, and fetch the device fqdn
for each in devices:
devicefqdn=client['Hardware'].getObject(id=each['resourceTableId'],mask='fullyQualifiedDomainName')

Python code to associate a device with a tag

#Steps are same here till the checking of authentication
# Get all servers belonging to the User using the getHardware method
serverIds = client['Account'].getHardware(mask='id,fullyQualifiedDomainName')
# To set tag on a device or multiple devices
for each in serverIds:
if (each['fullyQualifiedDomainName'] in fqdn or each['fullyQualifiedDomainName'] == fqdn): #tag is added to required fqdn
			try:
				setTag = client['Tag'].setTags(tagName,'HARDWARE',each['id'],'lll')
setTag = client['Tag'].setTags(tagName,'HARDWARE',each['id'],'lll')
# To set tags on all the devices belonging to a user
for each in serverIds:
		try:
			setTag = client['Tag'].setTags(tagName,'HARDWARE',each['id'],'lll')

Conclusion

This tutorial introduced you to SoftLayer tags and showed you how to associate tags using APIs and how to retrieve tags from APIs. In addition, we explored various use cases involving adding, listing, and deleting tags. We hope that this brief discussion of the power of SoftLayer tagging has enhanced your understanding of tagging and shown you how it can help streamline your business operations.

In closing, we would like to thank two co-workers whose support and help are much appreciated:

  • Vivekanandan Subramanian – Executive Architect, Cloud Tech Sales, IBM
  • Prabhakar Attaluri – Distinguished Engineer, Cloud Tech Sales, IBM

Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing
ArticleID=1035636
ArticleTitle=Streamline your operations with IBM SoftLayer tagging
publish-date=08092016