Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code generation from magic-module-specs#93 for Ansible #93

Open
wants to merge 2 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
395 changes: 395 additions & 0 deletions lib/ansible/modules/cloud/azure/azure_rm_backendpool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,395 @@
#!/usr/bin/python
#
# Copyright (C) 2019 audevbot
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file at
# https://github.com/Azure/magic-module-specs
#
# ----------------------------------------------------------------------------

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}


DOCUMENTATION = '''
---
module: azure_rm_backendpool
version_added: "2.9"
short_description: Manage Azure BackendPool instance.
description:
- Create, update and delete instance of Azure Backend Pool.

options:
id:
description:
- Resource ID.
type: str
resource_group:
description:
- Name of the Resource group within the Azure subscription.
required: true
type: str
name:
description:
- Resource name.
type: str
backends:
description:
- The set of backends for this pool.
type: dict
suboptions:
address:
description:
- Location of the backend (IP address or FQDN).
type: str
http_port:
description:
- The HTTP TCP port number. Must be between 1 and 65535.
type: int
https_port:
description:
- The HTTPS TCP port number. Must be between 1 and 65535.
type: int
enabled_state:
description:
- Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled'.
default: enabled
type: str
choices:
- enabled
- disabled
priority:
description:
- Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy.
type: int
weight:
description:
- Weight of this endpoint for load balancing purposes.
type: int
backend_host_header:
description:
- The value to use as the host header sent to the backend. If blank or unspecified, this defaults to the incoming host.
type: str
front_door_name:
description:
- Name of the Front Door which is globally unique.
required: true
type: str
health_probe_settings:
description:
- L7 health probe settings for a backend pool.
type: dict
suboptions:
id:
description:
- Resource ID.
type: str
load_balancing_settings:
description:
- Load balancing settings for a backend pool.
type: dict
suboptions:
id:
description:
- Resource ID.
type: str
resource_state:
description:
- Resource status.
default: creating
type: str
choices:
- creating
- enabling
- enabled
- disabling
- disabled
- deleting
state:
description:
- Assert the state of the Backend Pool.
- Use 'present' to create or update a Backend Pool and 'absent' to delete it.
default: present
choices:
- present
- absent

extends_documentation_fragment:
- azure

author:
- audevbot
'''


RETURN = '''
type:
description:
- Resource type.
returned: always
type: str
'''

import time
from ansible.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
from ansible.module_utils.common.dict_transformations import _snake_to_camel

try:
from msrestazure.azure_exceptions import CloudError
from msrest.polling import LROPoller
from msrestazure.azure_operation import AzureOperationPoller
from msrest.serialization import Model
from azure.mgmt.frontdoor import FrontdoorClient
except ImportError:
# This is handled in azure_rm_common
pass


class Actions:
NoAction, Create, Update, Delete = range(4)


class AzureRMBackendPool(AzureRMModuleBaseExt):
"""Configuration class for an Azure RM Backend Pool resource"""

def __init__(self):
self.module_arg_spec = dict(
id=dict(
type='str',
updatable=False,
disposition='/'
),
resource_group=dict(
required=True,
type='str'
),
name=dict(
required=True,
type='str'
),
name=dict(
type='str'
),
backends=dict(
type='dict',
options=dict(
address=dict(
type='str'
),
http_port=dict(
type='int'
),
https_port=dict(
type='int'
),
enabled_state=dict(
default='enabled',
type='str',
choices=['enabled', 'disabled']
),
priority=dict(
type='int'
),
weight=dict(
type='int'
),
backend_host_header=dict(
type='str'
)
)
),
front_door_name=dict(
required=True,
type='str',
updatable=False,
disposition='/'
),
health_probe_settings=dict(
type='dict',
options=dict(
id=dict(
type='str'
)
)
),
load_balancing_settings=dict(
type='dict',
options=dict(
id=dict(
type='str'
)
)
),
resource_state=dict(
default='creating',
type='str',
choices=['creating', 'enabling', 'enabled', 'disabling', 'disabled', 'deleting']
),
state=dict(
type='str',
default='present',
choices=['present', 'absent']
)
)

self.resource_group = None
self.front_door_name = None
self.name = None
self.backend_pool_parameters = dict()

self.results = dict(changed=False)
self.mgmt_client = None
self.state = None
self.to_do = Actions.NoAction

super(AzureRMBackendPool, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
supports_tags=False)

def exec_module(self, **kwargs):
"""Main module execution method"""

for key in list(self.module_arg_spec.keys()):
if hasattr(self, key):
setattr(self, key, kwargs[key])
elif kwargs[key] is not None:
self.backend_pool_parameters[key] = kwargs[key]

if self.backend_pool_parameters.get('backends') is not None:
self.backend_pool_parameters['backends']['enabled_state'] = _snake_to_camel(self.backend_pool_parameters['backends']['enabled_state'], True)
self.backend_pool_parameters['resource_state'] = _snake_to_camel(self.backend_pool_parameters['resource_state'], True)

response = None

self.mgmt_client = self.get_mgmt_svc_client(FrontdoorClient,
base_url=self._cloud_environment.endpoints.resource_manager)

old_response = self.get_backendpool()

if not old_response:
self.log("Backend Pool instance doesn't exist")
if self.state == 'absent':
self.log("Old instance didn't exist")
else:
self.to_do = Actions.Create
else:
self.log("Backend Pool instance already exists")
if self.state == 'absent':
self.to_do = Actions.Delete
elif self.state == 'present':
self.results['old'] = old_response
self.results['new'] = self.backend_pool_parameters
if not self.idempotency_check(old_response, self.backend_pool_parameters):
self.to_do = Actions.Update

if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
self.log("Need to Create / Update the Backend Pool instance")

self.results['changed'] = True
if self.check_mode:
return self.results

response = self.create_update_backendpool()

self.log("Creation / Update done")
elif self.to_do == Actions.Delete:
self.log("Backend Pool instance deleted")
self.results['changed'] = True

if self.check_mode:
return self.results

self.delete_backendpool()
else:
self.log("Backend Pool instance unchanged")
self.results['changed'] = False
response = old_response

if self.state == 'present':
self.results.update({
'type': response.get('type', None)
})
return self.results

def create_update_backendpool(self):
'''
Creates or updates Backend Pool with the specified configuration.

:return: deserialized Backend Pool instance state dictionary
'''
self.log("Creating / Updating the Backend Pool instance {0}".format(self.name))

try:
response = self.mgmt_client.backend_pools.create_or_update(resource_group_name=self.resource_group,
front_door_name=self.front_door_name,
backend_pool_name=self.name,
backend_pool_parameters=self.backend_pool_parameters)
if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller):
response = self.get_poller_result(response)
except CloudError as exc:
self.log('Error attempting to create the Backend Pool instance.')
self.fail("Error creating the Backend Pool instance: {0}".format(str(exc)))
return response.as_dict()

def delete_backendpool(self):
'''
Deletes specified Backend Pool instance in the specified subscription and resource group.

:return: True
'''
self.log("Deleting the Backend Pool instance {0}".format(self.name))
try:
response = self.mgmt_client.backend_pools.delete(resource_group_name=self.resource_group,
front_door_name=self.front_door_name,
backend_pool_name=self.name)
except CloudError as e:
self.log('Error attempting to delete the Backend Pool instance.')
self.fail("Error deleting the Backend Pool instance: {0}".format(str(e)))

if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller):
response = self.get_poller_result(response)
return True

def get_backendpool(self):
'''
Gets the properties of the specified Backend Pool
:return: deserialized Backend Pool instance state dictionary
'''
self.log("Checking if the Backend Pool instance {0} is present".format(self.name))
found = False
try:
response = self.mgmt_client.backend_pools.get(resource_group_name=self.resource_group,
front_door_name=self.front_door_name,
backend_pool_name=self.name)
found = True
self.log("Response : {0}".format(response))
self.log("Backend Pool instance : {0} found".format(response.name))
except CloudError as e:
self.log('Did not find the Backend Pool instance.')
if found is True:
return response.as_dict()
return False


def main():
"""Main execution"""
AzureRMBackendPool()


if __name__ == '__main__':
main()
Loading