Skip to content

Instantly share code, notes, and snippets.

@neillturner
Created October 14, 2015 09:32
Show Gist options
  • Save neillturner/20ab31ee5f0ed13d2b7e to your computer and use it in GitHub Desktop.
Save neillturner/20ab31ee5f0ed13d2b7e to your computer and use it in GitHub Desktop.
For Softlayer generate /etc/hosts from the list of active VMs and private IP addresses. This enables servers inside a softlayer private vlan to communicate with each other via hostname
'''
Get the list of active VMs based on the creator ID and generate /etc/hosts file
'''
from __future__ import print_function
import sys
import os
import SoftLayer
def generate_hosts_file(username, api_key, creator_id=None):
"""
Get the list of active VMs based on the creator ID and generate /etc/hosts file
Keyword arguments:
creator_id -- the SoftLayer ID of the VM's creator (default: None)
"""
print ( 'Connect to Softlayer Username', str(username), 'Api key', str(api_key))
client = SoftLayer.Client(username=username, api_key=api_key)
# number of results that we expect at a time
chunk = 200
mask = "id,fullyQualifiedDomainName,hostname,primaryIpAddress,primaryBackendIpAddress,createDate,billingItem[orderItem[description, order[userRecord[username], id]]]"
# get the data from the SoftLayer APIs
vms = client.iter_call("Account", "getVirtualGuests", chunk=chunk, mask=mask)
if creator_id is None:
# if the creator wasn't provided use the
# user provided to the API call as the creator
creator_id = client.auth.username
hosts_string = '127.0.0.1 localhost.localdomain localhost\n'
for vsi in vms:
# navigate to the creator property under the VMs billing item
if 'billingItem' in vsi.keys():
billing_item = vsi['billingItem']
if 'orderItem' in billing_item.keys():
vm_creator_userid = billing_item['orderItem']['order']['userRecord']['username']
if creator_id == vm_creator_userid:
# print(str(vsi['id']), '\t',
hosts_string += vsi.get('primaryBackendIpAddress', '')+'\t'
hosts_string += vsi['fullyQualifiedDomainName']+'\t'
hosts_string += vsi['hostname']+'\n'
with open('/etc/hosts', 'w') as f:
f.write(hosts_string)
if __name__ == '__main__':
if len(sys.argv) == 3:
generate_hosts_file(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 4:
generate_hosts_file(sys.argv[1], sys.argv[2], sys.argv[3])
else:
print ( 'USAGE: generate_hosts_file.py <Softlayer Username> <SoftLayer Api Key>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment