SoftLayer上の物理サーバー/仮想サーバーの一覧を取得して、プライベートIPアドレスとホスト名に基づくDNSレコードを一括登録するPythonプログラム。
実行方法
$python recordDNS.py
プログラム
recordDNS.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from prettytable import PrettyTable
import SoftLayer
SL_USERNAME = '<User Name>'
SL_API_KEY = '<API Key>'
_maskVirtualGuest = '''
hostname,
primaryBackendIpAddress
'''
_maskHardware = '''
hostname,
primaryBackendIpAddress
'''
_tableHeader = [
'hostname',
'backend_ip'
]
def lookup(dic, key, *keys):
"""A generic dictionary access helper.
This helps simplify code that uses heavily nested dictionaries. It will
return None if any of the keys in *keys do not exist.
"""
if keys:
return lookup(dic.get(key, {}), *keys)
return dic.get(key)
client = SoftLayer.Client(username=SL_USERNAME, api_key=SL_API_KEY)
virtualGuests = client['Account'].getVirtualGuests(mask=_maskVirtualGuest)
hardwares = client['Account'].getHardware(mask=_maskHardware)
instances = hardwares + virtualGuests
# Table definition
table = PrettyTable(_tableHeader)
table.padding_width = 1
# Get virtualGuests
count = 0
for inst in instances:
table.add_row(
[
inst['hostname'],
inst['primaryBackendIpAddress'],
]
)
count = count + 1
print(table)
# Register DNS
count = 0
for inst in instances:
manDNS = SoftLayer.managers.dns.DNSManager(client)
zone_id = manDNS.list_zones()[0]['id']
manDNS.create_record(zone_id, inst['hostname'], 'A', inst['primaryBackendIpAddress'], ttl=900)
record_id = manDNS.get_records(zone_id, ttl=900)[0]['id']
# manDNS.delete_record(record_id)
print inst['hostname'] + " - " + inst['primaryBackendIpAddress']
count = count + 1
exit()