Bluemix-IaaS(旧SoftLayer)のインスタンスをキャンセルするスクリプト

#内容
Bluemix IaaS（旧SoftLayer）のインスタンスを、API経由でキャンセルを実施してみました。

#前提
以下の記事が理解できていることが前提です。
Bluemix Infrastructure (旧SoftLayer) のAPIについて、詳しく解説してあります。
><a href="http://qiita.com/testnin2/items/f04ca0cee9b2f0a8f830" >ShinobiLayer: SoftLayer API 次の一歩: データ型オブジェクト(1) - Qiita</a>

#BillingItemIdの取得
デバイスの詳細一覧にBillingItemIdを最終列に取得できるスクリプトをつくったので、ぜひ使ってください。

##スクリプト
```py:getDevicesTable-BillID.py
import SoftLayer
import dateutil.parser
from prettytable import PrettyTable

# account info
client = SoftLayer.create_client_from_env()

objectmask_vitualGuests = """
	id,
	virtualGuests[
		id,
		billingItem[
			id,
			cancellationDate
		],
		notes,
		provisionDate,
		fullyQualifiedDomainName,
		primaryBackendIpAddress,
		primaryIpAddress,
		datacenter[
			longName
		],
		operatingSystem[
                        softwareLicense[
                                softwareDescription[
                                        name
                                ]
                        ],
                        passwords[
                                username,
                                password
                        ]
                ]
	]
"""
objectmask_hardware = """
	id,
	hardware[
		id,
		billingItem[
			id,
			cancellationDate
		],
		notes,
		provisionDate,
		fullyQualifiedDomainName,
		primaryBackendIpAddress,
		primaryIpAddress,
		datacenter[
			longName
		],
		operatingSystem[
			softwareLicense[
				softwareDescription[
					name
				]
			],
			passwords[		
				username,
				password
			]
		]
	]
"""

vg = client['Account'].getObject(mask=objectmask_vitualGuests)
hw = client['Account'].getObject(mask=objectmask_hardware)

virtualGuests=vg.keys()[0]
hardware=hw.keys()[0]

table = PrettyTable([
	'ID',
	'Device Name',
	'Type',
	'Location',
	'Public IP',
	'Private IP',
	'Start Date',
	'Cancel Date',
	'OS Name',
	'Username',
	'Password',
	'BillID'
	])

for key in range(len(vg['virtualGuests'])):
	for key2 in range(len(vg['virtualGuests'][key]['operatingSystem']['passwords'])):
		table.add_row([
			vg['virtualGuests'][key]['id'],
			vg['virtualGuests'][key]['fullyQualifiedDomainName'],
                	"VSI",
			vg['virtualGuests'][key]['datacenter']['longName'],
			vg['virtualGuests'][key].get('primaryIpAddress'),
			vg['virtualGuests'][key]['primaryBackendIpAddress'],
			dateutil.parser.parse(vg['virtualGuests'][key]['provisionDate']).strftime('%Y/%m/%d'),
			vg['virtualGuests'][key]['billingItem'].get('cancellationDate')[:16],
			vg['virtualGuests'][key]['operatingSystem']['softwareLicense']['softwareDescription']['name'][:16],
			vg['virtualGuests'][key]['operatingSystem']['passwords'][key2]['username'],
			vg['virtualGuests'][key]['operatingSystem']['passwords'][key2].get('password'),
			vg['virtualGuests'][key]['billingItem'].get('id')
		])
for key in range(len(hw['hardware'])):
	for key2 in range(len(hw['hardware'][key]['operatingSystem']['passwords'])):
	        table.add_row([
			hw['hardware'][key]['id'],
        	        hw['hardware'][key]['fullyQualifiedDomainName'],
        	        "BMS",
        	        hw['hardware'][key]['datacenter']['longName'],
			hw['hardware'][key].get('primaryIpAddress'),
        	        hw['hardware'][key]['primaryBackendIpAddress'],
        	        dateutil.parser.parse(hw['hardware'][key]['provisionDate']).strftime('%Y/%m/%d'),
			hw['hardware'][key]['billingItem'].get('cancellationDate')[:16],
			hw['hardware'][key]['operatingSystem']['softwareLicense']['softwareDescription']['name'][:16],
			hw['hardware'][key]['operatingSystem']['passwords'][key2]['username'],
			hw['hardware'][key]['operatingSystem']['passwords'][key2]['password'],
			hw['hardware'][key]['billingItem'].get('id')
        	])

print(table)
```

##実行結果の例
```
#実行コマンド
python ../Devices/getDevicesTable.py 

#結果
+----------+-----------------------------------------------+------+-------------+-----------------+----------------+------------+-------------+------------------+---------------+----------+-----------+
|    ID    |                  Device Name                  | Type |   Location  |    Public IP    |   Private IP   | Start Date | Cancel Date |     OS Name      |    Username   | Password |   BillID  |
+----------+-----------------------------------------------+------+-------------+-----------------+----------------+------------+-------------+------------------+---------------+----------+-----------+
| 22222222 | xxxxxxxxxxxxx.xxxxxxxxxxxxxxx01.vsphere.local | VSI  |   Tokyo 2   |   xxx.xxx.xx.x  |  xx.xxx.xx.xx  | 2016/xx/xx |             | Windows 2012 R2  | xxxxxxxxxxxxx | xxxxxxxx | 111111111 |
```

#キャンセルの実行
BillingItemIdを指定して、Immediately/ABD キャンセルできるスクリプトをつくったので、ぜひ使ってください。

##スクリプト
```py:cancelItem.py
import SoftLayer
import json
import sys
parm=sys.argv
itemId=parm[1]

# menu
print (30 * '-')
print ("   M A I N - M E N U")
print (30 * '-')
print ("1. Immediate Cancel")
print ("2. ABD Cancel")
print (30 * '-')

# account info
client = SoftLayer.create_client_from_env()
Billing = client['SoftLayer_Billing_Item']

# define option
is_valid=0
 
while not is_valid :
        try :
                choice = int ( raw_input('Enter your choice [1-2] : ') )
                is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
        except ValueError, e :
                print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
 
### Take action as per selected menu-option ###
if choice == 1:
        print ("Cancelling Immediately...")
	cancel = Billing.cancelItem(True,False,"No longer needed",id=itemId)
	print('Completed!')
elif choice == 2:
        print ("Configuring ABD Cancellation...")
	cancel = Billing.cancelItem(False,False,"No longer needed",id=itemId)
	print('Completed!')
else:
        print ("Invalid number. Try again...")
```
##実行結果の例
```
#実行コマンド
python cancelItem.py 111111111

#結果
------------------------------
   M A I N - M E N U
------------------------------
1. Immediate Cancel
2. ABD Cancel
------------------------------
Enter your choice [1-2] : 1
Cancelling Immediately...
Completed!
```

##参考にしたサイト
- [php - Softlayer API to cancel various product immediately or on anniversary date - Stack Overflow](http://stackoverflow.com/questions/37348287/softlayer-api-to-cancel-various-product-immediately-or-on-anniversary-date/37350107#37350107)
- [Python raw_input Example (Input From Keyboard)](https://www.cyberciti.biz/faq/python-raw_input-examples/)
- [BillingSoftLayer_Billing_Item::cancelItem | SoftLayer Development Network](http://sldn.softlayer.com/reference/services/SoftLayer_Billing_Item/cancelItem)