Skip to content
This repository has been archived by the owner on Oct 30, 2018. It is now read-only.

Added OVH Ip loadbalancing module for managing backends #1324

Closed
wants to merge 13 commits into from
Closed
Empty file added cloud/ovh/__init__.py
Empty file.
302 changes: 302 additions & 0 deletions cloud/ovh/ovh_ip_loadbalancing_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: ovh_ip_loadbalancing_backend
short_description: Manage OVH IP LoadBalancing backends
description:
- Manage OVH (French European hosting provider) LoadBalancing IP backends
version_added: "2.1"
author: Pascal HERAUD @pascalheraud
notes:
- Uses the python OVH Api U(https://github.com/ovh/python-ovh). \
You have to create an application (a key and secret) with a consummer \
key as described into U(https://eu.api.ovh.com/g934.first_step_with_api)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python multiline strings (started and stopped using triple quotes like `'''and"""``` do not need the backslash as a line continuation character. So you can remove all trailing backslashes at the end of lines within triple quoted strings.

I can't be certain but you may have added them in here because you weren't sure how yaml was parsing the documentation. If so, the problem is not that the line needs to be continued. Instead, it's that the indentation level is wrong. In order for YAML to understand that all of this is one entry, you probably need to make sure the indent lines up with the other text, not with the character introducing the element. IE: The "Y" in You needs to be directly underneath the "U" in Uses. Similarly, the "k" in key needs to be directly underneath those.

requirements:
- ovh > 0.3.5
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a way to verify the version in the import of the module, rather than just having it as a documentation ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see any version returned by the API Client in python.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like ovh needs python >= 2.6. you need to add that to the requirements section here. (This is especially important because otherwise you'd need to code the module to be compatible with python-2.4 and I wouldn't wish that on you unnecessarily ;-)

options:
name:
required: true
description:
- Name of the LoadBalancing internal name (ip-X.X.X.X)
backend:
required: true
description:
- The IP address of the backend to update / modify / delete
state:
required: false
default: present
choices: ['present', 'absent']
description:
- Determines wether the backend is to be created/modified \
or deleted
probe:
required: false
default: none
choices: ['none', 'http', 'icmp' , 'oco']
description:
- Determines the type of probe to use for this backend
weight:
required: false
default: 8
description:
- Determines the weight for this backend
endpoint:
required: true
description:
- The endpoint to use ( for instance ovh-eu)
application_key:
required: true
description:
- The applicationKey to use
application_secret:
required: true
description:
- The application secret to use
consumer_key:
required: true
description:
- The consumer key to use
timeout:
required: false
type: "int"
default: 120
description:
- The timeout in seconds used to wait for a task to be \
completed. Default is 120 seconds.

'''

EXAMPLES = '''
# Adds or modify the backend '212.1.1.1' to a \
loadbalancing 'ip-1.1.1.1'
- ovh_ip_loadbalancing name=ip-1.1.1.1 backend=212.1.1.1 \
state=present probe=none weight=8 \
endpoint=ovh-eu application_key=yourkey \
application_secret=yoursecret consumer_key=yourconsumerkey

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than using backslashes here I'd write the examples using yaml format like this:

# Adds or modify the backend '212.1.1.1' to a
# loadbalancing 'ip-1.1.1.1'
- ovh_ip_loadbalancing:
    name: ip-1.1.1.1
    backend: 212.1.1.1
    state: present
    probe: none
    weight: 8
    endpoint: ovh-eu
    application_key: yourkey
    application_secret: yoursecret
    consumer_key: yourconsumerkey

# Removes a backend '212.1.1.1' from a loadbalancing \
'ip-1.1.1.1'
- ovh_ip_loadbalancing name=ip-1.1.1.1 backend=212.1.1.1
state=absent endpoint=ovh-eu application_key=yourkey \
application_secret=yoursecret consumer_key=yourconsumerkey
'''

RETURN = '''
'''

import sys
try:
import ovh
import ovh.exceptions
from ovh.exceptions import APIError
HAS_OVH = True
except ImportError:
HAS_OVH = False

def getOvhClient(ansibleModule):
endpoint = ansibleModule.params.get('endpoint')
application_key = ansibleModule.params.get('application_key')
application_secret = ansibleModule.params.get('application_secret')
consumer_key = ansibleModule.params.get('consumer_key')

return ovh.Client(
endpoint=endpoint,
application_key=application_key,
application_secret=application_secret,
consumer_key=consumer_key
)


def waitForNoTask(client, name, timeout):
currentTimeout = timeout
while len(client.get('/ip/loadBalancing/{}/task'.format(name))) > 0:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Format replacement strings with nothing inside of them, {}, are only available in python-2.7 or better. So you'll need to make sure that all your formats have numbers inside of them. For example, this line would then be:

 +    while len(client.get('/ip/loadBalancing/{0}/task'.format(name))) > 0: 

time.sleep(1) # Delay for 1 sec
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no timeout, nor any kind of mutex, so this could loop forever in theory, no ? Shouldn't something be done for that ?

currentTimeout -= 1
if currentTimeout < 0:
return False
return True


def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True),
backend=dict(required=True),
weight=dict(default=8, type='int'),
probe=dict(default='none',
choices=['none', 'http', 'icmp', 'oco']),
state=dict(default='present', choices=['present', 'absent']),
endpoint=dict(required=True),
application_key=dict(required=True, no_log=True),
application_secret=dict(required=True, no_log=True),
consumer_key=dict(required=True, no_log=True),
timeout=dict(default=120, type='int')
)
)

if not HAS_OVH:
module.fail_json(msg='ovh-api python module\
is required to run this module ')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using backslashes in single quoted strings like this will have an odd effect. python won't know quite how much space to embed in the string when you do it this way. It's better to open and close the string on each line. Since the entire msg is being constructed inside of parenthesis, you don't need the backslashes at all. Putting those both together, this looks like this:

        module.fail_json(msg='ovh-api python module'
            ' is required to run this module')


# Get parameters
name = module.params.get('name')
state = module.params.get('state')
backend = module.params.get('backend')
weight = long(module.params.get('weight'))
probe = module.params.get('probe')
timeout = module.params.get('timeout')

# Connect to OVH API
client = getOvhClient(module)

# Check that the load balancing exists
try:
loadBalancings = client.get('/ip/loadBalancing')
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for getting the list of loadBalancing, \
check application key, secret, consumerkey and parameters. \
Error returned by OVH api was : {}'.format(apiError))

if name not in loadBalancings:
module.fail_json(msg='IP LoadBalancing {} does not exist'.format(name))

# Check that no task is pending before going on
try:
if not waitForNoTask(client, name, timeout):
module.fail_json(
msg='Timeout of {} seconds while waiting for no pending \
tasks before executing the module '.format(timeout))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for getting the list of pending tasks \
of the loadBalancing, check application key, secret, consumerkey \
and parameters. Error returned by OVH api was : {}\
'.format(apiError))

try:
backends = client.get('/ip/loadBalancing/{}/backend'.format(name))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for getting the list of backends \
of the loadBalancing, check application key, secret, consumerkey \
and parameters. Error returned by OVH api was : {}\
'.format(apiError))

backendExists = backend in backends
moduleChanged = False
if state == "absent":
if backendExists:
# Remove backend
try:
client.delete(
'/ip/loadBalancing/{}/backend/{}'.format(name, backend))
if not waitForNoTask(client, name, timeout):
module.fail_json(
msg='Timeout of {} seconds while waiting for completion \
of removing backend task'.format(timeout))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for deleting the backend, \
check application key, secret, consumerkey and \
parameters. Error returned by OVH api was : {}\
'.format(apiError))
moduleChanged = True
else:
if backendExists:
# Get properties
try:
backendProperties = client.get(
'/ip/loadBalancing/{}/backend/{}'.format(name, backend))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for getting the backend properties, \
check application key, secret, consumerkey and \
parameters. Error returned by OVH api was : {}\
'.format(apiError))

if (backendProperties['weight'] != weight):
# Change weight
try:
client.post(
'/ip/loadBalancing/{}/backend/{}/setWeight\
'.format(name, backend), weight=weight)
if not waitForNoTask(client, name, timeout):
module.fail_json(
msg='Timeout of {} seconds while waiting for completion \
of setWeight to backend task'.format(timeout))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for updating the weight of the \
backend, check application key, secret, consumerkey \
and parameters. Error returned by OVH api was : {}\
'.format(apiError))
moduleChanged = True

if (backendProperties['probe'] != probe):
# Change probe
backendProperties['probe'] = probe
try:
client.put(
'/ip/loadBalancing/{}/backend/{}\
'.format(name, backend), probe=probe)
if not waitForNoTask(client, name, timeout):
module.fail_json(
msg='Timeout of {} seconds while waiting for completion of \
setProbe to backend task'.format(timeout))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for updating the propbe of \
the backend, check application key, secret, \
consumerkey and parameters. Error returned by OVH api \
was : {}\
'.format(apiError))
moduleChanged = True

else:
# Creates backend
try:
try:
client.post('/ip/loadBalancing/{}/backend'.format(name),
ipBackend=backend, probe=probe, weight=weight)
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for creating the backend, check \
application key, secret, consumerkey and parameters. \
Error returned by OVH api was : {}'.format(apiError))

if not waitForNoTask(client, name, timeout):
module.fail_json(
msg='Timeout of {} seconds while waiting for completion of \
backend creation task'.format(timeout))
except APIError as apiError:
module.fail_json(
msg='Unable to call OVH api for creating the backend, check \
application key, secret, consumerkey and parameters. \
Error returned by OVH api was : {}'.format(apiError))
moduleChanged = True

module.exit_json(changed=moduleChanged)

# We should never reach here
module.fail_json(msg='Internal ovh_ip_loadbalancing_backend module error')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will really never be hit because module.exit_json() terminates the module.


# import module snippets
from ansible.module_utils.basic import *

if __name__ == '__main__':
main()