Updates to rax_clb module

reviewable/pr18780/r1
Matt Martz 11 years ago
parent adca8d0dd8
commit 9a1adb1772

@ -22,32 +22,28 @@ description:
- creates / deletes a Rackspace Public Cloud load balancer. - creates / deletes a Rackspace Public Cloud load balancer.
version_added: "1.4" version_added: "1.4"
options: options:
state: algorithm:
description: description:
- Indicate desired state of the resource - algorithm for the balancer being created
choices: ['present', 'absent'] choices: ['RANDOM', 'LEAST_CONNECTIONS', 'ROUND_ROBIN', 'WEIGHTED_LEAST_CONNECTIONS', 'WEIGHTED_ROUND_ROBIN']
default: present default: LEAST_CONNECTIONS
api_key:
description:
- Rackspace API key (overrides C(credentials))
credentials: credentials:
description: description:
- File to find the Rackspace credentials in (ignored if C(api_key) and - File to find the Rackspace credentials in (ignored if C(api_key) and
C(username) are provided) C(username) are provided)
default: null default: null
aliases: ['creds_file'] aliases: ['creds_file']
api_key: meta:
description: description:
- Rackspace API key (overrides C(credentials)) - A hash of metadata to associate with the instance
username: default: null
description:
- Rackspace username (overrides C(credentials))
name: name:
description: description:
- Name to give the load balancer - Name to give the load balancer
default: null default: null
algorithm:
description:
- algorithm for the balancer being created
choices: ['RANDOM', 'LEAST_CONNECTIONS', 'ROUND_ROBIN', 'WEIGHTED_LEAST_CONNECTIONS', 'WEIGHTED_ROUND_ROBIN']
default: LEAST_CONNECTIONS
port: port:
description: description:
- Port for the balancer being created - Port for the balancer being created
@ -57,6 +53,15 @@ options:
- Protocol for the balancer being created - Protocol for the balancer being created
choices: ['DNS_TCP', 'DNS_UDP' ,'FTP', 'HTTP', 'HTTPS', 'IMAPS', 'IMAPv4', 'LDAP', 'LDAPS', 'MYSQL', 'POP3', 'POP3S', 'SMTP', 'TCP', 'TCP_CLIENT_FIRST', 'UDP', 'UDP_STREAM', 'SFTP'] choices: ['DNS_TCP', 'DNS_UDP' ,'FTP', 'HTTP', 'HTTPS', 'IMAPS', 'IMAPv4', 'LDAP', 'LDAPS', 'MYSQL', 'POP3', 'POP3S', 'SMTP', 'TCP', 'TCP_CLIENT_FIRST', 'UDP', 'UDP_STREAM', 'SFTP']
default: HTTP default: HTTP
region:
description:
- Region to create the load balancer in
default: DFW
state:
description:
- Indicate desired state of the resource
choices: ['present', 'absent']
default: present
timeout: timeout:
description: description:
- timeout for communication between the balancer and the node - timeout for communication between the balancer and the node
@ -66,10 +71,9 @@ options:
- type of interface for the balancer being created - type of interface for the balancer being created
choices: ['PUBLIC', 'SERVICENET'] choices: ['PUBLIC', 'SERVICENET']
default: PUBLIC default: PUBLIC
region: username:
description: description:
- Region to create the load balancer in - Rackspace username (overrides C(credentials))
default: DFW
wait: wait:
description: description:
- wait for the balancer to be in state 'running' before returning - wait for the balancer to be in state 'running' before returning
@ -80,12 +84,12 @@ options:
- how long before wait gives up, in seconds - how long before wait gives up, in seconds
default: 300 default: 300
requirements: [ "pyrax" ] requirements: [ "pyrax" ]
author: Christopher H. Laco, Jesse Keating author: Christopher H. Laco, Matt Martz
notes: notes:
- The following environment variables can be used, C(RAX_USERNAME), - The following environment variables can be used, C(RAX_USERNAME),
C(RAX_API_KEY), C(RAX_CREDS), C(RAX_CREDENTIALS), C(RAX_REGION). C(RAX_API_KEY), C(RAX_CREDS_FILE), C(RAX_CREDENTIALS), C(RAX_REGION).
- C(RAX_CREDENTIALS) and C(RAX_CREDS) points to a credentials file - C(RAX_CREDENTIALS) and C(RAX_CREDS_FILE) points to a credentials file
appropriate for pyrax appropriate for pyrax. See U(https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating)
- C(RAX_USERNAME) and C(RAX_API_KEY) obviate the use of a credentials file - C(RAX_USERNAME) and C(RAX_API_KEY) obviate the use of a credentials file
- C(RAX_REGION) defines a Rackspace Public Cloud region (DFW, ORD, LON, ...) - C(RAX_REGION) defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
''' '''
@ -93,169 +97,224 @@ notes:
EXAMPLES = ''' EXAMPLES = '''
- name: Build a Load Balancer - name: Build a Load Balancer
gather_facts: False gather_facts: False
hosts: local
connection: local
tasks: tasks:
- name: Provision Load Balancer - name: Load Balancer create request
rax_lb: local_action:
module: rax_clb
credentials: ~/.raxpub credentials: ~/.raxpub
name: my-lb name: my-lb
port: 9000 port: 8080
protocol: HTTP protocol: HTTP
type: SERVICENET type: SERVICENET
timeout: 30 timeout: 30
region: DFW region: DFW
wait: yes wait: yes
state: present state: present
meta:
app: my-cool-app
register: my_lb register: my_lb
''' '''
import sys import sys
import os import os
import time
from types import NoneType
try: try:
import pyrax import pyrax
import pyrax.utils
from pyrax import exc
except ImportError: except ImportError:
print("failed=True msg='pyrax required for this module'") print("failed=True msg='pyrax required for this module'")
sys.exit(1) sys.exit(1)
NON_CALLABLES = (basestring, bool, dict, int, list, NoneType)
ALGORITHMS = ['RANDOM', 'LEAST_CONNECTIONS', 'ROUND_ROBIN',
'WEIGHTED_LEAST_CONNECTIONS', 'WEIGHTED_ROUND_ROBIN']
PROTOCOLS = ['DNS_TCP', 'DNS_UDP', 'FTP', 'HTTP', 'HTTPS', 'IMAPS', 'IMAPv4',
'LDAP', 'LDAPS', 'MYSQL', 'POP3', 'POP3S', 'SMTP', 'TCP',
'TCP_CLIENT_FIRST', 'UDP', 'UDP_STREAM', 'SFTP']
def cloud_load_balancer(module, state, name, meta, algorithm, port, protocol, type, timeout, def cloud_load_balancer(module, state, name, meta, algorithm, port, protocol,
wait, wait_timeout): vip_type, timeout, wait, wait_timeout):
for arg in (state, name, port, protocol, type): for arg in (state, name, port, protocol, vip_type):
if not arg: if not arg:
module.fail_json(msg='%s is required for cloud_loadbalancers' % arg) module.fail_json(msg='%s is required for rax_clb' % arg)
if int(timeout) < 30:
module.fail_json(msg='"timeout" must be greater than or equal to 30')
changed = False changed = False
balancer = None
balancers = [] balancers = []
instances = []
for balancer in pyrax.cloud_loadbalancers.list(): clb = pyrax.cloud_loadbalancers
if name != balancer.name:
for balancer in clb.list():
if name != balancer.name and name != balancer.id:
continue continue
balancers.append(balancer) balancers.append(balancer)
if len(balancers) > 1:
module.fail_json(msg='Multiple Load Balancers were matched by name, '
'try using the Load Balancer ID instead')
if state == 'present': if state == 'present':
if isinstance(meta, dict):
metadata = [dict(key=k, value=v) for k, v in meta.items()]
if not balancers: if not balancers:
try: try:
balancers=[pyrax.cloud_loadbalancers.create( virtual_ips = [clb.VirtualIP(type=vip_type)]
name, balancer = clb.create(name, metadata=metadata, port=port,
metadata=meta, algorithm=algorithm, protocol=protocol,
algorithm=algorithm, timeout=timeout, virtual_ips=virtual_ips)
port=port,
protocol=protocol,
timeout=timeout,
virtual_ips=[pyrax.cloud_loadbalancers.VirtualIP(type=type)]
)]
changed = True changed = True
except Exception, e: except Exception, e:
module.fail_json(msg='%s' % e.message) module.fail_json(msg='%s' % e.message)
else:
balancer = balancers[0]
setattr(balancer, 'metadata',
[dict(key=k, value=v) for k, v in
balancer.get_metadata().items()])
atts = {
'name': name,
'algorithm': algorithm,
'port': port,
'protocol': protocol,
'timeout': timeout
}
for att, value in atts.iteritems():
current = getattr(balancer, att)
if current != value:
changed = True
if changed:
balancer.update(**atts)
if balancer.metadata != metadata:
balancer.set_metadata(meta)
changed = True
virtual_ips = [clb.VirtualIP(type=vip_type)]
current_vip_types = set([v.type for v in balancer.virtual_ips])
vip_types = set([v.type for v in virtual_ips])
if current_vip_types != vip_types:
module.fail_json(msg='Load balancer Virtual IP type cannot '
'be changed')
for balancer in balancers:
if wait: if wait:
pyrax.utils.wait_for_build(balancer, interval=5, attempts=5) attempts = wait_timeout / 5
print attempts
if balancer.status == 'ACTIVE': pyrax.utils.wait_for_build(balancer, interval=5, attempts=attempts)
instance = dict(
id=balancer.id, balancer.get()
algorithm=balancer.algorithm, instance = {}
cluster=balancer.cluster, for key, value in vars(balancer).iteritems():
connectionLogging=balancer.connectionLogging, if key == 'virtual_ips':
contentCaching=balancer.contentCaching, virtual_ips = []
halfClosed=balancer.halfClosed, instance[key] = []
port=balancer.port, for vip in value:
protocol=balancer.protocol, vip_dict = {}
sourceAddresses=balancer.sourceAddresses, for vip_key, vip_value in vars(vip).iteritems():
name=balancer.name, if isinstance(vip_value, NON_CALLABLES):
timeout=balancer.timeout, vip_dict[vip_key] = vip_value
status=balancer.status instance[key].append(vip_dict)
) elif (isinstance(value, NON_CALLABLES) and
instances.append(instance) not key.startswith('_')):
elif balancer.status == 'ERROR': instance[key] = value
module.fail_json(msg='%s failed to build' % balancer.id)
elif wait: result = dict(changed=changed, balancer=instance)
module.fail_json(msg='Timeout waiting on %s' % balancer.id)
if balancer.status == 'ERROR':
result['msg'] = '%s failed to build' % balancer.id
elif wait and balancer.status not in ('ACTIVE', 'ERROR'):
result['msg'] = 'Timeout waiting on %s' % balancer.id
if 'msg' in result:
module.fail_json(**result)
else:
module.exit_json(**result)
elif state == 'absent': elif state == 'absent':
if balancer: if balancers:
balancer = balancers[0]
try: try:
balancer.delete() balancer.delete()
changed = True changed = True
except Exception, e: except Exception, e:
module.fail_json(msg='%s' % e.message) module.fail_json(msg='%s' % e.message)
instance = dict( instance = {}
id=balancer.id, for key, value in vars(balancer).iteritems():
algorithm=balancer.algorithm, if key == 'virtual_ips':
cluster=None, virtual_ips = []
connectionLogging=None, instance[key] = []
contentCaching=None, for vip in value:
halfClosed=None, vip_dict = {}
port=balancer.port, for vip_key, vip_value in vars(vip).iteritems():
protocol=balancer.protocol, if isinstance(vip_value, NON_CALLABLES):
sourceAddresses=None, vip_dict[vip_key] = vip_value
name=balancer.name, instance[key].append(vip_dict)
timeout=balancer.timeout, elif (isinstance(value, NON_CALLABLES) and
status=balancer.status not key.startswith('_')):
) instance[key] = value
instances.append(instance)
if wait:
attempts = wait_timeout / 5
pyrax.utils.wait_until(balancer, 'status', ('DELETED'),
interval=5, attempts=attempts)
module.exit_json(changed=changed, balancers=instances) module.exit_json(changed=changed, balancer=instance)
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
state=dict(default='present', algorithm=dict(choices=ALGORITHMS, default='LEAST_CONNECTIONS'),
choices=['present', 'absent']),
credentials=dict(aliases=['creds_file']),
api_key=dict(), api_key=dict(),
username=dict(), credentials=dict(aliases=['creds_file']),
region=dict(),
name=dict(),
meta=dict(type='dict', default={}), meta=dict(type='dict', default={}),
algorithm=dict(choices=['RANDOM', 'LEAST_CONNECTIONS', 'ROUND_ROBIN', 'WEIGHTED_LEAST_CONNECTIONS', 'WEIGHTED_ROUND_ROBIN'], default='LEAST_CONNECTIONS'), name=dict(),
port=dict(type='int', default=80), port=dict(type='int', default=80),
protocol=dict(choices=['DNS_TCP', 'DNS_UDP' ,'FTP', 'HTTP', 'HTTPS', 'IMAPS', 'IMAPv4', 'LDAP', 'LDAPS', 'MYSQL', 'POP3', 'POP3S', 'SMTP', 'TCP', 'TCP_CLIENT_FIRST', 'UDP', 'UDP_STREAM', 'SFTP'], default='HTTP'), protocol=dict(choices=PROTOCOLS, default='HTTP'),
type=dict(choices=['PUBLIC', 'SERVICENET'], default='PUBLIC'), region=dict(),
state=dict(default='present', choices=['present', 'absent']),
timeout=dict(type='int', default=30), timeout=dict(type='int', default=30),
type=dict(choices=['PUBLIC', 'SERVICENET'], default='PUBLIC'),
username=dict(),
wait=dict(type='bool'), wait=dict(type='bool'),
wait_timeout=dict(default=300) wait_timeout=dict(default=300),
) ),
) )
credentials = module.params.get('credentials') algorithm = module.params.get('algorithm')
api_key = module.params.get('api_key') api_key = module.params.get('api_key')
username = module.params.get('username') credentials = module.params.get('credentials')
region = module.params.get('region')
state = module.params.get('state')
name = module.params.get('name')
meta = module.params.get('meta') meta = module.params.get('meta')
algorithm = module.params.get('algorithm') name = module.params.get('name')
port = module.params.get('port') port = module.params.get('port')
protocol = module.params.get('protocol') protocol = module.params.get('protocol')
type = module.params.get('type') region = module.params.get('region')
state = module.params.get('state')
timeout = int(module.params.get('timeout')) timeout = int(module.params.get('timeout'))
username = module.params.get('username')
vip_type = module.params.get('type')
wait = module.params.get('wait') wait = module.params.get('wait')
wait_timeout = int(module.params.get('wait_timeout')) wait_timeout = int(module.params.get('wait_timeout'))
try: try:
username = username or os.environ.get('RAX_USERNAME') username = username or os.environ.get('RAX_USERNAME')
api_key = api_key or os.environ.get('RAX_API_KEY') api_key = api_key or os.environ.get('RAX_API_KEY')
credentials = (credentials or credentials = (credentials or os.environ.get('RAX_CREDENTIALS') or
os.environ.get('RAX_CREDENTIALS') or
os.environ.get('RAX_CREDS_FILE')) os.environ.get('RAX_CREDS_FILE'))
region = region or os.environ.get('RAX_REGION') region = region or os.environ.get('RAX_REGION')
except KeyError, e: except KeyError, e:
module.fail_json(msg='Unable to load %s' % e.message) module.fail_json(msg='Unable to load %s' % e.message)
try: try:
pyrax.set_setting("identity_type", "rackspace") pyrax.set_setting('identity_type', 'rackspace')
if api_key and username: if api_key and username:
pyrax.set_credentials(username, api_key=api_key, region=region) pyrax.set_credentials(username, api_key=api_key, region=region)
elif credentials: elif credentials:
@ -266,9 +325,9 @@ def main():
except Exception, e: except Exception, e:
module.fail_json(msg='%s' % e.message) module.fail_json(msg='%s' % e.message)
cloud_load_balancer(module, state, name, meta, algorithm, port, protocol, type, timeout, wait, wait_timeout) cloud_load_balancer(module, state, name, meta, algorithm, port, protocol,
vip_type, timeout, wait, wait_timeout)
# this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import *
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main() main()

Loading…
Cancel
Save