diff --git a/files/sha.json b/files/sha.json index 623fe45..6cb21f3 100644 --- a/files/sha.json +++ b/files/sha.json @@ -1,6 +1,6 @@ { - "lib/ansible/module_utils/azure_rm_common.py": "41778a8e1259993cc87c3ddc328de7d00e4d3eb2", - "lib/ansible/modules/cloud/azure": "bf108ee7bfc0270715fe26d143bc5885eb398fb5", - "packaging/requirements/requirements-azure.txt": "b4732dd2e6db5ff193a8b013ebe73a56f7ca373d", - "test/integration/targets": "a6f6256a0a2f886262ff92c3b789abb0bac73d74" + "lib/ansible/module_utils/azure_rm_common.py": "52a665e224a82b09cb26436d29a753dc8f7facad", + "lib/ansible/modules/cloud/azure": "68f9cd14cbbafdf426cc7f2f3a40a5b6c709ed11", + "packaging/requirements/requirements-azure.txt": "68fa03138c719377b754dc1bbd083529297d38b3", + "test/integration/targets": "2ebeadfc143449d4408a59cfd4b5fe4fca9880ef" } \ No newline at end of file diff --git a/library/_azure_rm_aks_facts.py b/library/_azure_rm_aks_facts.py index 36b1c0d..3eb0ef1 100644 --- a/library/_azure_rm_aks_facts.py +++ b/library/_azure_rm_aks_facts.py @@ -71,7 +71,6 @@ azure_aks: type: list ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -107,11 +106,6 @@ class AzureRMManagedClusterInfo(AzureRMModuleBase): self.tags = None self.show_kubeconfig = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_aks_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_aks_facts' module has been renamed to 'azure_rm_aks_info'", version='2.13') - super(AzureRMManagedClusterInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -120,6 +114,10 @@ class AzureRMManagedClusterInfo(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_aks_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_aks_facts' module has been renamed to 'azure_rm_aks_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) diff --git a/library/_azure_rm_aksversion_facts.py b/library/_azure_rm_aksversion_facts.py index 515ea48..462ee78 100644 --- a/library/_azure_rm_aksversion_facts.py +++ b/library/_azure_rm_aksversion_facts.py @@ -56,7 +56,6 @@ azure_aks_versions: type: list ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -84,11 +83,6 @@ class AzureRMAKSVersion(AzureRMModuleBase): self.location = None self.version = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_aksversion_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_aksversion_facts' module has been renamed to 'azure_rm_aksversion_info'", version='2.13') - super(AzureRMAKSVersion, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -97,6 +91,10 @@ class AzureRMAKSVersion(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_aksversion_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_aksversion_facts' module has been renamed to 'azure_rm_aksversion_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) diff --git a/library/_azure_rm_applicationsecuritygroup_facts.py b/library/_azure_rm_applicationsecuritygroup_facts.py index bdf757a..97b1e6e 100644 --- a/library/_azure_rm_applicationsecuritygroup_facts.py +++ b/library/_azure_rm_applicationsecuritygroup_facts.py @@ -89,7 +89,6 @@ applicationsecuritygroups: sample: Succeeded ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -130,12 +129,6 @@ class AzureRMApplicationSecurityGroupInfo(AzureRMModuleBase): self.results = dict(changed=False) - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_applicationsecuritygroup_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_applicationsecuritygroup_facts' module has been renamed to 'azure_rm_applicationsecuritygroup_info'", - version='2.13') - super(AzureRMApplicationSecurityGroupInfo, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=False, supports_tags=False) @@ -143,6 +136,11 @@ class AzureRMApplicationSecurityGroupInfo(AzureRMModuleBase): def exec_module(self, **kwargs): """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_applicationsecuritygroup_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_applicationsecuritygroup_facts' module has been renamed to 'azure_rm_applicationsecuritygroup_info'", + version='2.13') + for key in list(self.module_arg_spec.keys()) + ['tags']: if hasattr(self, key): setattr(self, key, kwargs[key]) diff --git a/library/_azure_rm_appserviceplan_facts.py b/library/_azure_rm_appserviceplan_facts.py index ac72145..3309dc1 100644 --- a/library/_azure_rm_appserviceplan_facts.py +++ b/library/_azure_rm_appserviceplan_facts.py @@ -126,7 +126,6 @@ except Exception: # This is handled in azure_rm_common pass -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'AppServicePlan' @@ -149,17 +148,16 @@ class AzureRMAppServicePlanInfo(AzureRMModuleBase): self.tags = None self.info_level = None - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_appserviceplan_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_appserviceplan_facts' module has been renamed to 'azure_rm_appserviceplan_info'", version='2.13') - super(AzureRMAppServicePlanInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_appserviceplan_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_appserviceplan_facts' module has been renamed to 'azure_rm_appserviceplan_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_automationaccount_facts.py b/library/_azure_rm_automationaccount_facts.py similarity index 95% rename from library/azure_rm_automationaccount_facts.py rename to library/_azure_rm_automationaccount_facts.py index 1520f4b..e463579 100644 --- a/library/azure_rm_automationaccount_facts.py +++ b/library/_azure_rm_automationaccount_facts.py @@ -15,7 +15,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_automationaccount_facts +module: azure_rm_automationaccount_info version_added: '2.9' short_description: Get Azure automation account facts description: @@ -61,7 +61,7 @@ author: EXAMPLES = ''' - name: Get details of an automation account - azure_rm_automationaccount_facts: + azure_rm_automationaccount_info: name: Testing resource_group: myResourceGroup list_statistics: yes @@ -69,11 +69,11 @@ EXAMPLES = ''' list_keys: yes - name: List automation account in a resource group - azure_rm_automationaccount_facts: + azure_rm_automationaccount_info: resource_group: myResourceGroup - name: List automation account in a resource group - azure_rm_automationaccount_facts: + azure_rm_automationaccount_info: ''' RETURN = ''' @@ -246,7 +246,7 @@ except ImportError: pass -class AzureRMAutomationAccountFacts(AzureRMModuleBase): +class AzureRMAutomationAccountInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -278,9 +278,15 @@ class AzureRMAutomationAccountFacts(AzureRMModuleBase): self.list_statistics = None self.list_usages = None self.list_keys = None - super(AzureRMAutomationAccountFacts, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) + + super(AzureRMAutomationAccountInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_automationaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_automationaccount_facts' module has been renamed to 'azure_rm_automationaccount_info'", version='2.13') + for key in list(self.module_arg_spec): setattr(self, key, kwargs[key]) @@ -370,7 +376,7 @@ class AzureRMAutomationAccountFacts(AzureRMModuleBase): def main(): - AzureRMAutomationAccountFacts() + AzureRMAutomationAccountInfo() if __name__ == '__main__': diff --git a/library/_azure_rm_autoscale_facts.py b/library/_azure_rm_autoscale_facts.py index 5db3947..995556a 100644 --- a/library/_azure_rm_autoscale_facts.py +++ b/library/_azure_rm_autoscale_facts.py @@ -114,7 +114,6 @@ autoscales: ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase from ansible.module_utils._text import to_native @@ -228,14 +227,14 @@ class AzureRMAutoScaleInfo(AzureRMModuleBase): self.name = None self.tags = None - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_autoscale_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_autoscale_facts' module has been renamed to 'azure_rm_autoscale_info'", version='2.13') - super(AzureRMAutoScaleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_autoscale_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_autoscale_facts' module has been renamed to 'azure_rm_autoscale_info'", version='2.13') + for key in list(self.module_arg_spec): setattr(self, key, kwargs[key]) diff --git a/library/_azure_rm_availabilityset_facts.py b/library/_azure_rm_availabilityset_facts.py index 8f10c64..df84730 100644 --- a/library/_azure_rm_availabilityset_facts.py +++ b/library/_azure_rm_availabilityset_facts.py @@ -105,7 +105,6 @@ azure_availabilityset: sample: { env: sandbox } ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -130,7 +129,7 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict( + ansible_info=dict( azure_availabilitysets=[] ) ) @@ -139,11 +138,6 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): self.resource_group = None self.tags = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_availabilityset_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_availabilityset_facts' module has been renamed to 'azure_rm_availabilityset_info'", version='2.13') - super(AzureRMAvailabilitySetInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -152,15 +146,19 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_availabilityset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_availabilityset_facts' module has been renamed to 'azure_rm_availabilityset_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") if self.name: - self.results['ansible_facts']['azure_availabilitysets'] = self.get_item() + self.results['ansible_info']['azure_availabilitysets'] = self.get_item() else: - self.results['ansible_facts']['azure_availabilitysets'] = self.list_items() + self.results['ansible_info']['azure_availabilitysets'] = self.list_items() return self.results diff --git a/library/azure_rm_cdnendpoint_facts.py b/library/_azure_rm_cdnendpoint_facts.py similarity index 95% rename from library/azure_rm_cdnendpoint_facts.py rename to library/_azure_rm_cdnendpoint_facts.py index 02fc721..de2d869 100644 --- a/library/azure_rm_cdnendpoint_facts.py +++ b/library/_azure_rm_cdnendpoint_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_cdnendpoint_facts +module: azure_rm_cdnendpoint_info -version_added: "2.8" +version_added: "2.9" short_description: Get Azure CDN endpoint facts @@ -49,12 +49,12 @@ author: EXAMPLES = ''' - name: Get facts for all endpoints in CDN profile - azure_rm_cdnendpoint_facts: + azure_rm_cdnendpoint_info: resource_group: myResourceGroup profile_name: myCDNProfile - name: Get facts of specific CDN endpoint - azure_rm_cdnendpoint_facts: + azure_rm_cdnendpoint_info: resource_group: myResourceGroup profile_name: myCDNProfile name: myEndpoint1 @@ -180,7 +180,7 @@ import re AZURE_OBJECT_CLASS = 'endpoints' -class AzureRMCdnEndpointFacts(AzureRMModuleBase): +class AzureRMCdnEndpointInfo(AzureRMModuleBase): """Utility class to get Azure Azure CDN endpoint facts""" def __init__(self): @@ -208,7 +208,7 @@ class AzureRMCdnEndpointFacts(AzureRMModuleBase): self.profile_name = None self.tags = None - super(AzureRMCdnEndpointFacts, self).__init__( + super(AzureRMCdnEndpointInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True @@ -216,6 +216,10 @@ class AzureRMCdnEndpointFacts(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_cdnendpoint_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cdnendpoint_facts' module has been renamed to 'azure_rm_cdnendpoint_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) @@ -304,7 +308,7 @@ class AzureRMCdnEndpointFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMCdnEndpointFacts() + AzureRMCdnEndpointInfo() if __name__ == '__main__': diff --git a/library/azure_rm_cdnprofile_facts.py b/library/_azure_rm_cdnprofile_facts.py similarity index 93% rename from library/azure_rm_cdnprofile_facts.py rename to library/_azure_rm_cdnprofile_facts.py index e336e2e..3de6967 100644 --- a/library/azure_rm_cdnprofile_facts.py +++ b/library/_azure_rm_cdnprofile_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_cdnprofile_facts +module: azure_rm_cdnprofile_info -version_added: "2.8" +version_added: "2.9" short_description: Get Azure CDN profile facts @@ -44,15 +44,15 @@ author: EXAMPLES = ''' - name: Get facts for one CDN profile - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: name: Testing resource_group: myResourceGroup - name: Get facts for all CDN profiles - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: - name: Get facts by tags - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: tags: - Environment:Test ''' @@ -129,7 +129,7 @@ import re AZURE_OBJECT_CLASS = 'profiles' -class AzureRMCdnprofileFacts(AzureRMModuleBase): +class AzureRMCdnprofileInfo(AzureRMModuleBase): """Utility class to get Azure CDN profile facts""" def __init__(self): @@ -150,7 +150,7 @@ class AzureRMCdnprofileFacts(AzureRMModuleBase): self.tags = None self.cdn_client = None - super(AzureRMCdnprofileFacts, self).__init__( + super(AzureRMCdnprofileInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True @@ -158,6 +158,10 @@ class AzureRMCdnprofileFacts(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_cdnprofile_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cdnprofile_facts' module has been renamed to 'azure_rm_cdnprofile_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) @@ -257,7 +261,7 @@ class AzureRMCdnprofileFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMCdnprofileFacts() + AzureRMCdnprofileInfo() if __name__ == '__main__': diff --git a/library/azure_rm_containerinstance_facts.py b/library/_azure_rm_containerinstance_facts.py similarity index 94% rename from library/azure_rm_containerinstance_facts.py rename to library/_azure_rm_containerinstance_facts.py index eb25e3b..e918e89 100644 --- a/library/azure_rm_containerinstance_facts.py +++ b/library/_azure_rm_containerinstance_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_containerinstance_facts -version_added: "2.8" +module: azure_rm_containerinstance_info +version_added: "2.9" short_description: Get Azure Container Instance facts description: - Get facts of Container Instance. @@ -43,12 +43,12 @@ author: EXAMPLES = ''' - name: Get specific Container Instance facts - azure_rm_containerinstance_facts: + azure_rm_containerinstance_info: resource_group: myResourceGroup name: myContainer - name: List Container Instances in a specified resource group name - azure_rm_containerinstance_facts: + azure_rm_containerinstance_info: resource_group: myResourceGroup ''' @@ -184,7 +184,7 @@ except ImportError: pass -class AzureRMContainerInstanceFacts(AzureRMModuleBase): +class AzureRMContainerInstanceInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -206,9 +206,15 @@ class AzureRMContainerInstanceFacts(AzureRMModuleBase): ) self.resource_group = None self.name = None - super(AzureRMContainerInstanceFacts, self).__init__(self.module_arg_spec, supports_tags=False) + + super(AzureRMContainerInstanceInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_containerinstance_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_containerinstance_facts' module has been renamed to 'azure_rm_containerinstance_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -308,7 +314,7 @@ class AzureRMContainerInstanceFacts(AzureRMModuleBase): def main(): - AzureRMContainerInstanceFacts() + AzureRMContainerInstanceInfo() if __name__ == '__main__': diff --git a/library/azure_rm_containerregistry_facts.py b/library/_azure_rm_containerregistry_facts.py similarity index 93% rename from library/azure_rm_containerregistry_facts.py rename to library/_azure_rm_containerregistry_facts.py index f66cd13..c1a8334 100644 --- a/library/azure_rm_containerregistry_facts.py +++ b/library/_azure_rm_containerregistry_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_containerregistry_facts -version_added: "2.7" +module: azure_rm_containerregistry_info +version_added: "2.9" short_description: Get Azure Container Registry facts description: - Get facts for Container Registry. @@ -48,12 +48,12 @@ author: EXAMPLES = ''' - name: Get instance of Registry - azure_rm_containerregistry_facts: + azure_rm_containerregistry_info: resource_group: myResourceGroup name: myRegistry - name: List instances of Registry - azure_rm_containerregistry_facts: + azure_rm_containerregistry_info: resource_group: myResourceGroup ''' @@ -150,7 +150,7 @@ except ImportError: pass -class AzureRMContainerRegistryFacts(AzureRMModuleBase): +class AzureRMContainerRegistryInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -176,9 +176,15 @@ class AzureRMContainerRegistryFacts(AzureRMModuleBase): self.resource_group = None self.name = None self.retrieve_credentials = False - super(AzureRMContainerRegistryFacts, self).__init__(self.module_arg_spec, supports_tags=False) + + super(AzureRMContainerRegistryInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_containerregistry_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_containerregistry_facts' module has been renamed to 'azure_rm_containerregistry_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -270,7 +276,7 @@ class AzureRMContainerRegistryFacts(AzureRMModuleBase): def main(): - AzureRMContainerRegistryFacts() + AzureRMContainerRegistryInfo() if __name__ == '__main__': diff --git a/library/azure_rm_cosmosdbaccount_facts.py b/library/_azure_rm_cosmosdbaccount_facts.py similarity index 97% rename from library/azure_rm_cosmosdbaccount_facts.py rename to library/_azure_rm_cosmosdbaccount_facts.py index d350dd2..f247e91 100644 --- a/library/azure_rm_cosmosdbaccount_facts.py +++ b/library/_azure_rm_cosmosdbaccount_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_cosmosdbaccount_facts -version_added: "2.8" +module: azure_rm_cosmosdbaccount_info +version_added: "2.9" short_description: Get Azure Cosmos DB Account facts description: - Get facts of Azure Cosmos DB Account. @@ -53,12 +53,12 @@ author: EXAMPLES = ''' - name: Get instance of Database Account - azure_rm_cosmosdbaccount_facts: + azure_rm_cosmosdbaccount_info: resource_group: myResourceGroup name: testaccount - name: List instances of Database Account - azure_rm_cosmosdbaccousnt_facts: + azure_rm_cosmosdbaccousnt_info: resource_group: myResourceGroup ''' @@ -357,7 +357,7 @@ except ImportError: pass -class AzureRMCosmosDBAccountFacts(AzureRMModuleBase): +class AzureRMCosmosDBAccountInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -389,9 +389,14 @@ class AzureRMCosmosDBAccountFacts(AzureRMModuleBase): self.retrieve_keys = None self.retrieve_connection_strings = None - super(AzureRMCosmosDBAccountFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMCosmosDBAccountInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_cosmosdbaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cosmosdbaccount_facts' module has been renamed to 'azure_rm_cosmosdbaccount_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(CosmosDB, @@ -508,7 +513,7 @@ class AzureRMCosmosDBAccountFacts(AzureRMModuleBase): def main(): - AzureRMCosmosDBAccountFacts() + AzureRMCosmosDBAccountInfo() if __name__ == '__main__': diff --git a/library/azure_rm_deployment_facts.py b/library/_azure_rm_deployment_facts.py similarity index 93% rename from library/azure_rm_deployment_facts.py rename to library/_azure_rm_deployment_facts.py index 44d5a0c..9b6ac71 100644 --- a/library/azure_rm_deployment_facts.py +++ b/library/_azure_rm_deployment_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_deployment_facts -version_added: "2.8" +module: azure_rm_deployment_info +version_added: "2.9" short_description: Get Azure Deployment facts description: - Get facts of Azure Deployment. @@ -40,7 +40,7 @@ author: EXAMPLES = ''' - name: Get instance of Deployment - azure_rm_deployment_facts: + azure_rm_deployment_info: resource_group: myResourceGroup name: myDeployment ''' @@ -135,7 +135,7 @@ except ImportError: pass -class AzureRMDeploymentFacts(AzureRMModuleBase): +class AzureRMDeploymentInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( resource_group=dict( @@ -151,9 +151,15 @@ class AzureRMDeploymentFacts(AzureRMModuleBase): ) self.resource_group = None self.name = None - super(AzureRMDeploymentFacts, self).__init__(self.module_arg_spec, supports_tags=False) + + super(AzureRMDeploymentInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_deployment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_deployment_facts' module has been renamed to 'azure_rm_deployment_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -237,7 +243,7 @@ class AzureRMDeploymentFacts(AzureRMModuleBase): def main(): - AzureRMDeploymentFacts() + AzureRMDeploymentInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlab_facts.py b/library/_azure_rm_devtestlab_facts.py similarity index 93% rename from library/azure_rm_devtestlab_facts.py rename to library/_azure_rm_devtestlab_facts.py index 7a69797..24c52df 100644 --- a/library/azure_rm_devtestlab_facts.py +++ b/library/_azure_rm_devtestlab_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlab_facts -version_added: "2.8" +module: azure_rm_devtestlab_info +version_added: "2.9" short_description: Get Azure DevTest Lab facts description: - Get facts of Azure DevTest Lab. @@ -25,12 +25,15 @@ options: resource_group: description: - The name of the resource group. + type: str name: description: - The name of the lab. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -41,14 +44,14 @@ author: EXAMPLES = ''' - name: List instances of DevTest Lab by resource group - azure_rm_devtestlab_facts: + azure_rm_devtestlab_info: resource_group: testrg - name: List instances of DevTest Lab in subscription - azure_rm_devtestlab_facts: + azure_rm_devtestlab_info: - name: Get instance of DevTest Lab - azure_rm_devtestlab_facts: + azure_rm_devtestlab_info: resource_group: testrg name: testlab ''' @@ -151,7 +154,7 @@ except ImportError: pass -class AzureRMDevTestLabFacts(AzureRMModuleBase): +class AzureRMDevTestLabInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -173,9 +176,13 @@ class AzureRMDevTestLabFacts(AzureRMModuleBase): self.resource_group = None self.name = None self.tags = None - super(AzureRMDevTestLabFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDevTestLabInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlab_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlab_facts' module has been renamed to 'azure_rm_devtestlab_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -258,7 +265,7 @@ class AzureRMDevTestLabFacts(AzureRMModuleBase): def main(): - AzureRMDevTestLabFacts() + AzureRMDevTestLabInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabarmtemplate_facts.py b/library/_azure_rm_devtestlabarmtemplate_facts.py similarity index 91% rename from library/azure_rm_devtestlabarmtemplate_facts.py rename to library/_azure_rm_devtestlabarmtemplate_facts.py index be95ea1..d3189fe 100644 --- a/library/azure_rm_devtestlabarmtemplate_facts.py +++ b/library/_azure_rm_devtestlabarmtemplate_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabarmtemplate_facts -version_added: "2.8" +module: azure_rm_devtestlabarmtemplate_info +version_added: "2.9" short_description: Get Azure DevTest Lab ARM Template facts description: - Get facts of Azure DevTest Lab ARM Template. @@ -26,17 +26,21 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str artifact_source_name: description: - The name of the artifact source. required: True + type: str name: description: - The name of the ARM template. + type: str extends_documentation_fragment: - azure @@ -48,7 +52,7 @@ author: EXAMPLES = ''' - name: Get information on DevTest Lab ARM Template - azure_rm_devtestlabarmtemplate_facts: + azure_rm_devtestlabarmtemplate_info: resource_group: myResourceGroup lab_name: myLab artifact_source_name: public environment repo @@ -117,7 +121,7 @@ except ImportError: pass -class AzureRMDtlArmTemplateFacts(AzureRMModuleBase): +class AzureRMDtlArmTemplateInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -146,9 +150,13 @@ class AzureRMDtlArmTemplateFacts(AzureRMModuleBase): self.lab_name = None self.artifact_source_name = None self.name = None - super(AzureRMDtlArmTemplateFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlArmTemplateInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabarmtemplate_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabarmtemplate_facts' module has been renamed to 'azure_rm_devtestlabarmtemplate_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -211,7 +219,7 @@ class AzureRMDtlArmTemplateFacts(AzureRMModuleBase): def main(): - AzureRMDtlArmTemplateFacts() + AzureRMDtlArmTemplateInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabartifact_facts.py b/library/_azure_rm_devtestlabartifact_facts.py similarity index 95% rename from library/azure_rm_devtestlabartifact_facts.py rename to library/_azure_rm_devtestlabartifact_facts.py index f1bb7cc..612e143 100644 --- a/library/azure_rm_devtestlabartifact_facts.py +++ b/library/_azure_rm_devtestlabartifact_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabartifact_facts -version_added: "2.8" +module: azure_rm_devtestlabartifact_info +version_added: "2.9" short_description: Get Azure DevTest Lab Artifact facts description: - Get facts of Azure DevTest Lab Artifact. @@ -26,17 +26,21 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str artifact_source_name: description: - The name of the artifact source. required: True + type: str name: description: - The name of the artifact. + type: str extends_documentation_fragment: - azure @@ -48,7 +52,7 @@ author: EXAMPLES = ''' - name: Get instance of DevTest Lab Artifact - azure_rm_devtestlabartifact_facts: + azure_rm_devtestlabartifact_info: resource_group: myResourceGroup lab_name: myLab artifact_source_name: myArtifactSource @@ -142,7 +146,7 @@ except ImportError: pass -class AzureRMArtifactFacts(AzureRMModuleBase): +class AzureRMArtifactInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -171,7 +175,7 @@ class AzureRMArtifactFacts(AzureRMModuleBase): self.lab_name = None self.artifact_source_name = None self.name = None - super(AzureRMArtifactFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMArtifactInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): for key in self.module_arg_spec: @@ -239,7 +243,7 @@ class AzureRMArtifactFacts(AzureRMModuleBase): def main(): - AzureRMArtifactFacts() + AzureRMArtifactInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabartifactsource_facts.py b/library/_azure_rm_devtestlabartifactsource_facts.py similarity index 91% rename from library/azure_rm_devtestlabartifactsource_facts.py rename to library/_azure_rm_devtestlabartifactsource_facts.py index 4f7df8a..8446b7d 100644 --- a/library/azure_rm_devtestlabartifactsource_facts.py +++ b/library/_azure_rm_devtestlabartifactsource_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabartifactsource_facts -version_added: "2.8" +module: azure_rm_devtestlabartifactsource_info +version_added: "2.9" short_description: Get Azure DevTest Lab Artifact Source facts description: - Get facts of Azure DevTest Lab Artifact Source. @@ -26,16 +26,20 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of DevTest Lab. required: True + type: str name: description: - The name of DevTest Lab Artifact Source. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -47,7 +51,7 @@ author: EXAMPLES = ''' - name: Get instance of DevTest Lab Artifact Source - azure_rm_devtestlabartifactsource_facts: + azure_rm_devtestlabartifactsource_info: resource_group: myResourceGroup lab_name: myLab name: myArtifactSource @@ -146,7 +150,7 @@ except ImportError: pass -class AzureRMDtlArtifactSourceFacts(AzureRMModuleBase): +class AzureRMDtlArtifactSourceInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -174,9 +178,14 @@ class AzureRMDtlArtifactSourceFacts(AzureRMModuleBase): self.lab_name = None self.name = None self.tags = None - super(AzureRMDtlArtifactSourceFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlArtifactSourceInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabartifactsource_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabartifactsource_facts' module has been renamed to 'azure_rm_devtestlabartifactsource_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -242,7 +251,7 @@ class AzureRMDtlArtifactSourceFacts(AzureRMModuleBase): def main(): - AzureRMDtlArtifactSourceFacts() + AzureRMDtlArtifactSourceInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabcustomimage_facts.py b/library/_azure_rm_devtestlabcustomimage_facts.py similarity index 90% rename from library/azure_rm_devtestlabcustomimage_facts.py rename to library/_azure_rm_devtestlabcustomimage_facts.py index ed49eb6..8d964dc 100644 --- a/library/azure_rm_devtestlabcustomimage_facts.py +++ b/library/_azure_rm_devtestlabcustomimage_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabcustomimage_facts -version_added: "2.8" +module: azure_rm_devtestlabcustomimage_info +version_added: "2.9" short_description: Get Azure DevTest Lab Custom Image facts description: - Get facts of Azure Azure DevTest Lab Custom Image. @@ -26,16 +26,20 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str name: description: - The name of the custom image. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -47,13 +51,13 @@ author: EXAMPLES = ''' - name: Get instance of Custom Image - azure_rm_devtestlabcustomimage_facts: + azure_rm_devtestlabcustomimage_info: resource_group: myResourceGroup lab_name: myLab name: myImage - name: List instances of Custom Image in the lab - azure_rm_devtestlabcustomimage_facts: + azure_rm_devtestlabcustomimage_info: resource_group: myResourceGroup lab_name: myLab name: myImage @@ -123,7 +127,7 @@ except ImportError: pass -class AzureRMDtlCustomImageFacts(AzureRMModuleBase): +class AzureRMDtlCustomImageInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -152,9 +156,13 @@ class AzureRMDtlCustomImageFacts(AzureRMModuleBase): self.lab_name = None self.name = None self.tags = None - super(AzureRMDtlCustomImageFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlCustomImageInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabcustomimage_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabcustomimage_facts' module has been renamed to 'azure_rm_devtestlabcustomimage_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -214,7 +222,7 @@ class AzureRMDtlCustomImageFacts(AzureRMModuleBase): def main(): - AzureRMDtlCustomImageFacts() + AzureRMDtlCustomImageInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabenvironment_facts.py b/library/_azure_rm_devtestlabenvironment_facts.py similarity index 91% rename from library/azure_rm_devtestlabenvironment_facts.py rename to library/_azure_rm_devtestlabenvironment_facts.py index 002b47b..d3409c2 100644 --- a/library/azure_rm_devtestlabenvironment_facts.py +++ b/library/_azure_rm_devtestlabenvironment_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabenvironment_facts -version_added: "2.8" +module: azure_rm_devtestlabenvironment_info +version_added: "2.9" short_description: Get Azure Environment facts description: - Get facts of Azure Environment. @@ -26,20 +26,25 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str user_name: description: - The name of the user profile. required: True + type: str name: description: - The name of the environment. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -51,7 +56,7 @@ author: EXAMPLES = ''' - name: Get instance of Environment - azure_rm_devtestlabenvironment_facts: + azure_rm_devtestlabenvironment_info: resource_group: myResourceGroup lab_name: myLab user_name: myUser @@ -128,7 +133,7 @@ except ImportError: pass -class AzureRMDtlEnvironmentFacts(AzureRMModuleBase): +class AzureRMDtlEnvironmentInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -161,9 +166,13 @@ class AzureRMDtlEnvironmentFacts(AzureRMModuleBase): self.user_name = None self.name = None self.tags = None - super(AzureRMDtlEnvironmentFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlEnvironmentInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabenvironment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabenvironment_facts' module has been renamed to 'azure_rm_devtestlabenvironment_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -229,7 +238,7 @@ class AzureRMDtlEnvironmentFacts(AzureRMModuleBase): def main(): - AzureRMDtlEnvironmentFacts() + AzureRMDtlEnvironmentInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabpolicy_facts.py b/library/_azure_rm_devtestlabpolicy_facts.py similarity index 91% rename from library/azure_rm_devtestlabpolicy_facts.py rename to library/_azure_rm_devtestlabpolicy_facts.py index da9378a..7df4596 100644 --- a/library/azure_rm_devtestlabpolicy_facts.py +++ b/library/_azure_rm_devtestlabpolicy_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabpolicy_facts -version_added: "2.8" +module: azure_rm_devtestlabpolicy_info +version_added: "2.9" short_description: Get Azure DTL Policy facts description: - Get facts of Azure DTL Policy. @@ -26,20 +26,25 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str policy_set_name: description: - The name of the policy set. required: True + type: str name: description: - The name of the policy. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -51,7 +56,7 @@ author: EXAMPLES = ''' - name: Get instance of Policy - azure_rm_devtestlabpolicy_facts: + azure_rm_devtestlabpolicy_info: resource_group: myResourceGroup lab_name: myLab policy_set_name: myPolicySet @@ -127,7 +132,7 @@ except ImportError: pass -class AzureRMDtlPolicyFacts(AzureRMModuleBase): +class AzureRMDtlPolicyInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -160,9 +165,13 @@ class AzureRMDtlPolicyFacts(AzureRMModuleBase): self.policy_set_name = None self.name = None self.tags = None - super(AzureRMDtlPolicyFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlPolicyInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabpolicy_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabpolicy_facts' module has been renamed to 'azure_rm_devtestlabpolicy_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -227,7 +236,7 @@ class AzureRMDtlPolicyFacts(AzureRMModuleBase): def main(): - AzureRMDtlPolicyFacts() + AzureRMDtlPolicyInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabschedule_facts.py b/library/_azure_rm_devtestlabschedule_facts.py similarity index 90% rename from library/azure_rm_devtestlabschedule_facts.py rename to library/_azure_rm_devtestlabschedule_facts.py index be1b42b..f620d2c 100644 --- a/library/azure_rm_devtestlabschedule_facts.py +++ b/library/_azure_rm_devtestlabschedule_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabschedule_facts -version_added: "2.8" +module: azure_rm_devtestlabschedule_info +version_added: "2.9" short_description: Get Azure Schedule facts description: - Get facts of Azure Schedule. @@ -26,16 +26,20 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str name: description: - The name of the schedule. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -47,7 +51,7 @@ author: EXAMPLES = ''' - name: Get instance of Schedule - azure_rm_devtestlabschedule_facts: + azure_rm_devtestlabschedule_info: resource_group: myResourceGroup lab_name: myLab name: mySchedule @@ -117,7 +121,7 @@ except ImportError: pass -class AzureRMDtlScheduleFacts(AzureRMModuleBase): +class AzureRMDtlScheduleInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -145,9 +149,13 @@ class AzureRMDtlScheduleFacts(AzureRMModuleBase): self.lab_name = None self.name = None self.tags = None - super(AzureRMDtlScheduleFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlScheduleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabschedule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabschedule_facts' module has been renamed to 'azure_rm_devtestlabschedule_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -207,7 +215,7 @@ class AzureRMDtlScheduleFacts(AzureRMModuleBase): def main(): - AzureRMDtlScheduleFacts() + AzureRMDtlScheduleInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabvirtualmachine_facts.py b/library/_azure_rm_devtestlabvirtualmachine_facts.py similarity index 93% rename from library/azure_rm_devtestlabvirtualmachine_facts.py rename to library/_azure_rm_devtestlabvirtualmachine_facts.py index 9b41816..b41e100 100644 --- a/library/azure_rm_devtestlabvirtualmachine_facts.py +++ b/library/_azure_rm_devtestlabvirtualmachine_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabvirtualmachine_facts -version_added: "2.8" +module: azure_rm_devtestlabvirtualmachine_info +version_added: "2.9" short_description: Get Azure DevTest Lab Virtual Machine facts description: - Get facts of Azure DevTest Lab Virtual Machine. @@ -26,16 +26,20 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of the lab. required: True + type: str name: description: - The name of the virtual machine. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -47,7 +51,7 @@ author: EXAMPLES = ''' - name: Get instance of DTL Virtual Machine - azure_rm_devtestlabvirtualmachine_facts: + azure_rm_devtestlabvirtualmachine_info: resource_group: myResourceGroup lab_name: myLab name: myVm @@ -212,7 +216,7 @@ except ImportError: pass -class AzureRMDtlVirtualMachineFacts(AzureRMModuleBase): +class AzureRMDtlVirtualMachineInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -240,9 +244,14 @@ class AzureRMDtlVirtualMachineFacts(AzureRMModuleBase): self.lab_name = None self.name = None self.tags = None - super(AzureRMDtlVirtualMachineFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDtlVirtualMachineInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabvirtualmachine_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabvirtualmachine_facts' module has been renamed to 'azure_rm_devtestlabvirtualmachine_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -313,7 +322,7 @@ class AzureRMDtlVirtualMachineFacts(AzureRMModuleBase): def main(): - AzureRMDtlVirtualMachineFacts() + AzureRMDtlVirtualMachineInfo() if __name__ == '__main__': diff --git a/library/azure_rm_devtestlabvirtualnetwork_facts.py b/library/_azure_rm_devtestlabvirtualnetwork_facts.py similarity index 89% rename from library/azure_rm_devtestlabvirtualnetwork_facts.py rename to library/_azure_rm_devtestlabvirtualnetwork_facts.py index 55559ba..c96941c 100644 --- a/library/azure_rm_devtestlabvirtualnetwork_facts.py +++ b/library/_azure_rm_devtestlabvirtualnetwork_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_devtestlabvirtualnetwork_facts -version_added: "2.8" +module: azure_rm_devtestlabvirtualnetwork_info +version_added: "2.9" short_description: Get Azure DevTest Lab Virtual Network facts description: - Get facts of Azure DevTest Lab Virtual Network. @@ -26,13 +26,16 @@ options: description: - The name of the resource group. required: True + type: str lab_name: description: - The name of DevTest Lab. required: True + type: str name: description: - The name of DevTest Lab Virtual Network. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get instance of DevTest Lab Virtual Network - azure_rm_devtestlabvirtualnetwork_facts: + azure_rm_devtestlabvirtualnetwork_info: resource_group: myResourceGroup lab_name: myLab name: myVirtualNetwork - name: List all Virtual Networks in DevTest Lab - azure_rm_devtestlabvirtualnetwork_facts: + azure_rm_devtestlabvirtualnetwork_info: resource_group: myResourceGroup lab_name: myLab name: myVirtualNetwork @@ -120,7 +123,7 @@ except ImportError: pass -class AzureRMDevTestLabVirtualNetworkFacts(AzureRMModuleBase): +class AzureRMDevTestLabVirtualNetworkInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -144,9 +147,14 @@ class AzureRMDevTestLabVirtualNetworkFacts(AzureRMModuleBase): self.resource_group = None self.lab_name = None self.name = None - super(AzureRMDevTestLabVirtualNetworkFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMDevTestLabVirtualNetworkInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabvirtualnetwork_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabvirtualnetwork_facts' module has been renamed to 'azure_rm_devtestlabvirtualnetwork_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, @@ -206,7 +214,7 @@ class AzureRMDevTestLabVirtualNetworkFacts(AzureRMModuleBase): def main(): - AzureRMDevTestLabVirtualNetworkFacts() + AzureRMDevTestLabVirtualNetworkInfo() if __name__ == '__main__': diff --git a/library/azure_rm_dnsrecordset_facts.py b/library/_azure_rm_dnsrecordset_facts.py similarity index 92% rename from library/azure_rm_dnsrecordset_facts.py rename to library/_azure_rm_dnsrecordset_facts.py index 88d8104..e6f6220 100644 --- a/library/azure_rm_dnsrecordset_facts.py +++ b/library/_azure_rm_dnsrecordset_facts.py @@ -13,9 +13,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_dnsrecordset_facts +module: azure_rm_dnsrecordset_info -version_added: "2.4" +version_added: "2.9" short_description: Get DNS Record Set facts @@ -51,18 +51,18 @@ author: EXAMPLES = ''' - name: Get facts for one Record Set - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: myResourceGroup zone_name: example.com relative_name: server10 record_type: A - name: Get facts for all Type A Record Sets in a Zone - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: myResourceGroup zone_name: example.com record_type: A - name: Get all record sets in one zone - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: myResourceGroup zone_name: example.com ''' @@ -163,7 +163,7 @@ RECORDSET_VALUE_MAP = dict( ) -class AzureRMRecordSetFacts(AzureRMModuleBase): +class AzureRMRecordSetInfo(AzureRMModuleBase): def __init__(self): @@ -179,7 +179,7 @@ class AzureRMRecordSetFacts(AzureRMModuleBase): # store the results of the module operation self.results = dict( changed=False, - ansible_facts=dict(azure_dnsrecordset=[]) + ansible_info=dict(azure_dnsrecordset=[]) ) self.relative_name = None @@ -188,10 +188,14 @@ class AzureRMRecordSetFacts(AzureRMModuleBase): self.record_type = None self.top = None - super(AzureRMRecordSetFacts, self).__init__(self.module_arg_spec) + super(AzureRMRecordSetInfo, self).__init__(self.module_arg_spec) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_dnsrecordset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_dnsrecordset_facts' module has been renamed to 'azure_rm_dnsrecordset_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -216,7 +220,8 @@ class AzureRMRecordSetFacts(AzureRMModuleBase): # if there is a zone name listed, then they want all the record sets in a zone results = self.list_zone() - self.results['ansible_facts']['azure_dnsrecordset'] = self.serialize_list(results) + if is_old_facts: + self.results['ansible_facts']['azure_dnsrecordset'] = self.serialize_list(results) self.results['dnsrecordsets'] = self.curated_list(results) return self.results @@ -281,7 +286,7 @@ class AzureRMRecordSetFacts(AzureRMModuleBase): def main(): - AzureRMRecordSetFacts() + AzureRMRecordSetInfo() if __name__ == '__main__': diff --git a/library/azure_rm_dnszone_facts.py b/library/_azure_rm_dnszone_facts.py similarity index 92% rename from library/azure_rm_dnszone_facts.py rename to library/_azure_rm_dnszone_facts.py index 6c81b52..a09e2aa 100644 --- a/library/azure_rm_dnszone_facts.py +++ b/library/_azure_rm_dnszone_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_dnszone_facts +module: azure_rm_dnszone_info -version_added: "2.4" +version_added: "2.9" short_description: Get DNS zone facts @@ -45,16 +45,16 @@ author: EXAMPLES = ''' - name: Get facts for one zone - azure_rm_dnszone_facts: + azure_rm_dnszone_info: resource_group: myResourceGroup name: foobar22 - name: Get facts for all zones in a resource group - azure_rm_dnszone_facts: + azure_rm_dnszone_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_dnszone_facts: + azure_rm_dnszone_info: tags: - testing ''' @@ -137,7 +137,7 @@ except Exception: AZURE_OBJECT_CLASS = 'DnsZone' -class AzureRMDNSZoneFacts(AzureRMModuleBase): +class AzureRMDNSZoneInfo(AzureRMModuleBase): def __init__(self): @@ -151,17 +151,21 @@ class AzureRMDNSZoneFacts(AzureRMModuleBase): # store the results of the module operation self.results = dict( changed=False, - ansible_facts=dict(azure_dnszones=[]) + ansible_info=dict(azure_dnszones=[]) ) self.name = None self.resource_group = None self.tags = None - super(AzureRMDNSZoneFacts, self).__init__(self.module_arg_spec) + super(AzureRMDNSZoneInfo, self).__init__(self.module_arg_spec) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_dnszone_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_dnszone_facts' module has been renamed to 'azure_rm_dnszone_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -180,7 +184,7 @@ class AzureRMDNSZoneFacts(AzureRMModuleBase): # all the zones in a subscription results = self.list_items() - self.results['ansible_facts']['azure_dnszones'] = self.serialize_items(results) + self.results['ansible_info']['azure_dnszones'] = self.serialize_items(results) self.results['dnszones'] = self.curated_items(results) return self.results @@ -247,7 +251,7 @@ class AzureRMDNSZoneFacts(AzureRMModuleBase): def main(): - AzureRMDNSZoneFacts() + AzureRMDNSZoneInfo() if __name__ == '__main__': diff --git a/library/azure_rm_functionapp_facts.py b/library/_azure_rm_functionapp_facts.py similarity index 86% rename from library/azure_rm_functionapp_facts.py rename to library/_azure_rm_functionapp_facts.py index b3fbb1f..0cd5b6f 100644 --- a/library/azure_rm_functionapp_facts.py +++ b/library/_azure_rm_functionapp_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_functionapp_facts -version_added: "2.4" +module: azure_rm_functionapp_info +version_added: "2.9" short_description: Get Azure Function App facts description: - Get facts for one Azure Function App or all Function Apps within a resource group. @@ -42,16 +42,16 @@ author: EXAMPLES = ''' - name: Get facts for one Function App - azure_rm_functionapp_facts: + azure_rm_functionapp_info: resource_group: myResourceGroup name: myfunctionapp - name: Get facts for all Function Apps in a resource group - azure_rm_functionapp_facts: + azure_rm_functionapp_info: resource_group: myResourceGroup - name: Get facts for all Function Apps by tags - azure_rm_functionapp_facts: + azure_rm_functionapp_info: tags: - testing ''' @@ -108,7 +108,7 @@ except Exception: from ansible.module_utils.azure_rm_common import AzureRMModuleBase -class AzureRMFunctionAppFacts(AzureRMModuleBase): +class AzureRMFunctionAppInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( @@ -119,14 +119,14 @@ class AzureRMFunctionAppFacts(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict(azure_functionapps=[]) + ansible_info=dict(azure_functionapps=[]) ) self.name = None self.resource_group = None self.tags = None - super(AzureRMFunctionAppFacts, self).__init__( + super(AzureRMFunctionAppInfo, self).__init__( self.module_arg_spec, supports_tags=False, facts_module=True @@ -134,6 +134,10 @@ class AzureRMFunctionAppFacts(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_functionapp_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_functionapp_facts' module has been renamed to 'azure_rm_functionapp_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -141,11 +145,11 @@ class AzureRMFunctionAppFacts(AzureRMModuleBase): self.fail("Parameter error: resource group required when filtering by name.") if self.name: - self.results['ansible_facts']['azure_functionapps'] = self.get_functionapp() + self.results['ansible_info']['azure_functionapps'] = self.get_functionapp() elif self.resource_group: - self.results['ansible_facts']['azure_functionapps'] = self.list_resource_group() + self.results['ansible_info']['azure_functionapps'] = self.list_resource_group() else: - self.results['ansible_facts']['azure_functionapps'] = self.list_all() + self.results['ansible_info']['azure_functionapps'] = self.list_all() return self.results @@ -195,7 +199,7 @@ class AzureRMFunctionAppFacts(AzureRMModuleBase): def main(): - AzureRMFunctionAppFacts() + AzureRMFunctionAppInfo() if __name__ == '__main__': diff --git a/library/azure_rm_hdinsightcluster_facts.py b/library/_azure_rm_hdinsightcluster_facts.py similarity index 94% rename from library/azure_rm_hdinsightcluster_facts.py rename to library/_azure_rm_hdinsightcluster_facts.py index 80e3fe1..9a703e9 100644 --- a/library/azure_rm_hdinsightcluster_facts.py +++ b/library/_azure_rm_hdinsightcluster_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_hdinsightcluster_facts -version_added: "2.8" +module: azure_rm_hdinsightcluster_info +version_added: "2.9" short_description: Get Azure HDInsight Cluster facts description: - Get facts of Azure HDInsight Cluster. @@ -42,12 +42,12 @@ author: EXAMPLES = ''' - name: Get instance of HDInsight Cluster - azure_rm_hdinsightcluster_facts: + azure_rm_hdinsightcluster_info: resource_group: myResourceGroup name: myCluster - name: List instances of HDInsight Cluster - azure_rm_hdinsightcluster_facts: + azure_rm_hdinsightcluster_info: resource_group: myResourceGroup ''' @@ -192,7 +192,7 @@ except ImportError: pass -class AzureRMHDInsightclusterFacts(AzureRMModuleBase): +class AzureRMHDInsightclusterInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -215,9 +215,15 @@ class AzureRMHDInsightclusterFacts(AzureRMModuleBase): self.name = None self.tags = None - super(AzureRMHDInsightclusterFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMHDInsightclusterInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_hdinsightcluster_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_hdinsightcluster_facts' module has been renamed to 'azure_rm_hdinsightcluster_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(HDInsightManagementClient, @@ -308,7 +314,7 @@ class AzureRMHDInsightclusterFacts(AzureRMModuleBase): def main(): - AzureRMHDInsightclusterFacts() + AzureRMHDInsightclusterInfo() if __name__ == '__main__': diff --git a/library/azure_rm_image_facts.py b/library/_azure_rm_image_facts.py similarity index 95% rename from library/azure_rm_image_facts.py rename to library/_azure_rm_image_facts.py index 2b73f46..10a53f2 100644 --- a/library/azure_rm_image_facts.py +++ b/library/_azure_rm_image_facts.py @@ -12,9 +12,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_image_facts +module: azure_rm_image_info -version_added: "2.8" +version_added: "2.9" short_description: Get facts about azure custom images @@ -42,19 +42,19 @@ author: EXAMPLES = ''' - name: List images with name - azure_rm_image_facts: + azure_rm_image_info: name: test-image resource_group: myResourceGroup - name: List images by resource group - azure_rm_image_facts: + azure_rm_image_info: resource_group: myResourceGroup tags: - testing - foo:bar - name: List all available images under current subscription - azure_rm_image_facts: + azure_rm_image_info: ''' @@ -179,7 +179,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] -class AzureRMImageFacts(AzureRMModuleBase): +class AzureRMImageInfo(AzureRMModuleBase): def __init__(self, **kwargs): @@ -198,7 +198,7 @@ class AzureRMImageFacts(AzureRMModuleBase): self.format = None self.tags = None - super(AzureRMImageFacts, self).__init__( + super(AzureRMImageInfo, self).__init__( derived_arg_spec=self.module_arg_spec, supports_tags=False, facts_module=True @@ -206,6 +206,10 @@ class AzureRMImageFacts(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_image_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_image_facts' module has been renamed to 'azure_rm_image_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -296,7 +300,7 @@ class AzureRMImageFacts(AzureRMModuleBase): def main(): - AzureRMImageFacts() + AzureRMImageInfo() if __name__ == '__main__': diff --git a/library/azure_rm_loadbalancer_facts.py b/library/_azure_rm_loadbalancer_facts.py similarity index 85% rename from library/azure_rm_loadbalancer_facts.py rename to library/_azure_rm_loadbalancer_facts.py index 2fefca4..af4507c 100644 --- a/library/azure_rm_loadbalancer_facts.py +++ b/library/_azure_rm_loadbalancer_facts.py @@ -15,9 +15,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_loadbalancer_facts +module: azure_rm_loadbalancer_info -version_added: "2.4" +version_added: "2.9" short_description: Get load balancer facts @@ -44,19 +44,19 @@ author: EXAMPLES = ''' - name: Get facts for one load balancer - azure_rm_loadbalancer_facts: + azure_rm_loadbalancer_info: name: Testing resource_group: myResourceGroup - name: Get facts for all load balancers - azure_rm_loadbalancer_facts: + azure_rm_loadbalancer_info: - name: Get facts for all load balancers in a specific resource group - azure_rm_loadbalancer_facts: + azure_rm_loadbalancer_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_loadbalancer_facts: + azure_rm_loadbalancer_info: tags: - testing ''' @@ -81,7 +81,7 @@ except Exception: AZURE_OBJECT_CLASS = 'LoadBalancer' -class AzureRMLoadBalancerFacts(AzureRMModuleBase): +class AzureRMLoadBalancerInfo(AzureRMModuleBase): """Utility class to get load balancer facts""" def __init__(self): @@ -94,7 +94,7 @@ class AzureRMLoadBalancerFacts(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict( + ansible_info=dict( azure_loadbalancers=[] ) ) @@ -103,7 +103,7 @@ class AzureRMLoadBalancerFacts(AzureRMModuleBase): self.resource_group = None self.tags = None - super(AzureRMLoadBalancerFacts, self).__init__( + super(AzureRMLoadBalancerInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True @@ -111,10 +111,14 @@ class AzureRMLoadBalancerFacts(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_loadbalancer_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_loadbalancer_facts' module has been renamed to 'azure_rm_loadbalancer_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) - self.results['ansible_facts']['azure_loadbalancers'] = ( + self.results['ansible_info']['azure_loadbalancers'] = ( self.get_item() if self.name else self.list_items() ) @@ -166,7 +170,7 @@ class AzureRMLoadBalancerFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMLoadBalancerFacts() + AzureRMLoadBalancerInfo() if __name__ == '__main__': diff --git a/library/azure_rm_lock_facts.py b/library/_azure_rm_lock_facts.py similarity index 92% rename from library/azure_rm_lock_facts.py rename to library/_azure_rm_lock_facts.py index e6ac7bb..cf8c1d1 100644 --- a/library/azure_rm_lock_facts.py +++ b/library/_azure_rm_lock_facts.py @@ -15,7 +15,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_lock_facts +module: azure_rm_lock_info version_added: "2.9" short_description: Manage Azure locks description: @@ -56,27 +56,27 @@ author: EXAMPLES = ''' - name: Get myLock details of myVM - azure_rm_lock_facts: + azure_rm_lock_info: name: myLock managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM - name: List locks of myVM - azure_rm_lock_facts: + azure_rm_lock_info: managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM - name: List locks of myResourceGroup - azure_rm_lock_facts: + azure_rm_lock_info: resource_group: myResourceGroup - name: List locks of myResourceGroup - azure_rm_lock_facts: + azure_rm_lock_info: managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup - name: List locks of mySubscription - azure_rm_lock_facts: + azure_rm_lock_info: - name: List locks of mySubscription - azure_rm_lock_facts: + azure_rm_lock_info: managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ''' @@ -126,7 +126,7 @@ except ImportError: pass -class AzureRMLockFacts(AzureRMModuleBase): +class AzureRMLockInfo(AzureRMModuleBase): def __init__(self): @@ -150,10 +150,14 @@ class AzureRMLockFacts(AzureRMModuleBase): self._query_parameters = {'api-version': '2016-09-01'} self._header_parameters = {'Content-Type': 'application/json; charset=utf-8'} - super(AzureRMLockFacts, self).__init__(self.module_arg_spec, facts_module=True, mutually_exclusive=mutually_exclusive, supports_tags=False) + super(AzureRMLockInfo, self).__init__(self.module_arg_spec, facts_module=True, mutually_exclusive=mutually_exclusive, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_lock_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_lock_facts' module has been renamed to 'azure_rm_lock_info'", version='2.13') + for key in self.module_arg_spec.keys(): setattr(self, key, kwargs[key]) @@ -212,7 +216,7 @@ class AzureRMLockFacts(AzureRMModuleBase): def main(): - AzureRMLockFacts() + AzureRMLockInfo() if __name__ == '__main__': diff --git a/library/azure_rm_loganalyticsworkspace_facts.py b/library/_azure_rm_loganalyticsworkspace_facts.py similarity index 93% rename from library/azure_rm_loganalyticsworkspace_facts.py rename to library/_azure_rm_loganalyticsworkspace_facts.py index ce101c2..03f841e 100644 --- a/library/azure_rm_loganalyticsworkspace_facts.py +++ b/library/_azure_rm_loganalyticsworkspace_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_loganalyticsworkspace_facts -version_added: "2.8" +module: azure_rm_loganalyticsworkspace_info +version_added: "2.9" short_description: Get facts of Azure Log Analytics workspaces description: - Get, query Azure Log Analytics workspaces. @@ -57,7 +57,7 @@ author: EXAMPLES = ''' - name: Query a workspace - azure_rm_loganalyticsworkspace_facts: + azure_rm_loganalyticsworkspace_info: resource_group: myResourceGroup name: myLogAnalyticsWorkspace show_intelligence_packs: true @@ -148,7 +148,7 @@ except ImportError: pass -class AzureRMLogAnalyticsWorkspaceFact(AzureRMModuleBase): +class AzureRMLogAnalyticsWorkspaceInfo(AzureRMModuleBase): def __init__(self): @@ -175,10 +175,15 @@ class AzureRMLogAnalyticsWorkspaceFact(AzureRMModuleBase): self.show_usages = None self.show_management_groups = None - super(AzureRMLogAnalyticsWorkspaceFact, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) + super(AzureRMLogAnalyticsWorkspaceInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_loganalyticsworkspace_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_loganalyticsworkspace_facts' module has been renamed to 'azure_rm_loganalyticsworkspace_info'", + version='2.13') + for key in list(self.module_arg_spec.keys()): setattr(self, key, kwargs[key]) @@ -257,7 +262,7 @@ class AzureRMLogAnalyticsWorkspaceFact(AzureRMModuleBase): def main(): - AzureRMLogAnalyticsWorkspaceFact() + AzureRMLogAnalyticsWorkspaceInfo() if __name__ == '__main__': diff --git a/library/_azure_rm_managed_disk_facts.py b/library/_azure_rm_managed_disk_facts.py index 50f9eab..cc90cb9 100644 --- a/library/_azure_rm_managed_disk_facts.py +++ b/library/_azure_rm_managed_disk_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = r''' --- -module: azure_rm_manageddisk_facts +module: azure_rm_manageddisk_info -version_added: "2.4" +version_added: "2.9" short_description: Get managed disk facts @@ -51,15 +51,15 @@ author: EXAMPLES = r''' - name: Get facts for one managed disk - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: name: Testing resource_group: myResourceGroup - name: Get facts for all managed disks - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: - name: Get facts by tags - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: tags: - testing ''' @@ -147,7 +147,7 @@ def managed_disk_to_dict(managed_disk): ) -class AzureRMManagedDiskFacts(AzureRMModuleBase): +class AzureRMManagedDiskInfo(AzureRMModuleBase): """Utility class to get managed disk facts""" def __init__(self): @@ -163,7 +163,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): ), ) self.results = dict( - ansible_facts=dict( + ansible_info=dict( azure_managed_disk=[] ) ) @@ -173,7 +173,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): self.source_uri = None self.source_resource_uri = None self.tags = None - super(AzureRMManagedDiskFacts, self).__init__( + super(AzureRMManagedDiskInfo, self).__init__( derived_arg_spec=self.module_arg_spec, supports_check_mode=True, supports_tags=True) @@ -182,7 +182,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): for key in self.module_arg_spec: setattr(self, key, kwargs[key]) - self.results['ansible_facts']['azure_managed_disk'] = ( + self.results['ansible_info']['azure_managed_disk'] = ( self.get_item() if self.name else (self.list_items_by_resource_group() if self.resource_group else self.list_items()) ) @@ -236,7 +236,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMManagedDiskFacts() + AzureRMManagedDiskInfo() if __name__ == '__main__': diff --git a/library/azure_rm_manageddisk_facts.py b/library/_azure_rm_manageddisk_facts.py similarity index 94% rename from library/azure_rm_manageddisk_facts.py rename to library/_azure_rm_manageddisk_facts.py index 50f9eab..cc90cb9 100644 --- a/library/azure_rm_manageddisk_facts.py +++ b/library/_azure_rm_manageddisk_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = r''' --- -module: azure_rm_manageddisk_facts +module: azure_rm_manageddisk_info -version_added: "2.4" +version_added: "2.9" short_description: Get managed disk facts @@ -51,15 +51,15 @@ author: EXAMPLES = r''' - name: Get facts for one managed disk - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: name: Testing resource_group: myResourceGroup - name: Get facts for all managed disks - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: - name: Get facts by tags - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: tags: - testing ''' @@ -147,7 +147,7 @@ def managed_disk_to_dict(managed_disk): ) -class AzureRMManagedDiskFacts(AzureRMModuleBase): +class AzureRMManagedDiskInfo(AzureRMModuleBase): """Utility class to get managed disk facts""" def __init__(self): @@ -163,7 +163,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): ), ) self.results = dict( - ansible_facts=dict( + ansible_info=dict( azure_managed_disk=[] ) ) @@ -173,7 +173,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): self.source_uri = None self.source_resource_uri = None self.tags = None - super(AzureRMManagedDiskFacts, self).__init__( + super(AzureRMManagedDiskInfo, self).__init__( derived_arg_spec=self.module_arg_spec, supports_check_mode=True, supports_tags=True) @@ -182,7 +182,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): for key in self.module_arg_spec: setattr(self, key, kwargs[key]) - self.results['ansible_facts']['azure_managed_disk'] = ( + self.results['ansible_info']['azure_managed_disk'] = ( self.get_item() if self.name else (self.list_items_by_resource_group() if self.resource_group else self.list_items()) ) @@ -236,7 +236,7 @@ class AzureRMManagedDiskFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMManagedDiskFacts() + AzureRMManagedDiskInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mariadbconfiguration_facts.py b/library/_azure_rm_mariadbconfiguration_facts.py similarity index 90% rename from library/azure_rm_mariadbconfiguration_facts.py rename to library/_azure_rm_mariadbconfiguration_facts.py index 888aaf2..ad38f12 100644 --- a/library/azure_rm_mariadbconfiguration_facts.py +++ b/library/_azure_rm_mariadbconfiguration_facts.py @@ -16,8 +16,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mariadbconfiguration_facts -version_added: "2.8" +module: azure_rm_mariadbconfiguration_info +version_added: "2.9" short_description: Get Azure MariaDB Configuration facts description: - Get facts of Azure MariaDB Configuration. @@ -27,13 +27,16 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - Setting name. + type: str extends_documentation_fragment: - azure @@ -46,13 +49,13 @@ author: EXAMPLES = ''' - name: Get specific setting of MariaDB Server - azure_rm_mariadbconfiguration_facts: + azure_rm_mariadbconfiguration_info: resource_group: myResourceGroup server_name: testserver name: deadlock_timeout - name: Get all settings of MariaDB Server - azure_rm_mariadbconfiguration_facts: + azure_rm_mariadbconfiguration_info: resource_group: myResourceGroup server_name: server_name ''' @@ -109,7 +112,7 @@ except ImportError: pass -class AzureRMMariaDbConfigurationFacts(AzureRMModuleBase): +class AzureRMMariaDbConfigurationInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -131,9 +134,13 @@ class AzureRMMariaDbConfigurationFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMariaDbConfigurationFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMariaDbConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbconfiguration_facts' module has been renamed to 'azure_rm_mariadbconfiguration_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(MariaDBManagementClient, @@ -202,7 +209,7 @@ class AzureRMMariaDbConfigurationFacts(AzureRMModuleBase): def main(): - AzureRMMariaDbConfigurationFacts() + AzureRMMariaDbConfigurationInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mariadbdatabase_facts.py b/library/_azure_rm_mariadbdatabase_facts.py similarity index 90% rename from library/azure_rm_mariadbdatabase_facts.py rename to library/_azure_rm_mariadbdatabase_facts.py index fc970a9..61e3301 100644 --- a/library/azure_rm_mariadbdatabase_facts.py +++ b/library/_azure_rm_mariadbdatabase_facts.py @@ -16,8 +16,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mariadbdatabase_facts -version_added: "2.8" +module: azure_rm_mariadbdatabase_info +version_added: "2.9" short_description: Get Azure MariaDB Database facts description: - Get facts of MariaDB Database. @@ -27,13 +27,16 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the database. + type: str extends_documentation_fragment: - azure @@ -46,13 +49,13 @@ author: EXAMPLES = ''' - name: Get instance of MariaDB Database - azure_rm_mariadbdatabase_facts: + azure_rm_mariadbdatabase_info: resource_group: myResourceGroup server_name: server_name name: database_name - name: List instances of MariaDB Database - azure_rm_mariadbdatabase_facts: + azure_rm_mariadbdatabase_info: resource_group: myResourceGroup server_name: server_name ''' @@ -114,7 +117,7 @@ except ImportError: pass -class AzureRMMariaDbDatabaseFacts(AzureRMModuleBase): +class AzureRMMariaDbDatabaseInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -137,9 +140,13 @@ class AzureRMMariaDbDatabaseFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMariaDbDatabaseFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMariaDbDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbdatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbdatabase_facts' module has been renamed to 'azure_rm_mariadbdatabase_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -197,7 +204,7 @@ class AzureRMMariaDbDatabaseFacts(AzureRMModuleBase): def main(): - AzureRMMariaDbDatabaseFacts() + AzureRMMariaDbDatabaseInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mariadbfirewallrule_facts.py b/library/_azure_rm_mariadbfirewallrule_facts.py similarity index 89% rename from library/azure_rm_mariadbfirewallrule_facts.py rename to library/_azure_rm_mariadbfirewallrule_facts.py index d6ca076..45557b5 100644 --- a/library/azure_rm_mariadbfirewallrule_facts.py +++ b/library/_azure_rm_mariadbfirewallrule_facts.py @@ -16,8 +16,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mariadbfirewallrule_facts -version_added: "2.8" +module: azure_rm_mariadbfirewallrule_info +version_added: "2.9" short_description: Get Azure MariaDB Firewall Rule facts description: - Get facts of Azure MariaDB Firewall Rule. @@ -27,13 +27,16 @@ options: description: - The name of the resource group. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the server firewall rule. + type: str extends_documentation_fragment: - azure @@ -46,13 +49,13 @@ author: EXAMPLES = ''' - name: Get instance of MariaDB Firewall Rule - azure_rm_mariadbfirewallrule_facts: + azure_rm_mariadbfirewallrule_info: resource_group: myResourceGroup server_name: server_name name: firewall_rule_name - name: List instances of MariaDB Firewall Rule - azure_rm_mariadbfirewallrule_facts: + azure_rm_mariadbfirewallrule_info: resource_group: myResourceGroup server_name: server_name ''' @@ -109,7 +112,7 @@ except ImportError: pass -class AzureRMMariaDbFirewallRuleFacts(AzureRMModuleBase): +class AzureRMMariaDbFirewallRuleInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -133,9 +136,13 @@ class AzureRMMariaDbFirewallRuleFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMariaDbFirewallRuleFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMariaDbFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbfirewallrule_facts' module has been renamed to 'azure_rm_mariadbfirewallrule_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(MariaDBManagementClient, @@ -193,7 +200,7 @@ class AzureRMMariaDbFirewallRuleFacts(AzureRMModuleBase): def main(): - AzureRMMariaDbFirewallRuleFacts() + AzureRMMariaDbFirewallRuleInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mariadbserver_facts.py b/library/_azure_rm_mariadbserver_facts.py similarity index 92% rename from library/azure_rm_mariadbserver_facts.py rename to library/_azure_rm_mariadbserver_facts.py index 8669bd1..ffe52c5 100644 --- a/library/azure_rm_mariadbserver_facts.py +++ b/library/_azure_rm_mariadbserver_facts.py @@ -16,8 +16,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mariadbserver_facts -version_added: "2.8" +module: azure_rm_mariadbserver_info +version_added: "2.9" short_description: Get Azure MariaDB Server facts description: - Get facts of MariaDB Server. @@ -27,12 +27,15 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str name: description: - The name of the server. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -45,12 +48,12 @@ author: EXAMPLES = ''' - name: Get instance of MariaDB Server - azure_rm_mariadbserver_facts: + azure_rm_mariadbserver_info: resource_group: myResourceGroup name: server_name - name: List instances of MariaDB Server - azure_rm_mariadbserver_facts: + azure_rm_mariadbserver_info: resource_group: myResourceGroup ''' @@ -163,7 +166,7 @@ except ImportError: pass -class AzureRMMariaDbServerFacts(AzureRMModuleBase): +class AzureRMMariaDbServerInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -185,9 +188,13 @@ class AzureRMMariaDbServerFacts(AzureRMModuleBase): self.resource_group = None self.name = None self.tags = None - super(AzureRMMariaDbServerFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMariaDbServerInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbserver_facts' module has been renamed to 'azure_rm_mariadbserver_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -250,7 +257,7 @@ class AzureRMMariaDbServerFacts(AzureRMModuleBase): def main(): - AzureRMMariaDbServerFacts() + AzureRMMariaDbServerInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mysqlconfiguration_facts.py b/library/_azure_rm_mysqlconfiguration_facts.py similarity index 90% rename from library/azure_rm_mysqlconfiguration_facts.py rename to library/_azure_rm_mysqlconfiguration_facts.py index de044b8..8fe9113 100644 --- a/library/azure_rm_mysqlconfiguration_facts.py +++ b/library/_azure_rm_mysqlconfiguration_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mysqlconfiguration_facts -version_added: "2.8" +module: azure_rm_mysqlconfiguration_info +version_added: "2.9" short_description: Get Azure MySQL Configuration facts description: - Get facts of Azure MySQL Configuration. @@ -26,13 +26,16 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - Setting name. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get specific setting of MySQL Server - azure_rm_mysqlconfiguration_facts: + azure_rm_mysqlconfiguration_info: resource_group: myResourceGroup server_name: testmysqlserver name: deadlock_timeout - name: Get all settings of MySQL Server - azure_rm_mysqlconfiguration_facts: + azure_rm_mysqlconfiguration_info: resource_group: myResourceGroup server_name: server_name ''' @@ -107,7 +110,7 @@ except ImportError: pass -class AzureRMMySqlConfigurationFacts(AzureRMModuleBase): +class AzureRMMySqlConfigurationInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -129,9 +132,13 @@ class AzureRMMySqlConfigurationFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMySqlConfigurationFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMySqlConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlconfiguration_facts' module has been renamed to 'azure_rm_mysqlconfiguration_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(MySQLManagementClient, @@ -200,7 +207,7 @@ class AzureRMMySqlConfigurationFacts(AzureRMModuleBase): def main(): - AzureRMMySqlConfigurationFacts() + AzureRMMySqlConfigurationInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mysqldatabase_facts.py b/library/_azure_rm_mysqldatabase_facts.py similarity index 90% rename from library/azure_rm_mysqldatabase_facts.py rename to library/_azure_rm_mysqldatabase_facts.py index 5998fab..988a417 100644 --- a/library/azure_rm_mysqldatabase_facts.py +++ b/library/_azure_rm_mysqldatabase_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mysqldatabase_facts -version_added: "2.7" +module: azure_rm_mysqldatabase_info +version_added: "2.9" short_description: Get Azure MySQL Database facts description: - Get facts of MySQL Database. @@ -26,13 +26,16 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the database. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get instance of MySQL Database - azure_rm_mysqldatabase_facts: + azure_rm_mysqldatabase_info: resource_group: myResourceGroup server_name: server_name name: database_name - name: List instances of MySQL Database - azure_rm_mysqldatabase_facts: + azure_rm_mysqldatabase_info: resource_group: myResourceGroup server_name: server_name ''' @@ -112,7 +115,7 @@ except ImportError: pass -class AzureRMMySqlDatabaseFacts(AzureRMModuleBase): +class AzureRMMySqlDatabaseInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -135,9 +138,13 @@ class AzureRMMySqlDatabaseFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMySqlDatabaseFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMySqlDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqldatabase_facts' module has been renamed to 'azure_rm_mysqldatabase_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -195,7 +202,7 @@ class AzureRMMySqlDatabaseFacts(AzureRMModuleBase): def main(): - AzureRMMySqlDatabaseFacts() + AzureRMMySqlDatabaseInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mysqlfirewallrule_facts.py b/library/_azure_rm_mysqlfirewallrule_facts.py similarity index 89% rename from library/azure_rm_mysqlfirewallrule_facts.py rename to library/_azure_rm_mysqlfirewallrule_facts.py index e262d6d..9fa760e 100644 --- a/library/azure_rm_mysqlfirewallrule_facts.py +++ b/library/_azure_rm_mysqlfirewallrule_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mysqlfirewallrule_facts -version_added: "2.8" +module: azure_rm_mysqlfirewallrule_info +version_added: "2.9" short_description: Get Azure MySQL Firewall Rule facts description: - Get facts of Azure MySQL Firewall Rule. @@ -26,13 +26,16 @@ options: description: - The name of the resource group. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the server firewall rule. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get instance of MySQL Firewall Rule - azure_rm_mysqlfirewallrule_facts: + azure_rm_mysqlfirewallrule_info: resource_group: myResourceGroup server_name: server_name name: firewall_rule_name - name: List instances of MySQL Firewall Rule - azure_rm_mysqlfirewallrule_facts: + azure_rm_mysqlfirewallrule_info: resource_group: myResourceGroup server_name: server_name ''' @@ -107,7 +110,7 @@ except ImportError: pass -class AzureRMMySqlFirewallRuleFacts(AzureRMModuleBase): +class AzureRMMySqlFirewallRuleInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -131,9 +134,13 @@ class AzureRMMySqlFirewallRuleFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMMySqlFirewallRuleFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMySqlFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlfirewallrule_facts' module has been renamed to 'azure_rm_mysqlfirewallrule_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(MySQLManagementClient, @@ -191,7 +198,7 @@ class AzureRMMySqlFirewallRuleFacts(AzureRMModuleBase): def main(): - AzureRMMySqlFirewallRuleFacts() + AzureRMMySqlFirewallRuleInfo() if __name__ == '__main__': diff --git a/library/azure_rm_mysqlserver_facts.py b/library/_azure_rm_mysqlserver_facts.py similarity index 92% rename from library/azure_rm_mysqlserver_facts.py rename to library/_azure_rm_mysqlserver_facts.py index f0f2104..3cae238 100644 --- a/library/azure_rm_mysqlserver_facts.py +++ b/library/_azure_rm_mysqlserver_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_mysqlserver_facts -version_added: "2.7" +module: azure_rm_mysqlserver_info +version_added: "2.9" short_description: Get Azure MySQL Server facts description: - Get facts of MySQL Server. @@ -26,12 +26,15 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str name: description: - The name of the server. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -43,12 +46,12 @@ author: EXAMPLES = ''' - name: Get instance of MySQL Server - azure_rm_mysqlserver_facts: + azure_rm_mysqlserver_info: resource_group: myResourceGroup name: server_name - name: List instances of MySQL Server - azure_rm_mysqlserver_facts: + azure_rm_mysqlserver_info: resource_group: myResourceGroup ''' @@ -161,7 +164,7 @@ except ImportError: pass -class AzureRMMySqlServerFacts(AzureRMModuleBase): +class AzureRMMySqlServerInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -183,9 +186,13 @@ class AzureRMMySqlServerFacts(AzureRMModuleBase): self.resource_group = None self.name = None self.tags = None - super(AzureRMMySqlServerFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMMySqlServerInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlserver_facts' module has been renamed to 'azure_rm_mysqlserver_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -248,7 +255,7 @@ class AzureRMMySqlServerFacts(AzureRMModuleBase): def main(): - AzureRMMySqlServerFacts() + AzureRMMySqlServerInfo() if __name__ == '__main__': diff --git a/library/azure_rm_networkinterface_facts.py b/library/_azure_rm_networkinterface_facts.py similarity index 92% rename from library/azure_rm_networkinterface_facts.py rename to library/_azure_rm_networkinterface_facts.py index 4003375..db7eded 100644 --- a/library/azure_rm_networkinterface_facts.py +++ b/library/_azure_rm_networkinterface_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_networkinterface_facts +module: azure_rm_networkinterface_info -version_added: "2.1" +version_added: "2.9" short_description: Get network interface facts @@ -47,16 +47,16 @@ author: EXAMPLES = ''' - name: Get facts for one network interface - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: myResourceGroup name: nic001 - name: Get network interfaces within a resource group - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: myResourceGroup - name: Get network interfaces by tag - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: myResourceGroup tags: - testing @@ -261,7 +261,7 @@ def nic_to_dict(nic): ) -class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): +class AzureRMNetworkInterfaceInfo(AzureRMModuleBase): def __init__(self): @@ -273,20 +273,24 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict(azure_networkinterfaces=[]) ) self.name = None self.resource_group = None self.tags = None - super(AzureRMNetworkInterfaceFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True - ) + super(AzureRMNetworkInterfaceInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True + ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_networkinterface_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_networkinterface_facts' module has been renamed to 'azure_rm_networkinterface_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -302,7 +306,10 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): else: results = self.list_all() - self.results['ansible_facts']['azure_networkinterfaces'] = self.serialize_nics(results) + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_networkinterfaces': self.serialize_nics(results) + } self.results['networkinterfaces'] = self.to_dict_list(results) return self.results @@ -340,7 +347,7 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): def main(): - AzureRMNetworkInterfaceFacts() + AzureRMNetworkInterfaceInfo() if __name__ == '__main__': diff --git a/library/azure_rm_postgresqlconfiguration_facts.py b/library/_azure_rm_postgresqlconfiguration_facts.py similarity index 89% rename from library/azure_rm_postgresqlconfiguration_facts.py rename to library/_azure_rm_postgresqlconfiguration_facts.py index 7a37ff4..3b45737 100644 --- a/library/azure_rm_postgresqlconfiguration_facts.py +++ b/library/_azure_rm_postgresqlconfiguration_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_postgresqlconfiguration_facts -version_added: "2.8" +module: azure_rm_postgresqlconfiguration_info +version_added: "2.9" short_description: Get Azure PostgreSQL Configuration facts description: - Get facts of Azure PostgreSQL Configuration. @@ -26,13 +26,16 @@ options: description: - The name of the resource group that contains the resource. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - Setting name. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get specific setting of PostgreSQL configuration - azure_rm_postgresqlconfiguration_facts: + azure_rm_postgresqlconfiguration_info: resource_group: myResourceGroup server_name: testpostgresqlserver name: deadlock_timeout - name: Get all settings of PostgreSQL Configuration - azure_rm_postgresqlconfiguration_facts: + azure_rm_postgresqlconfiguration_info: resource_group: myResourceGroup server_name: testpostgresqlserver ''' @@ -107,7 +110,7 @@ except ImportError: pass -class AzureRMPostgreSQLConfigurationFacts(AzureRMModuleBase): +class AzureRMPostgreSQLConfigurationInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -131,9 +134,14 @@ class AzureRMPostgreSQLConfigurationFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMPostgreSQLConfigurationFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMPostgreSQLConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlconfiguration_facts' module has been renamed to 'azure_rm_postgresqlconfiguration_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(PostgreSQLManagementClient, @@ -202,7 +210,7 @@ class AzureRMPostgreSQLConfigurationFacts(AzureRMModuleBase): def main(): - AzureRMPostgreSQLConfigurationFacts() + AzureRMPostgreSQLConfigurationInfo() if __name__ == '__main__': diff --git a/library/azure_rm_postgresqldatabase_facts.py b/library/_azure_rm_postgresqldatabase_facts.py similarity index 89% rename from library/azure_rm_postgresqldatabase_facts.py rename to library/_azure_rm_postgresqldatabase_facts.py index e22e713..115b8fa 100644 --- a/library/azure_rm_postgresqldatabase_facts.py +++ b/library/_azure_rm_postgresqldatabase_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_postgresqldatabase_facts -version_added: "2.7" +module: azure_rm_postgresqldatabase_info +version_added: "2.9" short_description: Get Azure PostgreSQL Database facts description: - Get facts of PostgreSQL Database. @@ -26,13 +26,16 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the database. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get instance of PostgreSQL Database - azure_rm_postgresqldatabase_facts: + azure_rm_postgresqldatabase_info: resource_group: myResourceGroup server_name: server_name name: database_name - name: List instances of PostgreSQL Database - azure_rm_postgresqldatabase_facts: + azure_rm_postgresqldatabase_info: resource_group: myResourceGroup server_name: server_name ''' @@ -112,7 +115,7 @@ except ImportError: pass -class AzureRMPostgreSqlDatabasesFacts(AzureRMModuleBase): +class AzureRMPostgreSqlDatabasesInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -135,9 +138,13 @@ class AzureRMPostgreSqlDatabasesFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMPostgreSqlDatabasesFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMPostgreSqlDatabasesInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqldatabase_facts' module has been renamed to 'azure_rm_postgresqldatabase_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -195,7 +202,7 @@ class AzureRMPostgreSqlDatabasesFacts(AzureRMModuleBase): def main(): - AzureRMPostgreSqlDatabasesFacts() + AzureRMPostgreSqlDatabasesInfo() if __name__ == '__main__': diff --git a/library/azure_rm_postgresqlfirewallrule_facts.py b/library/_azure_rm_postgresqlfirewallrule_facts.py similarity index 88% rename from library/azure_rm_postgresqlfirewallrule_facts.py rename to library/_azure_rm_postgresqlfirewallrule_facts.py index 452236a..dae3140 100644 --- a/library/azure_rm_postgresqlfirewallrule_facts.py +++ b/library/_azure_rm_postgresqlfirewallrule_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_postgresqlfirewallrule_facts -version_added: "2.8" +module: azure_rm_postgresqlfirewallrule_info +version_added: "2.9" short_description: Get Azure PostgreSQL Firewall Rule facts description: - Get facts of Azure PostgreSQL Firewall Rule. @@ -26,13 +26,16 @@ options: description: - The name of the resource group. required: True + type: str server_name: description: - The name of the server. required: True + type: str name: description: - The name of the server firewall rule. + type: str extends_documentation_fragment: - azure @@ -44,13 +47,13 @@ author: EXAMPLES = ''' - name: Get instance of PostgreSQL Firewall Rule - azure_rm_postgresqlfirewallrule_facts: + azure_rm_postgresqlfirewallrule_info: resource_group: myResourceGroup server_name: server_name name: firewall_rule_name - name: List instances of PostgreSQL Firewall Rule - azure_rm_postgresqlfirewallrule_facts: + azure_rm_postgresqlfirewallrule_info: resource_group: myResourceGroup server_name: server_name ''' @@ -106,7 +109,7 @@ except ImportError: pass -class AzureRMPostgreSQLFirewallRulesFacts(AzureRMModuleBase): +class AzureRMPostgreSQLFirewallRulesInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -130,9 +133,14 @@ class AzureRMPostgreSQLFirewallRulesFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMPostgreSQLFirewallRulesFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMPostgreSQLFirewallRulesInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlfirewallrule_facts' module has been renamed to 'azure_rm_postgresqlfirewallrule_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(PostgreSQLManagementClient, @@ -190,7 +198,7 @@ class AzureRMPostgreSQLFirewallRulesFacts(AzureRMModuleBase): def main(): - AzureRMPostgreSQLFirewallRulesFacts() + AzureRMPostgreSQLFirewallRulesInfo() if __name__ == '__main__': diff --git a/library/azure_rm_postgresqlserver_facts.py b/library/_azure_rm_postgresqlserver_facts.py similarity index 92% rename from library/azure_rm_postgresqlserver_facts.py rename to library/_azure_rm_postgresqlserver_facts.py index 7e6cfde..b19d649 100644 --- a/library/azure_rm_postgresqlserver_facts.py +++ b/library/_azure_rm_postgresqlserver_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_postgresqlserver_facts -version_added: "2.7" +module: azure_rm_postgresqlserver_info +version_added: "2.9" short_description: Get Azure PostgreSQL Server facts description: - Get facts of PostgreSQL Server. @@ -26,12 +26,15 @@ options: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True + type: str name: description: - The name of the server. + type: str tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list extends_documentation_fragment: - azure @@ -43,12 +46,12 @@ author: EXAMPLES = ''' - name: Get instance of PostgreSQL Server - azure_rm_postgresqlserver_facts: + azure_rm_postgresqlserver_info: resource_group: myResourceGroup name: server_name - name: List instances of PostgreSQL Server - azure_rm_postgresqlserver_facts: + azure_rm_postgresqlserver_info: resource_group: myResourceGroup ''' @@ -162,7 +165,7 @@ except ImportError: pass -class AzureRMPostgreSqlServersFacts(AzureRMModuleBase): +class AzureRMPostgreSqlServersInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -184,9 +187,13 @@ class AzureRMPostgreSqlServersFacts(AzureRMModuleBase): self.resource_group = None self.name = None self.tags = None - super(AzureRMPostgreSqlServersFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMPostgreSqlServersInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlserver_facts' module has been renamed to 'azure_rm_postgresqlserver_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -249,7 +256,7 @@ class AzureRMPostgreSqlServersFacts(AzureRMModuleBase): def main(): - AzureRMPostgreSqlServersFacts() + AzureRMPostgreSqlServersInfo() if __name__ == '__main__': diff --git a/library/azure_rm_publicipaddress_facts.py b/library/_azure_rm_publicipaddress_facts.py similarity index 92% rename from library/azure_rm_publicipaddress_facts.py rename to library/_azure_rm_publicipaddress_facts.py index 2b14fff..0be71fe 100644 --- a/library/azure_rm_publicipaddress_facts.py +++ b/library/_azure_rm_publicipaddress_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_publicipaddress_facts +module: azure_rm_publicipaddress_info -version_added: "2.1" +version_added: "2.9" short_description: Get public IP facts @@ -46,12 +46,12 @@ author: EXAMPLES = ''' - name: Get facts for one Public IP - azure_rm_publicipaddress_facts: + azure_rm_publicipaddress_info: resource_group: myResourceGroup name: publicip001 - name: Get facts for all Public IPs within a resource groups - azure_rm_publicipaddress_facts: + azure_rm_publicipaddress_info: resource_group: myResourceGroup ''' @@ -195,7 +195,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'PublicIp' -class AzureRMPublicIPFacts(AzureRMModuleBase): +class AzureRMPublicIPInfo(AzureRMModuleBase): def __init__(self): @@ -207,18 +207,20 @@ class AzureRMPublicIPFacts(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict(azure_publicipaddresses=[]) ) self.name = None self.resource_group = None self.tags = None - super(AzureRMPublicIPFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMPublicIPInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_publicipaddress_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_publicipaddress_facts' module has been renamed to 'azure_rm_publicipaddress_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -236,7 +238,10 @@ class AzureRMPublicIPFacts(AzureRMModuleBase): raw = self.filter(result) - self.results['ansible_facts']['azure_publicipaddresses'] = self.serialize(raw) + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_publicipaddresses': self.serialize(raw), + } self.results['publicipaddresses'] = self.format(raw) return self.results @@ -309,7 +314,7 @@ class AzureRMPublicIPFacts(AzureRMModuleBase): def main(): - AzureRMPublicIPFacts() + AzureRMPublicIPInfo() if __name__ == '__main__': diff --git a/library/azure_rm_rediscache_facts.py b/library/_azure_rm_rediscache_facts.py similarity index 95% rename from library/azure_rm_rediscache_facts.py rename to library/_azure_rm_rediscache_facts.py index fbfa179..d238e48 100644 --- a/library/azure_rm_rediscache_facts.py +++ b/library/_azure_rm_rediscache_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_rediscache_facts +module: azure_rm_rediscache_info -version_added: "2.8" +version_added: "2.9" short_description: Get Azure Cache for Redis instance facts @@ -49,18 +49,18 @@ author: EXAMPLES = ''' - name: Get Azure Cache for Redis by name - azure_rm_rediscache_facts: + azure_rm_rediscache_info: resource_group: myResourceGroup name: myRedis - name: Get Azure Cache for Redis with access keys by name - azure_rm_rediscache_facts: + azure_rm_rediscache_info: resource_group: myResourceGroup name: myRedis return_access_keys: true - name: Get Azure Cache for Redis in specific resource group - azure_rm_rediscache_facts: + azure_rm_rediscache_info: resource_group: myResourceGroup ''' @@ -202,7 +202,7 @@ except ImportError: import re -class AzureRMRedisCacheFacts(AzureRMModuleBase): +class AzureRMRedisCacheInfo(AzureRMModuleBase): """Utility class to get Azure Cache for Redis facts""" def __init__(self): @@ -232,13 +232,16 @@ class AzureRMRedisCacheFacts(AzureRMModuleBase): self._client = None - super(AzureRMRedisCacheFacts, self).__init__( + super(AzureRMRedisCacheInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_rediscache_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_rediscache_facts' module has been renamed to 'azure_rm_rediscache_info'", version='2.13') for key in self.module_args: setattr(self, key, kwargs[key]) @@ -344,7 +347,7 @@ class AzureRMRedisCacheFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMRedisCacheFacts() + AzureRMRedisCacheInfo() if __name__ == '__main__': diff --git a/library/azure_rm_resource_facts.py b/library/_azure_rm_resource_facts.py similarity index 97% rename from library/azure_rm_resource_facts.py rename to library/_azure_rm_resource_facts.py index ed52666..44c6f21 100644 --- a/library/azure_rm_resource_facts.py +++ b/library/_azure_rm_resource_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_resource_facts -version_added: "2.6" +module: azure_rm_resource_info +version_added: "2.9" short_description: Generic facts of Azure resources description: - Obtain facts of any resource using Azure REST API. @@ -67,7 +67,7 @@ author: EXAMPLES = ''' - name: Get scaleset info - azure_rm_resource_facts: + azure_rm_resource_info: resource_group: myResourceGroup provider: compute resource_type: virtualmachinescalesets @@ -75,7 +75,7 @@ EXAMPLES = ''' api_version: "2017-12-01" - name: Query all the resources in the resource group - azure_rm_resource_facts: + azure_rm_resource_info: resource_group: "{{ resource_group }}" resource_type: resources ''' @@ -292,7 +292,7 @@ except ImportError: pass -class AzureRMResourceFacts(AzureRMModuleBase): +class AzureRMResourceInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -331,9 +331,13 @@ class AzureRMResourceFacts(AzureRMModuleBase): self.resource_type = None self.resource_name = None self.subresource = [] - super(AzureRMResourceFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMResourceInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_resource_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_resource_facts' module has been renamed to 'azure_rm_resource_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient, @@ -420,7 +424,7 @@ class AzureRMResourceFacts(AzureRMModuleBase): def main(): - AzureRMResourceFacts() + AzureRMResourceInfo() if __name__ == '__main__': diff --git a/library/azure_rm_roleassignment_facts.py b/library/_azure_rm_roleassignment_facts.py similarity index 91% rename from library/azure_rm_roleassignment_facts.py rename to library/_azure_rm_roleassignment_facts.py index 813c1d9..e12b0c2 100644 --- a/library/azure_rm_roleassignment_facts.py +++ b/library/_azure_rm_roleassignment_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_roleassignment_facts -version_added: "2.8" +module: azure_rm_roleassignment_info +version_added: "2.9" short_description: Gets Azure Role Assignment facts description: - Gets facts of Azure Role Assignment. @@ -50,11 +50,11 @@ author: EXAMPLES = ''' - name: Get role assignments for specific service principal - azure_rm_roleassignment_facts: + azure_rm_roleassignment_info: assignee: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - name: Get role assignments for specific scope - azure_rm_roleassignment_facts: + azure_rm_roleassignment_info: scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ''' @@ -127,7 +127,7 @@ def roleassignment_to_dict(assignment): ) -class AzureRMRoleAssignmentFacts(AzureRMModuleBase): +class AzureRMRoleAssignmentInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( @@ -158,12 +158,15 @@ class AzureRMRoleAssignmentFacts(AzureRMModuleBase): mutually_exclusive = [['name', 'assignee']] - super(AzureRMRoleAssignmentFacts, self).__init__(derived_arg_spec=self.module_arg_spec, - supports_tags=False, - mutually_exclusive=mutually_exclusive) + super(AzureRMRoleAssignmentInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False, + mutually_exclusive=mutually_exclusive) def exec_module(self, **kwargs): """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_roleassignment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_roleassignment_facts' module has been renamed to 'azure_rm_roleassignment_info'", version='2.13') for key in list(self.module_arg_spec.keys()): if hasattr(self, key): @@ -270,7 +273,7 @@ class AzureRMRoleAssignmentFacts(AzureRMModuleBase): def main(): """Main execution""" - AzureRMRoleAssignmentFacts() + AzureRMRoleAssignmentInfo() if __name__ == '__main__': diff --git a/library/azure_rm_roledefinition_facts.py b/library/_azure_rm_roledefinition_facts.py similarity index 93% rename from library/azure_rm_roledefinition_facts.py rename to library/_azure_rm_roledefinition_facts.py index 82499a8..e887732 100644 --- a/library/azure_rm_roledefinition_facts.py +++ b/library/_azure_rm_roledefinition_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_roledefinition_facts -version_added: "2.8" +module: azure_rm_roledefinition_info +version_added: "2.9" short_description: Get Azure Role Definition facts description: - Get facts of Azure Role Definition. @@ -49,11 +49,11 @@ author: EXAMPLES = ''' - name: List Role Definitions in scope - azure_rm_roledefinition_facts: + azure_rm_roledefinition_info: scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup - name: Get Role Definition by name - azure_rm_roledefinition_facts: + azure_rm_roledefinition_info: scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup name: myRoleDefinition ''' @@ -152,7 +152,7 @@ def roledefinition_to_dict(role): return result -class AzureRMRoleDefinitionFacts(AzureRMModuleBase): +class AzureRMRoleDefinitionInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( scope=dict( @@ -177,11 +177,14 @@ class AzureRMRoleDefinitionFacts(AzureRMModuleBase): self._client = None - super(AzureRMRoleDefinitionFacts, self).__init__(derived_arg_spec=self.module_arg_spec, - supports_tags=False) + super(AzureRMRoleDefinitionInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False) def exec_module(self, **kwargs): """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_roledefinition_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_roledefinition_facts' module has been renamed to 'azure_rm_roledefinition_info'", version='2.13') for key in list(self.module_arg_spec.keys()): if hasattr(self, key): @@ -300,7 +303,7 @@ class AzureRMRoleDefinitionFacts(AzureRMModuleBase): def main(): """Main execution""" - AzureRMRoleDefinitionFacts() + AzureRMRoleDefinitionInfo() if __name__ == '__main__': diff --git a/library/azure_rm_routetable_facts.py b/library/_azure_rm_routetable_facts.py similarity index 88% rename from library/azure_rm_routetable_facts.py rename to library/_azure_rm_routetable_facts.py index 59fda98..4ef342a 100644 --- a/library/azure_rm_routetable_facts.py +++ b/library/_azure_rm_routetable_facts.py @@ -15,9 +15,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_routetable_facts +module: azure_rm_routetable_info -version_added: "2.7" +version_added: "2.9" short_description: Get route table facts @@ -45,16 +45,16 @@ author: EXAMPLES = ''' - name: Get facts for one route table - azure_rm_routetable_facts: + azure_rm_routetable_info: name: Testing resource_group: myResourceGroup - name: Get facts for all route tables - azure_rm_routetable_facts: + azure_rm_routetable_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_routetable_facts: + azure_rm_routetable_info: tags: - testing - foo:bar @@ -143,7 +143,7 @@ def instance_to_dict(table): ) -class AzureRMRouteTableFacts(AzureRMModuleBase): +class AzureRMRouteTableInfo(AzureRMModuleBase): def __init__(self): @@ -162,11 +162,14 @@ class AzureRMRouteTableFacts(AzureRMModuleBase): self.resource_group = None self.tags = None - super(AzureRMRouteTableFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMRouteTableInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_routetable_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_routetable_facts' module has been renamed to 'azure_rm_routetable_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -209,7 +212,7 @@ class AzureRMRouteTableFacts(AzureRMModuleBase): def main(): - AzureRMRouteTableFacts() + AzureRMRouteTableInfo() if __name__ == '__main__': diff --git a/library/azure_rm_securitygroup_facts.py b/library/_azure_rm_securitygroup_facts.py similarity index 92% rename from library/azure_rm_securitygroup_facts.py rename to library/_azure_rm_securitygroup_facts.py index dc91236..dfb00bb 100644 --- a/library/azure_rm_securitygroup_facts.py +++ b/library/_azure_rm_securitygroup_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_securitygroup_facts +module: azure_rm_securitygroup_info -version_added: "2.1" +version_added: "2.9" short_description: Get security group facts @@ -48,18 +48,18 @@ author: EXAMPLES = ''' - name: Get facts for one security group - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: myResourceGroup name: secgroup001 - name: Get facts for all security groups - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: myResourceGroup ''' RETURN = ''' -azure_securitygroups: +securitygroups: description: - List containing security group dicts. returned: always @@ -235,7 +235,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'NetworkSecurityGroup' -class AzureRMSecurityGroupFacts(AzureRMModuleBase): +class AzureRMSecurityGroupInfo(AzureRMModuleBase): def __init__(self): @@ -247,25 +247,35 @@ class AzureRMSecurityGroupFacts(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict(azure_securitygroups=[]) ) self.name = None self.resource_group = None self.tags = None - super(AzureRMSecurityGroupFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMSecurityGroupInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_securitygroup_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_securitygroup_facts' module has been renamed to 'azure_rm_securitygroup_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) if self.name is not None: - self.results['ansible_facts']['azure_securitygroups'] = self.get_item() + info = self.get_item() else: - self.results['ansible_facts']['azure_securitygroups'] = self.list_items() + info = self.list_items() + + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_securitygroups': info + } + self.results['securitygroups'] = info return self.results @@ -303,7 +313,7 @@ class AzureRMSecurityGroupFacts(AzureRMModuleBase): def main(): - AzureRMSecurityGroupFacts() + AzureRMSecurityGroupInfo() if __name__ == '__main__': diff --git a/library/azure_rm_servicebus_facts.py b/library/_azure_rm_servicebus_facts.py similarity index 96% rename from library/azure_rm_servicebus_facts.py rename to library/_azure_rm_servicebus_facts.py index 7fc57a9..672edfc 100644 --- a/library/azure_rm_servicebus_facts.py +++ b/library/_azure_rm_servicebus_facts.py @@ -15,9 +15,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_servicebus_facts +module: azure_rm_servicebus_info -version_added: "2.8" +version_added: "2.9" short_description: Get servicebus facts @@ -68,18 +68,18 @@ author: EXAMPLES = ''' - name: Get all namespaces under a resource group - azure_rm_servicebus_facts: + azure_rm_servicebus_info: resource_group: myResourceGroup type: namespace - name: Get all topics under a namespace - azure_rm_servicebus_facts: + azure_rm_servicebus_info: resource_group: myResourceGroup namespace: bar type: topic - name: Get a single queue with SAS policies - azure_rm_servicebus_facts: + azure_rm_servicebus_info: resource_group: myResourceGroup namespace: bar type: queue @@ -87,7 +87,7 @@ EXAMPLES = ''' show_sas_policies: true - name: Get all subscriptions under a resource group - azure_rm_servicebus_facts: + azure_rm_servicebus_info: resource_group: myResourceGroup type: subscription namespace: bar @@ -402,7 +402,7 @@ def is_valid_timedelta(value): return value -class AzureRMServiceBusFacts(AzureRMModuleBase): +class AzureRMServiceBusInfo(AzureRMModuleBase): def __init__(self): @@ -435,12 +435,15 @@ class AzureRMServiceBusFacts(AzureRMModuleBase): self.topic = None self.show_sas_policies = None - super(AzureRMServiceBusFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - required_if=required_if, - facts_module=True) + super(AzureRMServiceBusInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + required_if=required_if, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_servicebus_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_servicebus_facts' module has been renamed to 'azure_rm_servicebus_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -574,7 +577,7 @@ class AzureRMServiceBusFacts(AzureRMModuleBase): def main(): - AzureRMServiceBusFacts() + AzureRMServiceBusInfo() if __name__ == '__main__': diff --git a/library/azure_rm_sqldatabase_facts.py b/library/_azure_rm_sqldatabase_facts.py similarity index 94% rename from library/azure_rm_sqldatabase_facts.py rename to library/_azure_rm_sqldatabase_facts.py index a7bfc07..e0535b8 100644 --- a/library/azure_rm_sqldatabase_facts.py +++ b/library/_azure_rm_sqldatabase_facts.py @@ -15,7 +15,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_sqldatabase_facts +module: azure_rm_sqldatabase_info version_added: "2.8" short_description: Get Azure SQL Database facts description: @@ -50,19 +50,19 @@ author: EXAMPLES = ''' - name: Get instance of SQL Database - azure_rm_sqldatabase_facts: + azure_rm_sqldatabase_info: resource_group: testrg server_name: testserver name: testdb - name: List instances of SQL Database - azure_rm_sqldatabase_facts: + azure_rm_sqldatabase_info: resource_group: testrg server_name: testserver elastic_pool_name: testep - name: List instances of SQL Database - azure_rm_sqldatabase_facts: + azure_rm_sqldatabase_info: resource_group: testrg server_name: testserver ''' @@ -159,7 +159,7 @@ except ImportError: pass -class AzureRMSqlDatabaseFacts(AzureRMModuleBase): +class AzureRMSqlDatabaseInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -190,9 +190,13 @@ class AzureRMSqlDatabaseFacts(AzureRMModuleBase): self.name = None self.elastic_pool_name = None self.tags = None - super(AzureRMSqlDatabaseFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMSqlDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqldatabase_facts' module has been renamed to 'azure_rm_sqldatabase_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -277,7 +281,7 @@ class AzureRMSqlDatabaseFacts(AzureRMModuleBase): def main(): - AzureRMSqlDatabaseFacts() + AzureRMSqlDatabaseInfo() if __name__ == '__main__': diff --git a/library/azure_rm_sqlfirewallrule_facts.py b/library/_azure_rm_sqlfirewallrule_facts.py similarity index 91% rename from library/azure_rm_sqlfirewallrule_facts.py rename to library/_azure_rm_sqlfirewallrule_facts.py index d669af3..8885820 100644 --- a/library/azure_rm_sqlfirewallrule_facts.py +++ b/library/_azure_rm_sqlfirewallrule_facts.py @@ -15,7 +15,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_sqlfirewallrule_facts +module: azure_rm_sqlfirewallrule_info version_added: "2.8" short_description: Get Azure SQL Firewall Rule facts description: @@ -44,13 +44,13 @@ author: EXAMPLES = ''' - name: Get instance of SQL Firewall Rule - azure_rm_sqlfirewallrule_facts: + azure_rm_sqlfirewallrule_info: resource_group: myResourceGroup server_name: testserver name: testrule - name: List instances of SQL Firewall Rule - azure_rm_sqlfirewallrule_facts: + azure_rm_sqlfirewallrule_info: resource_group: myResourceGroup server_name: testserver ''' @@ -113,7 +113,7 @@ except ImportError: pass -class AzureRMSqlFirewallRuleFacts(AzureRMModuleBase): +class AzureRMSqlFirewallRuleInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -136,9 +136,13 @@ class AzureRMSqlFirewallRuleFacts(AzureRMModuleBase): self.resource_group = None self.server_name = None self.name = None - super(AzureRMSqlFirewallRuleFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMSqlFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqlfirewallrule_facts' module has been renamed to 'azure_rm_sqlfirewallrule_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -204,7 +208,7 @@ class AzureRMSqlFirewallRuleFacts(AzureRMModuleBase): def main(): - AzureRMSqlFirewallRuleFacts() + AzureRMSqlFirewallRuleInfo() if __name__ == '__main__': diff --git a/library/azure_rm_sqlserver_facts.py b/library/_azure_rm_sqlserver_facts.py similarity index 92% rename from library/azure_rm_sqlserver_facts.py rename to library/_azure_rm_sqlserver_facts.py index eb9c90d..bae4ab8 100644 --- a/library/azure_rm_sqlserver_facts.py +++ b/library/_azure_rm_sqlserver_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_sqlserver_facts -version_added: "2.5" +module: azure_rm_sqlserver_info +version_added: "2.9" short_description: Get SQL Server facts description: - Get facts of SQL Server. @@ -41,12 +41,12 @@ author: EXAMPLES = ''' - name: Get instance of SQL Server - azure_rm_sqlserver_facts: + azure_rm_sqlserver_info: resource_group: myResourceGroup server_name: server_name - name: List instances of SQL Server - azure_rm_sqlserver_facts: + azure_rm_sqlserver_info: resource_group: myResourceGroup ''' @@ -123,7 +123,7 @@ except ImportError: pass -class AzureRMSqlServerFacts(AzureRMModuleBase): +class AzureRMSqlServerInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -142,9 +142,13 @@ class AzureRMSqlServerFacts(AzureRMModuleBase): ) self.resource_group = None self.server_name = None - super(AzureRMSqlServerFacts, self).__init__(self.module_arg_spec) + super(AzureRMSqlServerInfo, self).__init__(self.module_arg_spec) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqlserver_facts' module has been renamed to 'azure_rm_sqlserver_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -197,7 +201,7 @@ class AzureRMSqlServerFacts(AzureRMModuleBase): def main(): - AzureRMSqlServerFacts() + AzureRMSqlServerInfo() if __name__ == '__main__': diff --git a/library/azure_rm_storageaccount_facts.py b/library/_azure_rm_storageaccount_facts.py similarity index 95% rename from library/azure_rm_storageaccount_facts.py rename to library/_azure_rm_storageaccount_facts.py index 7c52ef7..82906c9 100644 --- a/library/azure_rm_storageaccount_facts.py +++ b/library/_azure_rm_storageaccount_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_storageaccount_facts +module: azure_rm_storageaccount_info -version_added: "2.1" +version_added: "2.9" short_description: Get storage account facts @@ -62,16 +62,16 @@ author: EXAMPLES = ''' - name: Get facts for one account - azure_rm_storageaccount_facts: + azure_rm_storageaccount_info: resource_group: myResourceGroup name: clh0002 - name: Get facts for all accounts in a resource group - azure_rm_storageaccount_facts: + azure_rm_storageaccount_info: resource_group: myResourceGroup - name: Get facts for all accounts by tags - azure_rm_storageaccount_facts: + azure_rm_storageaccount_info: tags: - testing - foo:bar @@ -358,7 +358,7 @@ from ansible.module_utils._text import to_native AZURE_OBJECT_CLASS = 'StorageAccount' -class AzureRMStorageAccountFacts(AzureRMModuleBase): +class AzureRMStorageAccountInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( @@ -381,11 +381,14 @@ class AzureRMStorageAccountFacts(AzureRMModuleBase): self.show_connection_string = None self.show_blob_cors = None - super(AzureRMStorageAccountFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMStorageAccountInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_storageaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_storageaccount_facts' module has been renamed to 'azure_rm_storageaccount_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -403,8 +406,10 @@ class AzureRMStorageAccountFacts(AzureRMModuleBase): filtered = self.filter_tag(results) - self.results['ansible_facts']['azure_storageaccounts'] = self.serialize(filtered) - self.results['ansible_facts']['storageaccounts'] = self.format_to_dict(filtered) + if is_old_facts: + self.results['ansible_facts']['azure_storageaccounts'] = self.serialize(filtered) + self.results['ansible_facts']['storageaccounts'] = self.format_to_dict(filtered) + self.results['storageaccounts'] = self.format_to_dict(filtered) return self.results def get_account(self): @@ -544,7 +549,7 @@ class AzureRMStorageAccountFacts(AzureRMModuleBase): def main(): - AzureRMStorageAccountFacts() + AzureRMStorageAccountInfo() if __name__ == '__main__': diff --git a/library/azure_rm_subnet_facts.py b/library/_azure_rm_subnet_facts.py similarity index 93% rename from library/azure_rm_subnet_facts.py rename to library/_azure_rm_subnet_facts.py index fd9cd85..697f7a0 100644 --- a/library/azure_rm_subnet_facts.py +++ b/library/_azure_rm_subnet_facts.py @@ -15,7 +15,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_subnet_facts +module: azure_rm_subnet_info version_added: "2.8" short_description: Get Azure Subnet facts description: @@ -44,13 +44,13 @@ author: EXAMPLES = ''' - name: Get facts of specific subnet - azure_rm_subnet_facts: + azure_rm_subnet_info: resource_group: myResourceGroup virtual_network_name: myVirtualNetwork name: mySubnet - name: List facts for all subnets in virtual network - azure_rm_subnet_facts: + azure_rm_subnet_info: resource_group: myResourceGroup virtual_network_name: myVirtualNetwork name: mySubnet @@ -151,7 +151,7 @@ except ImportError: pass -class AzureRMSubnetFacts(AzureRMModuleBase): +class AzureRMSubnetInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -174,9 +174,13 @@ class AzureRMSubnetFacts(AzureRMModuleBase): self.resource_group = None self.virtual_network_name = None self.name = None - super(AzureRMSubnetFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMSubnetInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_subnet_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_subnet_facts' module has been renamed to 'azure_rm_subnet_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -236,7 +240,7 @@ class AzureRMSubnetFacts(AzureRMModuleBase): def main(): - AzureRMSubnetFacts() + AzureRMSubnetInfo() if __name__ == '__main__': diff --git a/library/azure_rm_trafficmanagerendpoint_facts.py b/library/_azure_rm_trafficmanagerendpoint_facts.py similarity index 93% rename from library/azure_rm_trafficmanagerendpoint_facts.py rename to library/_azure_rm_trafficmanagerendpoint_facts.py index 2a4b6a8..f2a565c 100644 --- a/library/azure_rm_trafficmanagerendpoint_facts.py +++ b/library/_azure_rm_trafficmanagerendpoint_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_trafficmanagerendpoint_facts +module: azure_rm_trafficmanagerendpoint_info -version_added: "2.7" +version_added: "2.9" short_description: Get Azure Traffic Manager endpoint facts @@ -53,12 +53,12 @@ author: EXAMPLES = ''' - name: Get endpoints facts of a Traffic Manager profile - azure_rm_trafficmanagerendpoint_facts: + azure_rm_trafficmanagerendpoint_info: resource_group: myResourceGroup profile_name: Testing - name: Get specific endpoint of a Traffic Manager profile - azure_rm_trafficmanager_facts: + azure_rm_trafficmanager_info: resource_group: myResourceGroup profile_name: Testing name: test_external_endpoint @@ -185,7 +185,7 @@ def serialize_endpoint(endpoint, resource_group): return result -class AzureRMTrafficManagerEndpointFacts(AzureRMModuleBase): +class AzureRMTrafficManagerEndpointInfo(AzureRMModuleBase): """Utility class to get Azure Traffic Manager Endpoint facts""" def __init__(self): @@ -217,13 +217,17 @@ class AzureRMTrafficManagerEndpointFacts(AzureRMModuleBase): self.resource_group = None self.type = None - super(AzureRMTrafficManagerEndpointFacts, self).__init__( + super(AzureRMTrafficManagerEndpointInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_trafficmanagerendpoint_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_trafficmanagerendpoint_facts' module has been renamed to 'azure_rm_trafficmanagerendpoint_info'", + version='2.13') for key in self.module_args: setattr(self, key, kwargs[key]) @@ -300,7 +304,7 @@ class AzureRMTrafficManagerEndpointFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMTrafficManagerEndpointFacts() + AzureRMTrafficManagerEndpointInfo() if __name__ == '__main__': diff --git a/library/azure_rm_trafficmanagerprofile_facts.py b/library/_azure_rm_trafficmanagerprofile_facts.py similarity index 95% rename from library/azure_rm_trafficmanagerprofile_facts.py rename to library/_azure_rm_trafficmanagerprofile_facts.py index 8dfb747..2b6ed59 100644 --- a/library/azure_rm_trafficmanagerprofile_facts.py +++ b/library/_azure_rm_trafficmanagerprofile_facts.py @@ -14,9 +14,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_trafficmanagerprofile_facts +module: azure_rm_trafficmanagerprofile_info -version_added: "2.7" +version_added: "2.9" short_description: Get Azure Traffic Manager profile facts @@ -44,15 +44,15 @@ author: EXAMPLES = ''' - name: Get facts for one Traffic Manager profile - azure_rm_trafficmanager_facts: + azure_rm_trafficmanager_info: name: Testing resource_group: myResourceGroup - name: Get facts for all Traffic Manager profiles - azure_rm_trafficmanager_facts: + azure_rm_trafficmanager_info: - name: Get facts by tags - azure_rm_trafficmanager_facts: + azure_rm_trafficmanager_info: tags: - Environment:Test ''' @@ -280,7 +280,7 @@ def serialize_endpoint(endpoint): return result -class AzureRMTrafficManagerProfileFacts(AzureRMModuleBase): +class AzureRMTrafficManagerProfileInfo(AzureRMModuleBase): """Utility class to get Azure Traffic Manager profile facts""" def __init__(self): @@ -300,13 +300,16 @@ class AzureRMTrafficManagerProfileFacts(AzureRMModuleBase): self.resource_group = None self.tags = None - super(AzureRMTrafficManagerProfileFacts, self).__init__( + super(AzureRMTrafficManagerProfileInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_trafficmanagerprofile_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_trafficmanagerprofile_facts' module has been renamed to 'azure_rm_trafficmanagerprofile_info'", version='2.13') for key in self.module_args: setattr(self, key, kwargs[key]) @@ -412,7 +415,7 @@ class AzureRMTrafficManagerProfileFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMTrafficManagerProfileFacts() + AzureRMTrafficManagerProfileInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachine_facts.py b/library/_azure_rm_virtualmachine_facts.py similarity index 95% rename from library/azure_rm_virtualmachine_facts.py rename to library/_azure_rm_virtualmachine_facts.py index f308434..f6cb8ec 100644 --- a/library/azure_rm_virtualmachine_facts.py +++ b/library/_azure_rm_virtualmachine_facts.py @@ -17,9 +17,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachine_facts +module: azure_rm_virtualmachine_info -version_added: "2.7" +version_added: "2.9" short_description: Get virtual machine facts @@ -48,16 +48,16 @@ author: EXAMPLES = ''' - name: Get facts for all virtual machines of a resource group - azure_rm_virtualmachine_facts: + azure_rm_virtualmachine_info: resource_group: myResourceGroup - name: Get facts by name - azure_rm_virtualmachine_facts: + azure_rm_virtualmachine_info: resource_group: myResourceGroup name: myVm - name: Get facts by tags - azure_rm_virtualmachine_facts: + azure_rm_virtualmachine_info: resource_group: myResourceGroup tags: - testing @@ -264,7 +264,7 @@ AZURE_OBJECT_CLASS = 'VirtualMachine' AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] -class AzureRMVirtualMachineFacts(AzureRMModuleBase): +class AzureRMVirtualMachineInfo(AzureRMModuleBase): def __init__(self): @@ -283,11 +283,14 @@ class AzureRMVirtualMachineFacts(AzureRMModuleBase): self.name = None self.tags = None - super(AzureRMVirtualMachineFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMVirtualMachineInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachine_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachine_facts' module has been renamed to 'azure_rm_virtualmachine_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -446,7 +449,7 @@ class AzureRMVirtualMachineFacts(AzureRMModuleBase): def main(): - AzureRMVirtualMachineFacts() + AzureRMVirtualMachineInfo() if __name__ == '__main__': diff --git a/library/_azure_rm_virtualmachine_scaleset.py b/library/_azure_rm_virtualmachine_scaleset.py index 8e8596d..24396ec 100644 --- a/library/_azure_rm_virtualmachine_scaleset.py +++ b/library/_azure_rm_virtualmachine_scaleset.py @@ -890,7 +890,7 @@ class AzureRMVirtualMachineScaleSet(AzureRMModuleBase): create_option=self.compute_models.DiskCreateOptionTypes.empty, disk_size_gb=data_disk['disk_size_gb'], managed_disk=self.compute_models.VirtualMachineScaleSetManagedDiskParameters( - storage_account_type=data_disk['managed_disk_type'] + storage_account_type=data_disk.get('managed_disk_type', None) ), )) vmss_resource.virtual_machine_profile.storage_profile.data_disks = data_disks diff --git a/library/_azure_rm_virtualmachine_scaleset_facts.py b/library/_azure_rm_virtualmachine_scaleset_facts.py index 2830dff..849b35e 100644 --- a/library/_azure_rm_virtualmachine_scaleset_facts.py +++ b/library/_azure_rm_virtualmachine_scaleset_facts.py @@ -13,9 +13,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachinescaleset_facts +module: azure_rm_virtualmachinescaleset_info -version_added: "2.4" +version_added: "2.9" short_description: Get Virtual Machine Scale Set facts @@ -55,17 +55,17 @@ author: EXAMPLES = ''' - name: Get facts for a virtual machine scale set - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup name: testvmss001 format: curated - name: Get facts for all virtual networks - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup tags: - testing @@ -261,7 +261,7 @@ AZURE_OBJECT_CLASS = 'VirtualMachineScaleSet' AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] -class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): +class AzureRMVirtualMachineScaleSetInfo(AzureRMModuleBase): """Utility class to get virtual machine scale set facts""" def __init__(self): @@ -290,27 +290,34 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): self.format = None self.tags = None - super(AzureRMVirtualMachineScaleSetFacts, self).__init__( + super(AzureRMVirtualMachineScaleSetInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescaleset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescaleset_facts' module has been renamed to 'azure_rm_virtualmachinescaleset_info'", + version='2.13') for key in self.module_args: setattr(self, key, kwargs[key]) - if self.module._name == 'azure_rm_virtualmachine_scaleset_facts': - self.module.deprecate("The 'azure_rm_virtualmachine_scaleset_facts' module has been renamed to 'azure_rm_virtualmachinescaleset_facts'", - version='2.12') - if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") - if self.name: - self.results['ansible_facts']['azure_vmss'] = self.get_item() + + if is_old_facts: + if self.name: + self.results['ansible_facts']['azure_vmss'] = self.get_item() + else: + self.results['ansible_facts']['azure_vmss'] = self.list_items() else: - self.results['ansible_facts']['azure_vmss'] = self.list_items() + if self.name: + self.results['vmss'] = self.get_item() + else: + self.results['vmss'] = self.list_items() if self.format == 'curated': for index in range(len(self.results['ansible_facts']['azure_vmss'])): @@ -383,6 +390,8 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): # proper result format we want to support in the future # dropping 'ansible_facts' and shorter name 'vmss' self.results['vmss'] = self.results['ansible_facts']['azure_vmss'] + if not is_old_facts: + self.results.pop('ansible_facts', None) return self.results @@ -425,7 +434,7 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMVirtualMachineScaleSetFacts() + AzureRMVirtualMachineScaleSetInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachineextension_facts.py b/library/_azure_rm_virtualmachineextension_facts.py similarity index 91% rename from library/azure_rm_virtualmachineextension_facts.py rename to library/_azure_rm_virtualmachineextension_facts.py index 3d08ddf..de9d797 100644 --- a/library/azure_rm_virtualmachineextension_facts.py +++ b/library/_azure_rm_virtualmachineextension_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachineextension_facts -version_added: "2.8" +module: azure_rm_virtualmachineextension_info +version_added: "2.9" short_description: Get Azure Virtual Machine Extension facts description: - Get facts of Azure Virtual Machine Extension. @@ -47,13 +47,13 @@ author: EXAMPLES = ''' - name: Get information on specific Virtual Machine Extension - azure_rm_virtualmachineextension_facts: + azure_rm_virtualmachineextension_info: resource_group: myResourceGroup virtual_machine_name: myvm name: myextension - name: List installed Virtual Machine Extensions - azure_rm_virtualmachineextension_facts: + azure_rm_virtualmachineextension_info: resource_group: myResourceGroup virtual_machine_name: myvm ''' @@ -144,7 +144,7 @@ except ImportError: pass -class AzureRMVirtualMachineExtensionFacts(AzureRMModuleBase): +class AzureRMVirtualMachineExtensionInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -171,9 +171,14 @@ class AzureRMVirtualMachineExtensionFacts(AzureRMModuleBase): self.virtual_machine_name = None self.name = None self.tags = None - super(AzureRMVirtualMachineExtensionFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMVirtualMachineExtensionInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachineextension_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachineextension_facts' module has been renamed to 'azure_rm_virtualmachineextension_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -236,7 +241,7 @@ class AzureRMVirtualMachineExtensionFacts(AzureRMModuleBase): def main(): - AzureRMVirtualMachineExtensionFacts() + AzureRMVirtualMachineExtensionInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachineimage_facts.py b/library/_azure_rm_virtualmachineimage_facts.py similarity index 79% rename from library/azure_rm_virtualmachineimage_facts.py rename to library/_azure_rm_virtualmachineimage_facts.py index ddd7df7..c598432 100644 --- a/library/azure_rm_virtualmachineimage_facts.py +++ b/library/_azure_rm_virtualmachineimage_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachineimage_facts +module: azure_rm_virtualmachineimage_info -version_added: "2.1" +version_added: "2.9" short_description: Get virtual machine image facts @@ -55,7 +55,7 @@ author: EXAMPLES = ''' - name: Get facts for a specific image - azure_rm_virtualmachineimage_facts: + azure_rm_virtualmachineimage_info: location: eastus publisher: OpenLogic offer: CentOS @@ -63,19 +63,19 @@ EXAMPLES = ''' version: '7.1.20160308' - name: List available versions - azure_rm_virtualmachineimage_facts: + azure_rm_virtualmachineimage_info: location: eastus publisher: OpenLogic offer: CentOS sku: '7.1' - name: List available offers - azure_rm_virtualmachineimage_facts: + azure_rm_virtualmachineimage_info: location: eastus publisher: OpenLogic - name: List available publishers - azure_rm_virtualmachineimage_facts: + azure_rm_virtualmachineimage_info: location: eastus ''' @@ -125,7 +125,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] -class AzureRMVirtualMachineImageFacts(AzureRMModuleBase): +class AzureRMVirtualMachineImageInfo(AzureRMModuleBase): def __init__(self, **kwargs): @@ -148,21 +148,34 @@ class AzureRMVirtualMachineImageFacts(AzureRMModuleBase): self.sku = None self.version = None - super(AzureRMVirtualMachineImageFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMVirtualMachineImageInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachineimage_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachineimage_facts' module has been renamed to 'azure_rm_virtualmachineimage_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) - if self.location and self.publisher and self.offer and self.sku and self.version: - self.results['ansible_facts']['azure_vmimages'] = self.get_item() - elif self.location and self.publisher and self.offer and self.sku: - self.results['ansible_facts']['azure_vmimages'] = self.list_images() - elif self.location and self.publisher: - self.results['ansible_facts']['azure_vmimages'] = self.list_offers() - elif self.location: - self.results['ansible_facts']['azure_vmimages'] = self.list_publishers() + if is_old_facts: + if self.location and self.publisher and self.offer and self.sku and self.version: + self.results['ansible_facts']['azure_vmimages'] = self.get_item() + elif self.location and self.publisher and self.offer and self.sku: + self.results['ansible_facts']['azure_vmimages'] = self.list_images() + elif self.location and self.publisher: + self.results['ansible_facts']['azure_vmimages'] = self.list_offers() + elif self.location: + self.results['ansible_facts']['azure_vmimages'] = self.list_publishers() + else: + if self.location and self.publisher and self.offer and self.sku and self.version: + self.results['vmimages'] = self.get_item() + elif self.location and self.publisher and self.offer and self.sku: + self.results['vmimages'] = self.list_images() + elif self.location and self.publisher: + self.results['vmimages'] = self.list_offers() + elif self.location: + self.results['vmimages'] = self.list_publishers() return self.results @@ -238,7 +251,7 @@ class AzureRMVirtualMachineImageFacts(AzureRMModuleBase): def main(): - AzureRMVirtualMachineImageFacts() + AzureRMVirtualMachineImageInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachinescaleset_facts.py b/library/_azure_rm_virtualmachinescaleset_facts.py similarity index 92% rename from library/azure_rm_virtualmachinescaleset_facts.py rename to library/_azure_rm_virtualmachinescaleset_facts.py index 2830dff..849b35e 100644 --- a/library/azure_rm_virtualmachinescaleset_facts.py +++ b/library/_azure_rm_virtualmachinescaleset_facts.py @@ -13,9 +13,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachinescaleset_facts +module: azure_rm_virtualmachinescaleset_info -version_added: "2.4" +version_added: "2.9" short_description: Get Virtual Machine Scale Set facts @@ -55,17 +55,17 @@ author: EXAMPLES = ''' - name: Get facts for a virtual machine scale set - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup name: testvmss001 format: curated - name: Get facts for all virtual networks - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_virtualmachinescaleset_facts: + azure_rm_virtualmachinescaleset_info: resource_group: myResourceGroup tags: - testing @@ -261,7 +261,7 @@ AZURE_OBJECT_CLASS = 'VirtualMachineScaleSet' AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] -class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): +class AzureRMVirtualMachineScaleSetInfo(AzureRMModuleBase): """Utility class to get virtual machine scale set facts""" def __init__(self): @@ -290,27 +290,34 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): self.format = None self.tags = None - super(AzureRMVirtualMachineScaleSetFacts, self).__init__( + super(AzureRMVirtualMachineScaleSetInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescaleset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescaleset_facts' module has been renamed to 'azure_rm_virtualmachinescaleset_info'", + version='2.13') for key in self.module_args: setattr(self, key, kwargs[key]) - if self.module._name == 'azure_rm_virtualmachine_scaleset_facts': - self.module.deprecate("The 'azure_rm_virtualmachine_scaleset_facts' module has been renamed to 'azure_rm_virtualmachinescaleset_facts'", - version='2.12') - if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") - if self.name: - self.results['ansible_facts']['azure_vmss'] = self.get_item() + + if is_old_facts: + if self.name: + self.results['ansible_facts']['azure_vmss'] = self.get_item() + else: + self.results['ansible_facts']['azure_vmss'] = self.list_items() else: - self.results['ansible_facts']['azure_vmss'] = self.list_items() + if self.name: + self.results['vmss'] = self.get_item() + else: + self.results['vmss'] = self.list_items() if self.format == 'curated': for index in range(len(self.results['ansible_facts']['azure_vmss'])): @@ -383,6 +390,8 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): # proper result format we want to support in the future # dropping 'ansible_facts' and shorter name 'vmss' self.results['vmss'] = self.results['ansible_facts']['azure_vmss'] + if not is_old_facts: + self.results.pop('ansible_facts', None) return self.results @@ -425,7 +434,7 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase): def main(): """Main module execution code path""" - AzureRMVirtualMachineScaleSetFacts() + AzureRMVirtualMachineScaleSetInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachinescalesetextension_facts.py b/library/_azure_rm_virtualmachinescalesetextension_facts.py similarity index 89% rename from library/azure_rm_virtualmachinescalesetextension_facts.py rename to library/_azure_rm_virtualmachinescalesetextension_facts.py index ff9cc10..a5e11d1 100644 --- a/library/azure_rm_virtualmachinescalesetextension_facts.py +++ b/library/_azure_rm_virtualmachinescalesetextension_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachinescalesetextension_facts -version_added: "2.8" +module: azure_rm_virtualmachinescalesetextension_info +version_added: "2.9" short_description: Get Azure Virtual Machine Scale Set Extension facts description: - Get facts of Azure Virtual Machine Scale Set Extension. @@ -44,13 +44,13 @@ author: EXAMPLES = ''' - name: Get information on specific Virtual Machine Scale Set Extension - azure_rm_virtualmachineextension_facts: + azure_rm_virtualmachineextension_info: resource_group: myResourceGroup vmss_name: myvmss name: myextension - name: List installed Virtual Machine Scale Set Extensions - azure_rm_virtualmachineextension_facts: + azure_rm_virtualmachineextension_info: resource_group: myrg vmss_name: myvmss ''' @@ -129,7 +129,7 @@ except ImportError: pass -class AzureRMVirtualMachineScaleSetExtensionFacts(AzureRMModuleBase): +class AzureRMVirtualMachineScaleSetExtensionInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -152,9 +152,15 @@ class AzureRMVirtualMachineScaleSetExtensionFacts(AzureRMModuleBase): self.resource_group = None self.vmss_name = None self.name = None - super(AzureRMVirtualMachineScaleSetExtensionFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMVirtualMachineScaleSetExtensionInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescalesetextension_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescalesetextension_facts' module has been renamed to" + + " 'azure_rm_virtualmachinescalesetextension_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -215,7 +221,7 @@ class AzureRMVirtualMachineScaleSetExtensionFacts(AzureRMModuleBase): def main(): - AzureRMVirtualMachineScaleSetExtensionFacts() + AzureRMVirtualMachineScaleSetExtensionInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualmachinescalesetinstance_facts.py b/library/_azure_rm_virtualmachinescalesetinstance_facts.py similarity index 90% rename from library/azure_rm_virtualmachinescalesetinstance_facts.py rename to library/_azure_rm_virtualmachinescalesetinstance_facts.py index c6c310a..12a8e3e 100644 --- a/library/azure_rm_virtualmachinescalesetinstance_facts.py +++ b/library/_azure_rm_virtualmachinescalesetinstance_facts.py @@ -15,8 +15,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualmachinescalesetinstance_facts -version_added: "2.8" +module: azure_rm_virtualmachinescalesetinstance_info +version_added: "2.9" short_description: Get Azure Virtual Machine Scale Set Instance facts description: - Get facts of Azure Virtual Machine Scale Set VMs. @@ -47,7 +47,7 @@ author: EXAMPLES = ''' - name: List VM instances in Virtual Machine ScaleSet - azure_rm_computevirtualmachinescalesetinstance_facts: + azure_rm_computevirtualmachinescalesetinstance_info: resource_group: myResourceGroup vmss_name: myVMSS ''' @@ -121,7 +121,7 @@ except ImportError: pass -class AzureRMVirtualMachineScaleSetVMFacts(AzureRMModuleBase): +class AzureRMVirtualMachineScaleSetVMInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( @@ -149,9 +149,15 @@ class AzureRMVirtualMachineScaleSetVMFacts(AzureRMModuleBase): self.vmss_name = None self.instance_id = None self.tags = None - super(AzureRMVirtualMachineScaleSetVMFacts, self).__init__(self.module_arg_spec, supports_tags=False) + super(AzureRMVirtualMachineScaleSetVMInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescalesetinstance_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescalesetinstance_facts' module has been renamed to" + + " 'azure_rm_virtualmachinescalesetinstance_info'", + version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) self.mgmt_client = self.get_mgmt_svc_client(ComputeManagementClient, @@ -221,7 +227,7 @@ class AzureRMVirtualMachineScaleSetVMFacts(AzureRMModuleBase): def main(): - AzureRMVirtualMachineScaleSetVMFacts() + AzureRMVirtualMachineScaleSetVMInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualnetwork_facts.py b/library/_azure_rm_virtualnetwork_facts.py similarity index 92% rename from library/azure_rm_virtualnetwork_facts.py rename to library/_azure_rm_virtualnetwork_facts.py index 43af90a..5e785ff 100644 --- a/library/azure_rm_virtualnetwork_facts.py +++ b/library/_azure_rm_virtualnetwork_facts.py @@ -16,9 +16,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualnetwork_facts +module: azure_rm_virtualnetwork_info -version_added: "2.1" +version_added: "2.9" short_description: Get virtual network facts @@ -47,16 +47,16 @@ author: EXAMPLES = ''' - name: Get facts for one virtual network - azure_rm_virtualnetwork_facts: + azure_rm_virtualnetwork_info: resource_group: myResourceGroup name: secgroup001 - name: Get facts for all virtual networks - azure_rm_virtualnetwork_facts: + azure_rm_virtualnetwork_info: resource_group: myResourceGroup - name: Get facts by tags - azure_rm_virtualnetwork_facts: + azure_rm_virtualnetwork_info: tags: - testing ''' @@ -202,7 +202,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'VirtualNetwork' -class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): +class AzureRMNetworkInterfaceInfo(AzureRMModuleBase): def __init__(self): @@ -222,11 +222,14 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): self.resource_group = None self.tags = None - super(AzureRMNetworkInterfaceFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMNetworkInterfaceInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualnetwork_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualnetwork_facts' module has been renamed to 'azure_rm_virtualnetwork_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -238,7 +241,8 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): else: results = self.list_items() - self.results['ansible_facts']['azure_virtualnetworks'] = self.serialize(results) + if is_old_facts: + self.results['ansible_facts']['azure_virtualnetworks'] = self.serialize(results) self.results['virtualnetworks'] = self.curated(results) return self.results @@ -326,7 +330,7 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase): def main(): - AzureRMNetworkInterfaceFacts() + AzureRMNetworkInterfaceInfo() if __name__ == '__main__': diff --git a/library/azure_rm_virtualnetworkpeering_facts.py b/library/_azure_rm_virtualnetworkpeering_facts.py similarity index 92% rename from library/azure_rm_virtualnetworkpeering_facts.py rename to library/_azure_rm_virtualnetworkpeering_facts.py index eb4e563..4548894 100644 --- a/library/azure_rm_virtualnetworkpeering_facts.py +++ b/library/_azure_rm_virtualnetworkpeering_facts.py @@ -13,8 +13,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_virtualnetworkpeering_facts -version_added: "2.8" +module: azure_rm_virtualnetworkpeering_info +version_added: "2.9" short_description: Get facts of Azure Virtual Network Peering description: - Get facts of Azure Virtual Network Peering. @@ -41,7 +41,7 @@ author: EXAMPLES = ''' - name: Get virtual network peering by name - azure_rm_virtualnetworkpeering_facts: + azure_rm_virtualnetworkpeering_info: resource_group: myResourceGroup virtual_network: myVnet1 name: myVnetPeer @@ -158,7 +158,7 @@ def vnetpeering_to_dict(vnetpeering): return results -class AzureRMVirtualNetworkPeeringFacts(AzureRMModuleBase): +class AzureRMVirtualNetworkPeeringInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( @@ -181,11 +181,14 @@ class AzureRMVirtualNetworkPeeringFacts(AzureRMModuleBase): self.results = dict(changed=False) - super(AzureRMVirtualNetworkPeeringFacts, self).__init__(derived_arg_spec=self.module_arg_spec, - supports_tags=False) + super(AzureRMVirtualNetworkPeeringInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False) def exec_module(self, **kwargs): """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_virtualnetworkpeering_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualnetworkpeering_facts' module has been renamed to 'azure_rm_virtualnetworkpeering_info'", version='2.13') for key in list(self.module_arg_spec.keys()): setattr(self, key, kwargs[key]) @@ -246,7 +249,7 @@ class AzureRMVirtualNetworkPeeringFacts(AzureRMModuleBase): def main(): """Main execution""" - AzureRMVirtualNetworkPeeringFacts() + AzureRMVirtualNetworkPeeringInfo() if __name__ == '__main__': diff --git a/library/azure_rm_webapp_facts.py b/library/_azure_rm_webapp_facts.py similarity index 96% rename from library/azure_rm_webapp_facts.py rename to library/_azure_rm_webapp_facts.py index f1687ba..4a3b4cd 100644 --- a/library/azure_rm_webapp_facts.py +++ b/library/_azure_rm_webapp_facts.py @@ -15,9 +15,9 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = ''' --- -module: azure_rm_webapp_facts +module: azure_rm_webapp_info -version_added: "2.7" +version_added: "2.9" short_description: Get Azure web app facts @@ -49,16 +49,16 @@ author: EXAMPLES = ''' - name: Get facts for web app by name - azure_rm_webapp_facts: + azure_rm_webapp_info: resource_group: myResourceGroup name: winwebapp1 - name: Get facts for web apps in resource group - azure_rm_webapp_facts: + azure_rm_webapp_info: resource_group: myResourceGroup - name: Get facts for web apps with tags - azure_rm_webapp_facts: + azure_rm_webapp_info: tags: - testtag - foo:bar @@ -235,7 +235,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'WebApp' -class AzureRMWebAppFacts(AzureRMModuleBase): +class AzureRMWebAppInfo(AzureRMModuleBase): def __init__(self): @@ -258,11 +258,14 @@ class AzureRMWebAppFacts(AzureRMModuleBase): self.framework_names = ['net_framework', 'java', 'php', 'node', 'python', 'dotnetcore', 'ruby'] - super(AzureRMWebAppFacts, self).__init__(self.module_arg_spec, - supports_tags=False, - facts_module=True) + super(AzureRMWebAppInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_webapp_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_webapp_facts' module has been renamed to 'azure_rm_webapp_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) @@ -478,7 +481,7 @@ class AzureRMWebAppFacts(AzureRMModuleBase): def main(): - AzureRMWebAppFacts() + AzureRMWebAppInfo() if __name__ == '__main__': diff --git a/library/azure_rm_aks_info.py b/library/azure_rm_aks_info.py index 36b1c0d..3eb0ef1 100644 --- a/library/azure_rm_aks_info.py +++ b/library/azure_rm_aks_info.py @@ -71,7 +71,6 @@ azure_aks: type: list ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -107,11 +106,6 @@ class AzureRMManagedClusterInfo(AzureRMModuleBase): self.tags = None self.show_kubeconfig = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_aks_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_aks_facts' module has been renamed to 'azure_rm_aks_info'", version='2.13') - super(AzureRMManagedClusterInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -120,6 +114,10 @@ class AzureRMManagedClusterInfo(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_aks_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_aks_facts' module has been renamed to 'azure_rm_aks_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_aksversion_info.py b/library/azure_rm_aksversion_info.py index 515ea48..462ee78 100644 --- a/library/azure_rm_aksversion_info.py +++ b/library/azure_rm_aksversion_info.py @@ -56,7 +56,6 @@ azure_aks_versions: type: list ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -84,11 +83,6 @@ class AzureRMAKSVersion(AzureRMModuleBase): self.location = None self.version = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_aksversion_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_aksversion_facts' module has been renamed to 'azure_rm_aksversion_info'", version='2.13') - super(AzureRMAKSVersion, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -97,6 +91,10 @@ class AzureRMAKSVersion(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_aksversion_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_aksversion_facts' module has been renamed to 'azure_rm_aksversion_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_applicationsecuritygroup_info.py b/library/azure_rm_applicationsecuritygroup_info.py index bdf757a..97b1e6e 100644 --- a/library/azure_rm_applicationsecuritygroup_info.py +++ b/library/azure_rm_applicationsecuritygroup_info.py @@ -89,7 +89,6 @@ applicationsecuritygroups: sample: Succeeded ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -130,12 +129,6 @@ class AzureRMApplicationSecurityGroupInfo(AzureRMModuleBase): self.results = dict(changed=False) - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_applicationsecuritygroup_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_applicationsecuritygroup_facts' module has been renamed to 'azure_rm_applicationsecuritygroup_info'", - version='2.13') - super(AzureRMApplicationSecurityGroupInfo, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=False, supports_tags=False) @@ -143,6 +136,11 @@ class AzureRMApplicationSecurityGroupInfo(AzureRMModuleBase): def exec_module(self, **kwargs): """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_applicationsecuritygroup_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_applicationsecuritygroup_facts' module has been renamed to 'azure_rm_applicationsecuritygroup_info'", + version='2.13') + for key in list(self.module_arg_spec.keys()) + ['tags']: if hasattr(self, key): setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_appserviceplan_info.py b/library/azure_rm_appserviceplan_info.py index ac72145..3309dc1 100644 --- a/library/azure_rm_appserviceplan_info.py +++ b/library/azure_rm_appserviceplan_info.py @@ -126,7 +126,6 @@ except Exception: # This is handled in azure_rm_common pass -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase AZURE_OBJECT_CLASS = 'AppServicePlan' @@ -149,17 +148,16 @@ class AzureRMAppServicePlanInfo(AzureRMModuleBase): self.tags = None self.info_level = None - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_appserviceplan_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_appserviceplan_facts' module has been renamed to 'azure_rm_appserviceplan_info'", version='2.13') - super(AzureRMAppServicePlanInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_appserviceplan_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_appserviceplan_facts' module has been renamed to 'azure_rm_appserviceplan_info'", version='2.13') + for key in self.module_arg_spec: setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_automationaccount_info.py b/library/azure_rm_automationaccount_info.py new file mode 100644 index 0000000..e463579 --- /dev/null +++ b/library/azure_rm_automationaccount_info.py @@ -0,0 +1,383 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Yuwei Zhou, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_automationaccount_info +version_added: '2.9' +short_description: Get Azure automation account facts +description: + - Get facts of automation account. + +options: + resource_group: + description: + - The name of the resource group. + type: str + required: True + name: + description: + - The name of the automation account. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + list_statistics: + description: + - List statistics details for a automation account. + - Note this will cost network overhead, suggest only used when I(name) set. + type: bool + list_usages: + description: + - List usage details for a automation account. + - Note this will cost network overhead, suggest only used when I(name) set. + type: bool + list_keys: + description: + - List keys for a automation account. + - Note this will cost network overhead, suggest only used when I(name) set. + type: bool + +extends_documentation_fragment: + - azure + +author: + - Yuwei Zhou (@yuwzho) + +''' + +EXAMPLES = ''' +- name: Get details of an automation account + azure_rm_automationaccount_info: + name: Testing + resource_group: myResourceGroup + list_statistics: yes + list_usages: yes + list_keys: yes + +- name: List automation account in a resource group + azure_rm_automationaccount_info: + resource_group: myResourceGroup + +- name: List automation account in a resource group + azure_rm_automationaccount_info: +''' + +RETURN = ''' +automation_accounts: + description: + - List of automation account dicts. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + type: str + returned: always + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups + /myResourceGroup/providers/Microsoft.Automation/automationAccounts/Testing" + resource_group: + description: + - Resource group name. + type: str + returned: always + sample: myResourceGroup + name: + description: + - Resource name. + type: str + returned: always + sample: Testing + location: + description: + - Resource location. + type: str + returned: always + sample: eastus + creation_time: + description: + - Resource creation date time. + type: str + returned: always + sample: "2019-04-26T02:55:16.500Z" + last_modified_time: + description: + - Resource last modified date time. + type: str + returned: always + sample: "2019-04-26T02:55:16.500Z" + state: + description: + - Resource state. + type: str + returned: always + sample: ok + keys: + description: + - Resource keys. + type: complex + returned: always + contains: + key_name: + description: + - Name of the key. + type: str + returned: always + sample: Primary + permissions: + description: + - Permission of the key. + type: str + returned: always + sample: Full + value: + description: + - Value of the key. + type: str + returned: always + sample: "MbepKTO6IyGwml0GaKBkKN" + statistics: + description: + - Resource statistics. + type: complex + returned: always + contains: + counter_property: + description: + - Property value of the statistic. + type: str + returned: always + sample: New + counter_value: + description: + - Value of the statistic. + type: int + returned: always + sample: 0 + end_time: + description: + - EndTime of the statistic. + type: str + returned: always + sample: "2019-04-26T06:29:43.587518Z" + id: + description: + - ID of the statistic. + type: str + returned: always + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups + /myResourceGroup/providers/Microsoft.Automation/automationAccounts/Testing/statistics/New" + start_time: + description: + - StartTime of the statistic. + type: str + returned: always + sample: "2019-04-26T06:29:43.587518Z" + usages: + description: + - Resource usages. + type: complex + returned: always + contains: + current_value: + description: + - Current usage. + type: float + returned: always + sample: 0.0 + limit: + description: + - Max limit, C(-1) for unlimited. + type: long + returned: always + sample: -1 + name: + description: + - Usage counter name. + type: complex + returned: always + contains: + localized_value: + description: + - Localized name. + type: str + returned: always + sample: "SubscriptionUsage" + value: + description: + - Name value. + type: str + returned: always + sample: "SubscriptionUsage" + unit: + description: + - Usage unit name. + type: str + returned: always + sample: "Minute" + throttle_status: + description: + - Usage throttle status. + type: str + returned: always + sample: "NotThrottled" + +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.tools import parse_resource_id +except ImportError: + pass + + +class AzureRMAutomationAccountInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ), + list_statistics=dict( + type='bool' + ), + list_usages=dict( + type='bool' + ), + list_keys=dict( + type='bool' + ) + ) + # store the results of the module operation + self.results = dict() + self.resource_group = None + self.name = None + self.tags = None + self.list_statistics = None + self.list_usages = None + self.list_keys = None + + super(AzureRMAutomationAccountInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_automationaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_automationaccount_facts' module has been renamed to 'azure_rm_automationaccount_info'", version='2.13') + + for key in list(self.module_arg_spec): + setattr(self, key, kwargs[key]) + + if self.resource_group and self.name: + accounts = [self.get()] + elif self.resource_group: + accounts = self.list_by_resource_group() + else: + accounts = self.list_all() + self.results['automation_accounts'] = [self.to_dict(x) for x in accounts if self.has_tags(x.tags, self.tags)] + return self.results + + def to_dict(self, account): + if not account: + return None + id_dict = parse_resource_id(account.id) + result = account.as_dict() + result['resource_group'] = id_dict['resource_group'] + if self.list_statistics: + result['statistics'] = self.get_statics(id_dict['resource_group'], account.name) + if self.list_usages: + result['usages'] = self.get_usages(id_dict['resource_group'], account.name) + if self.list_keys: + result['keys'] = self.list_account_keys(id_dict['resource_group'], account.name) + return result + + def get(self): + try: + return self.automation_client.automation_account.get(self.resource_group, self.name) + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when getting automation account {0}: {1}'.format(self.name, exc.message)) + + def list_by_resource_group(self): + result = [] + try: + resp = self.automation_client.automation_account.list_by_resource_group(self.resource_group) + while True: + result.append(resp.next()) + except StopIteration: + pass + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when listing automation account in resource group {0}: {1}'.format(self.resource_group, exc.message)) + return result + + def list_all(self): + result = [] + try: + resp = self.automation_client.automation_account.list() + while True: + result.append(resp.next()) + except StopIteration: + pass + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when listing automation account: {0}'.format(exc.message)) + return result + + def get_statics(self, resource_group, name): + result = [] + try: + resp = self.automation_client.statistics.list_by_automation_account(resource_group, name) + while True: + result.append(resp.next().as_dict()) + except StopIteration: + pass + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when getting statics for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message)) + return result + + def get_usages(self, resource_group, name): + result = [] + try: + resp = self.automation_client.usages.list_by_automation_account(resource_group, name) + while True: + result.append(resp.next().as_dict()) + except StopIteration: + pass + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when getting usage for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message)) + return result + + def list_account_keys(self, resource_group, name): + try: + resp = self.automation_client.keys.list_by_automation_account(resource_group, name) + return [x.as_dict() for x in resp.keys] + except self.automation_models.ErrorResponseException as exc: + self.fail('Error when listing keys for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message)) + + +def main(): + AzureRMAutomationAccountInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_autoscale_info.py b/library/azure_rm_autoscale_info.py index 5db3947..995556a 100644 --- a/library/azure_rm_autoscale_info.py +++ b/library/azure_rm_autoscale_info.py @@ -114,7 +114,6 @@ autoscales: ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase from ansible.module_utils._text import to_native @@ -228,14 +227,14 @@ class AzureRMAutoScaleInfo(AzureRMModuleBase): self.name = None self.tags = None - module = AnsibleModule(self.module_arg_spec) - is_old_facts = module._name == 'azure_rm_autoscale_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_autoscale_facts' module has been renamed to 'azure_rm_autoscale_info'", version='2.13') - super(AzureRMAutoScaleInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_autoscale_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_autoscale_facts' module has been renamed to 'azure_rm_autoscale_info'", version='2.13') + for key in list(self.module_arg_spec): setattr(self, key, kwargs[key]) diff --git a/library/azure_rm_availabilityset_info.py b/library/azure_rm_availabilityset_info.py index 8f10c64..df84730 100644 --- a/library/azure_rm_availabilityset_info.py +++ b/library/azure_rm_availabilityset_info.py @@ -105,7 +105,6 @@ azure_availabilityset: sample: { env: sandbox } ''' -from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: @@ -130,7 +129,7 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): self.results = dict( changed=False, - ansible_facts=dict( + ansible_info=dict( azure_availabilitysets=[] ) ) @@ -139,11 +138,6 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): self.resource_group = None self.tags = None - module = AnsibleModule(self.module_args) - is_old_facts = module._name == 'azure_rm_availabilityset_facts' - if is_old_facts: - module.deprecate("The 'azure_rm_availabilityset_facts' module has been renamed to 'azure_rm_availabilityset_info'", version='2.13') - super(AzureRMAvailabilitySetInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, @@ -152,15 +146,19 @@ class AzureRMAvailabilitySetInfo(AzureRMModuleBase): def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_availabilityset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_availabilityset_facts' module has been renamed to 'azure_rm_availabilityset_info'", version='2.13') + for key in self.module_args: setattr(self, key, kwargs[key]) if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") if self.name: - self.results['ansible_facts']['azure_availabilitysets'] = self.get_item() + self.results['ansible_info']['azure_availabilitysets'] = self.get_item() else: - self.results['ansible_facts']['azure_availabilitysets'] = self.list_items() + self.results['ansible_info']['azure_availabilitysets'] = self.list_items() return self.results diff --git a/library/azure_rm_cdnendpoint_info.py b/library/azure_rm_cdnendpoint_info.py new file mode 100644 index 0000000..de2d869 --- /dev/null +++ b/library/azure_rm_cdnendpoint_info.py @@ -0,0 +1,315 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Hai Cao, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_cdnendpoint_info + +version_added: "2.9" + +short_description: Get Azure CDN endpoint facts + +description: + - Get facts for a specific Azure CDN endpoint or all Azure CDN endpoints. + +options: + resource_group: + description: + - Name of resource group where this CDN profile belongs to. + required: true + profile_name: + description: + - Name of CDN profile. + required: true + name: + description: + - Limit results to a specific Azure CDN endpoint. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Hai Cao (@caohai) + - Yunge zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get facts for all endpoints in CDN profile + azure_rm_cdnendpoint_info: + resource_group: myResourceGroup + profile_name: myCDNProfile + + - name: Get facts of specific CDN endpoint + azure_rm_cdnendpoint_info: + resource_group: myResourceGroup + profile_name: myCDNProfile + name: myEndpoint1 +''' + +RETURN = ''' +cdnendpoints: + description: List of Azure CDN endpoints. + returned: always + type: complex + contains: + resource_group: + description: + - Name of a resource group where the Azure CDN endpoint exists. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Name of the Azure CDN endpoint. + returned: always + type: str + sample: myEndpoint + profile_name: + description: + - Name of the Azure CDN profile that this endpoint is attached to. + returned: always + type: str + sample: myProfile + location: + description: + - Location of the Azure CDN endpoint. + type: str + sample: WestUS + id: + description: + - ID of the Azure CDN endpoint. + type: str + sample: + "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myCDN/providers/Microsoft.Cdn/profiles/myProfile/endpoints/myEndpoint1" + provisioning_state: + description: + - Provisioning status of the Azure CDN endpoint. + type: str + sample: Succeeded + resource_state: + description: + - Resource status of the profile. + type: str + sample: Running + is_compression_enabled: + description: + - Indicates whether content compression is enabled on CDN. + type: bool + sample: true + is_http_allowed: + description: + - Indicates whether HTTP traffic is allowed on the endpoint. + type: bool + sample: true + is_https_allowed: + description: + - Indicates whether HTTPS traffic is allowed on the endpoint. + type: bool + sample: true + query_string_caching_behavior: + description: + - Defines how CDN caches requests that include query strings. + type: str + sample: IgnoreQueryString + content_types_to_compress: + description: + - List of content types on which compression applies. + type: list + sample: [ + "text/plain", + "text/html", + "text/css", + "text/javascript", + "application/x-javascript", + "application/javascript", + "application/json", + "application/xml" + ] + origins: + description: + - The source of the content being delivered via CDN. + sample: { + "host_name": "xxxxxxxx.blob.core.windows.net", + "http_port": null, + "https_port": null, + "name": "xxxxxxxx-blob-core-windows-net" + } + origin_host_header: + description: + - The host header value sent to the origin with each request. + type: str + sample: xxxxxxxx.blob.core.windows.net + origin_path: + description: + - A directory path on the origin that CDN can use to retreive content from. + type: str + sample: /pic/ + tags: + description: + - The tags of the Azure CDN endpoint. + type: list + sample: foo +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from azure.mgmt.cdn import CdnManagementClient + from azure.mgmt.cdn.models import ErrorResponseException + from azure.common import AzureHttpError +except ImportError: + # handled in azure_rm_common + pass + +import re + +AZURE_OBJECT_CLASS = 'endpoints' + + +class AzureRMCdnEndpointInfo(AzureRMModuleBase): + """Utility class to get Azure Azure CDN endpoint facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict( + type='str', + required=True + ), + profile_name=dict( + type='str', + required=True + ), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + cdnendpoints=[] + ) + + self.name = None + self.resource_group = None + self.profile_name = None + self.tags = None + + super(AzureRMCdnEndpointInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_cdnendpoint_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cdnendpoint_facts' module has been renamed to 'azure_rm_cdnendpoint_info'", version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + self.cdn_client = self.get_mgmt_svc_client(CdnManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + api_version='2017-04-02') + + if self.name: + self.results['cdnendpoints'] = self.get_item() + else: + self.results['cdnendpoints'] = self.list_by_profile() + + return self.results + + def get_item(self): + """Get a single Azure Azure CDN endpoint""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self.cdn_client.endpoints.get( + self.resource_group, self.profile_name, self.name) + except ErrorResponseException: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [self.serialize_cdnendpoint(item)] + + return result + + def list_by_profile(self): + """Get all Azure Azure CDN endpoints within an Azure CDN profile""" + + self.log('List all Azure CDN endpoints within an Azure CDN profile') + + try: + response = self.cdn_client.endpoints.list_by_profile( + self.resource_group, self.profile_name) + except ErrorResponseException as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_cdnendpoint(item)) + + return results + + def serialize_cdnendpoint(self, cdnendpoint): + ''' + Convert a Azure CDN endpoint object to dict. + :param cdn: Azure CDN endpoint object + :return: dict + ''' + result = self.serialize_obj(cdnendpoint, AZURE_OBJECT_CLASS) + + new_result = {} + new_result['id'] = cdnendpoint.id + new_result['resource_group'] = re.sub('\\/.*', '', re.sub('.*resourcegroups\\/', '', result['id'])) + new_result['profile_name'] = re.sub('\\/.*', '', re.sub('.*profiles\\/', '', result['id'])) + new_result['name'] = cdnendpoint.name + new_result['type'] = cdnendpoint.type + new_result['location'] = cdnendpoint.location + new_result['resource_state'] = cdnendpoint.resource_state + new_result['provisioning_state'] = cdnendpoint.provisioning_state + new_result['query_string_caching_behavior'] = cdnendpoint.query_string_caching_behavior + new_result['is_compression_enabled'] = cdnendpoint.is_compression_enabled + new_result['is_http_allowed'] = cdnendpoint.is_http_allowed + new_result['is_https_allowed'] = cdnendpoint.is_https_allowed + new_result['content_types_to_compress'] = cdnendpoint.content_types_to_compress + new_result['origin_host_header'] = cdnendpoint.origin_host_header + new_result['origin_path'] = cdnendpoint.origin_path + new_result['origin'] = dict( + name=cdnendpoint.origins[0].name, + host_name=cdnendpoint.origins[0].host_name, + http_port=cdnendpoint.origins[0].http_port, + https_port=cdnendpoint.origins[0].https_port + ) + new_result['tags'] = cdnendpoint.tags + return new_result + + +def main(): + """Main module execution code path""" + + AzureRMCdnEndpointInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_cdnprofile_info.py b/library/azure_rm_cdnprofile_info.py new file mode 100644 index 0000000..3de6967 --- /dev/null +++ b/library/azure_rm_cdnprofile_info.py @@ -0,0 +1,268 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Hai Cao, , Yunge Zhu +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_cdnprofile_info + +version_added: "2.9" + +short_description: Get Azure CDN profile facts + +description: + - Get facts for a specific Azure CDN profile or all CDN profiles. + +options: + name: + description: + - Limit results to a specific CDN profile. + resource_group: + description: + - The resource group to search for the desired CDN profile. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Hai Cao (@caohai) + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get facts for one CDN profile + azure_rm_cdnprofile_info: + name: Testing + resource_group: myResourceGroup + + - name: Get facts for all CDN profiles + azure_rm_cdnprofile_info: + + - name: Get facts by tags + azure_rm_cdnprofile_info: + tags: + - Environment:Test +''' + +RETURN = ''' +cdnprofiles: + description: List of CDN profiles. + returned: always + type: complex + contains: + resource_group: + description: + - Name of a resource group where the CDN profile exists. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Name of the CDN profile. + returned: always + type: str + sample: Testing + location: + description: + - Location of the CDN profile. + type: str + sample: WestUS + id: + description: + - ID of the CDN profile. + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Cdn/profiles/myCDN + provisioning_state: + description: + - Provisioning status of the profile. + type: str + sample: Succeeded + resource_state: + description: + - Resource status of the profile. + type: str + sample: Active + sku: + description: + - The pricing tier, defines a CDN provider, feature list and rate of the CDN profile. + type: str + sample: standard_verizon + type: + description: + - The type of the CDN profile. + type: str + sample: Microsoft.Cdn/profiles + tags: + description: + - The tags of the CDN profile. + type: list + sample: [ + {"foo": "bar"} + ] +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from azure.mgmt.cdn.models import ErrorResponseException + from azure.common import AzureHttpError + from azure.mgmt.cdn import CdnManagementClient +except Exception: + # handled in azure_rm_common + pass + +import re + +AZURE_OBJECT_CLASS = 'profiles' + + +class AzureRMCdnprofileInfo(AzureRMModuleBase): + """Utility class to get Azure CDN profile facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + cdnprofiles=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + self.cdn_client = None + + super(AzureRMCdnprofileInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_cdnprofile_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cdnprofile_facts' module has been renamed to 'azure_rm_cdnprofile_info'", version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + self.cdn_client = self.get_cdn_client() + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if self.name: + self.results['cdnprofiles'] = self.get_item() + elif self.resource_group: + self.results['cdnprofiles'] = self.list_resource_group() + else: + self.results['cdnprofiles'] = self.list_all() + + return self.results + + def get_item(self): + """Get a single Azure CDN profile""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self.cdn_client.profiles.get( + self.resource_group, self.name) + except ErrorResponseException: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [self.serialize_cdnprofile(item)] + + return result + + def list_resource_group(self): + """Get all Azure CDN profiles within a resource group""" + + self.log('List all Azure CDNs within a resource group') + + try: + response = self.cdn_client.profiles.list_by_resource_group( + self.resource_group) + except AzureHttpError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_cdnprofile(item)) + + return results + + def list_all(self): + """Get all Azure CDN profiles within a subscription""" + self.log('List all CDN profiles within a subscription') + try: + response = self.cdn_client.profiles.list() + except Exception as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_cdnprofile(item)) + return results + + def serialize_cdnprofile(self, cdnprofile): + ''' + Convert a CDN profile object to dict. + :param cdn: CDN profile object + :return: dict + ''' + result = self.serialize_obj(cdnprofile, AZURE_OBJECT_CLASS) + + new_result = {} + new_result['id'] = cdnprofile.id + new_result['resource_group'] = re.sub('\\/.*', '', re.sub('.*resourcegroups\\/', '', result['id'])) + new_result['name'] = cdnprofile.name + new_result['type'] = cdnprofile.type + new_result['location'] = cdnprofile.location + new_result['resource_state'] = cdnprofile.resource_state + new_result['sku'] = cdnprofile.sku.name + new_result['provisioning_state'] = cdnprofile.provisioning_state + new_result['tags'] = cdnprofile.tags + return new_result + + def get_cdn_client(self): + if not self.cdn_client: + self.cdn_client = self.get_mgmt_svc_client(CdnManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + api_version='2017-04-02') + return self.cdn_client + + +def main(): + """Main module execution code path""" + + AzureRMCdnprofileInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_containerinstance_info.py b/library/azure_rm_containerinstance_info.py new file mode 100644 index 0000000..e918e89 --- /dev/null +++ b/library/azure_rm_containerinstance_info.py @@ -0,0 +1,321 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_containerinstance_info +version_added: "2.9" +short_description: Get Azure Container Instance facts +description: + - Get facts of Container Instance. + +options: + resource_group: + description: + - The name of the resource group. + required: True + name: + description: + - The name of the container instance. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get specific Container Instance facts + azure_rm_containerinstance_info: + resource_group: myResourceGroup + name: myContainer + + - name: List Container Instances in a specified resource group name + azure_rm_containerinstance_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +container_groups: + description: A list of Container Instance dictionaries. + returned: always + type: complex + contains: + id: + description: + - The resource id. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance/contain + erGroups/myContainer" + resource_group: + description: + - Resource group where the container exists. + returned: always + type: str + sample: testrg + name: + description: + - The resource name. + returned: always + type: str + sample: mycontainers + location: + description: + - The resource location. + returned: always + type: str + sample: westus + os_type: + description: + - The OS type of containers. + returned: always + type: str + sample: linux + ip_address: + description: + - IP address of the container instance. + returned: always + type: str + sample: 173.15.18.1 + dns_name_label: + description: + - The Dns name label for the IP. + returned: always + type: str + sample: mydomain + ports: + description: + - List of ports exposed by the container instance. + returned: always + type: list + sample: [ 80, 81 ] + containers: + description: + - The containers within the container group. + returned: always + type: complex + sample: containers + contains: + name: + description: + - The name of the container instance. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance + /containerGroups/myContainer" + image: + description: + - The container image name. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance + /containerGroups/myContainer" + memory: + description: + - The required memory of the containers in GB. + returned: always + type: float + sample: 1.5 + cpu: + description: + - The required number of CPU cores of the containers. + returned: always + type: int + sample: 1 + ports: + description: + - List of ports exposed within the container group. + returned: always + type: list + sample: [ 80, 81 ] + commands: + description: + - List of commands to execute within the container instance in exec form. + returned: always + type: list + sample: [ "pip install abc" ] + environment_variables: + description: + - List of container environment variables. + type: complex + contains: + name: + description: + - Environment variable name. + type: str + value: + description: + - Environment variable value. + type: str + tags: + description: Tags assigned to the resource. Dictionary of string:string pairs. + type: dict + sample: { "tag1": "abc" } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import _camel_to_snake + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.containerinstance import ContainerInstanceManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMContainerInstanceInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False, + ansible_facts=dict() + ) + self.resource_group = None + self.name = None + + super(AzureRMContainerInstanceInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_containerinstance_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_containerinstance_facts' module has been renamed to 'azure_rm_containerinstance_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.name is not None): + self.results['containerinstances'] = self.get() + elif (self.resource_group is not None): + self.results['containerinstances'] = self.list_by_resource_group() + else: + self.results['containerinstances'] = self.list_all() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.containerinstance_client.container_groups.get(resource_group_name=self.resource_group, + container_group_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Container Instances.') + + if response is not None and self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.containerinstance_client.container_groups.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not list facts for Container Instances.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def list_all(self): + response = None + results = [] + try: + response = self.containerinstance_client.container_groups.list() + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not list facts for Container Instances.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + containers = d['containers'] + ports = d['ip_address']['ports'] if 'ip_address' in d else [] + resource_group = d['id'].split('resourceGroups/')[1].split('/')[0] + + for port_index in range(len(ports)): + ports[port_index] = ports[port_index]['port'] + + for container_index in range(len(containers)): + old_container = containers[container_index] + new_container = { + 'name': old_container['name'], + 'image': old_container['image'], + 'memory': old_container['resources']['requests']['memory_in_gb'], + 'cpu': old_container['resources']['requests']['cpu'], + 'ports': [], + 'commands': old_container.get('command'), + 'environment_variables': old_container.get('environment_variables') + } + for port_index in range(len(old_container['ports'])): + new_container['ports'].append(old_container['ports'][port_index]['port']) + containers[container_index] = new_container + + d = { + 'id': d['id'], + 'resource_group': resource_group, + 'name': d['name'], + 'os_type': d['os_type'], + 'dns_name_label': d['ip_address'].get('dns_name_label'), + 'ip_address': d['ip_address']['ip'] if 'ip_address' in d else '', + 'ports': ports, + 'location': d['location'], + 'containers': containers, + 'restart_policy': _camel_to_snake(d.get('restart_policy')) if d.get('restart_policy') else None, + 'tags': d.get('tags', None) + } + return d + + +def main(): + AzureRMContainerInstanceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_containerregistry_info.py b/library/azure_rm_containerregistry_info.py new file mode 100644 index 0000000..c1a8334 --- /dev/null +++ b/library/azure_rm_containerregistry_info.py @@ -0,0 +1,283 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_containerregistry_info +version_added: "2.9" +short_description: Get Azure Container Registry facts +description: + - Get facts for Container Registry. + +options: + resource_group: + description: + - The name of the resource group to which the container registry belongs. + required: True + name: + description: + - The name of the container registry. + retrieve_credentials: + description: + - Retrieve credentials for container registry. + type: bool + default: no + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Registry + azure_rm_containerregistry_info: + resource_group: myResourceGroup + name: myRegistry + + - name: List instances of Registry + azure_rm_containerregistry_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +registries: + description: + - A list of dictionaries containing facts for registries. + returned: always + type: complex + contains: + id: + description: + - The resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerRegistry/registr + ies/myRegistry" + name: + description: + - The name of the resource. + returned: always + type: str + sample: myRegistry + location: + description: + - The location of the resource. This cannot be changed after the resource is created. + returned: always + type: str + sample: westus + admin_user_enabled: + description: + - Is admin user enabled. + returned: always + type: bool + sample: yes + sku: + description: + - The SKU name of the container registry. + returned: always + type: str + sample: Premium + provisioning_state: + description: + - Provisioning state of the container registry. + returned: always + type: str + sample: Succeeded + login_server: + description: + - Login server for the registry. + returned: always + type: str + sample: acrd08521b.azurecr.io + credentials: + description: + - Credentials, fields will be empty if admin user is not enabled for ACR. + return: when C(retrieve_credentials) is set and C(admin_user_enabled) is set on ACR + type: complex + contains: + username: + description: + - The user name for container registry. + returned: when registry exists and C(admin_user_enabled) is set + type: str + sample: zim + password: + description: + - password value. + returned: when registry exists and C(admin_user_enabled) is set + type: str + sample: pass1value + password2: + description: + - password2 value. + returned: when registry exists and C(admin_user_enabled) is set + type: str + sample: pass2value + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + type: dict + sample: { "tag1": "abc" } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.containerregistry import ContainerRegistryManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMContainerRegistryInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ), + retrieve_credentials=dict( + type='bool', + default=False + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.name = None + self.retrieve_credentials = False + + super(AzureRMContainerRegistryInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_containerregistry_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_containerregistry_facts' module has been renamed to 'azure_rm_containerregistry_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name: + self.results['registries'] = self.get() + elif self.resource_group: + self.results['registries'] = self.list_by_resource_group() + else: + self.results['registries'] = self.list_all() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.containerregistry_client.registries.get(resource_group_name=self.resource_group, + registry_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Registries.') + + if response is not None: + if self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_all(self): + response = None + results = [] + try: + response = self.containerregistry_client.registries.list() + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Registries.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.containerregistry_client.registries.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Registries.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + return results + + def format_item(self, item): + d = item.as_dict() + resource_group = d['id'].split('resourceGroups/')[1].split('/')[0] + name = d['name'] + credentials = {} + admin_user_enabled = d['admin_user_enabled'] + + if self.retrieve_credentials and admin_user_enabled: + credentials = self.containerregistry_client.registries.list_credentials(resource_group, name).as_dict() + for index in range(len(credentials['passwords'])): + password = credentials['passwords'][index] + if password['name'] == 'password': + credentials['password'] = password['value'] + elif password['name'] == 'password2': + credentials['password2'] = password['value'] + credentials.pop('passwords') + + d = { + 'resource_group': resource_group, + 'name': d['name'], + 'location': d['location'], + 'admin_user_enabled': admin_user_enabled, + 'sku': d['sku']['tier'].lower(), + 'provisioning_state': d['provisioning_state'], + 'login_server': d['login_server'], + 'id': d['id'], + 'tags': d.get('tags', None), + 'credentials': credentials + } + return d + + +def main(): + AzureRMContainerRegistryInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_cosmosdbaccount_info.py b/library/azure_rm_cosmosdbaccount_info.py new file mode 100644 index 0000000..f247e91 --- /dev/null +++ b/library/azure_rm_cosmosdbaccount_info.py @@ -0,0 +1,520 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_cosmosdbaccount_info +version_added: "2.9" +short_description: Get Azure Cosmos DB Account facts +description: + - Get facts of Azure Cosmos DB Account. + +options: + resource_group: + description: + - Name of an Azure resource group. + name: + description: + - Cosmos DB database account name. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + retrieve_keys: + description: + - Retrieve keys and connection strings. + type: str + choices: + - all + - readonly + retrieve_connection_strings: + description: + - Retrieve connection strings. + type: bool + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Database Account + azure_rm_cosmosdbaccount_info: + resource_group: myResourceGroup + name: testaccount + + - name: List instances of Database Account + azure_rm_cosmosdbaccousnt_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +accounts: + description: A list of dictionaries containing facts for Database Account. + returned: always + type: complex + contains: + id: + description: + - The unique resource identifier of the database account. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DocumentDB/databaseAccount + s/testaccount" + resource_group: + description: + - Name of an Azure resource group. + returned: always + type: str + sample: myResourceGroup + name: + description: + - The name of the database account. + returned: always + type: str + sample: testaccount + location: + description: + - The location of the resource group to which the resource belongs. + returned: always + type: str + sample: westus + kind: + description: + - Indicates the type of database account. + returned: always + type: str + sample: global_document_db + consistency_policy: + description: + - Consistency policy. + returned: always + type: complex + contains: + default_consistency_level: + description: + - Default consistency level. + returned: always + type: str + sample: session + max_interval_in_seconds: + description: + - Maximum interval in seconds. + returned: always + type: int + sample: 5 + max_staleness_prefix: + description: + - Maximum staleness prefix. + returned: always + type: int + sample: 100 + failover_policies: + description: + - The list of new failover policies for the failover priority change. + returned: always + type: complex + contains: + name: + description: + - Location name. + returned: always + type: str + sample: eastus + failover_priority: + description: + - Failover priority. + returned: always + type: int + sample: 0 + id: + description: + - Read location ID. + returned: always + type: str + sample: testaccount-eastus + read_locations: + description: + - Read locations. + returned: always + type: complex + contains: + name: + description: + - Location name. + returned: always + type: str + sample: eastus + failover_priority: + description: + - Failover priority. + returned: always + type: int + sample: 0 + id: + description: + - Read location ID. + returned: always + type: str + sample: testaccount-eastus + document_endpoint: + description: + - Document endpoint. + returned: always + type: str + sample: https://testaccount-eastus.documents.azure.com:443/ + provisioning_state: + description: + - Provisioning state. + returned: always + type: str + sample: Succeeded + write_locations: + description: + - Write locations. + returned: always + type: complex + contains: + name: + description: + - Location name. + returned: always + type: str + sample: eastus + failover_priority: + description: + - Failover priority. + returned: always + type: int + sample: 0 + id: + description: + - Read location ID. + returned: always + type: str + sample: testaccount-eastus + document_endpoint: + description: + - Document endpoint. + returned: always + type: str + sample: https://testaccount-eastus.documents.azure.com:443/ + provisioning_state: + description: + - Provisioning state. + returned: always + type: str + sample: Succeeded + database_account_offer_type: + description: + - Offer type. + returned: always + type: str + sample: Standard + ip_range_filter: + description: + - Enable IP range filter. + returned: always + type: str + sample: 10.10.10.10 + is_virtual_network_filter_enabled: + description: + - Enable virtual network filter. + returned: always + type: bool + sample: true + enable_automatic_failover: + description: + - Enable automatic failover. + returned: always + type: bool + sample: true + enable_cassandra: + description: + - Enable Cassandra. + returned: always + type: bool + sample: true + enable_table: + description: + - Enable Table. + returned: always + type: bool + sample: true + enable_gremlin: + description: + - Enable Gremlin. + returned: always + type: bool + sample: true + virtual_network_rules: + description: + - List of Virtual Network ACL rules configured for the Cosmos DB account. + type: list + contains: + subnet: + description: + - Resource id of a subnet. + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNet + works/testvnet/subnets/testsubnet1" + ignore_missing_vnet_service_endpoint: + description: + - Create Cosmos DB account without existing virtual network service endpoint. + type: bool + enable_multiple_write_locations: + description: + - Enable multiple write locations. + returned: always + type: bool + sample: true + document_endpoint: + description: + - Document endpoint. + returned: always + type: str + sample: https://testaccount.documents.azure.com:443/ + provisioning_state: + description: + - Provisioning state of Cosmos DB. + returned: always + type: str + sample: Succeeded + primary_master_key: + description: + - Primary master key. + returned: when requested + type: str + sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== + secondary_master_key: + description: + - Primary master key. + returned: when requested + type: str + sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== + primary_readonly_master_key: + description: + - Primary master key. + returned: when requested + type: str + sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== + secondary_readonly_master_key: + description: + - Primary master key. + returned: when requested + type: str + sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== + connection_strings: + description: + - List of connection strings. + type: list + returned: when requested + contains: + connection_string: + description: + - Description of connection string. + type: str + returned: always + sample: Primary SQL Connection String + description: + description: + - Connection string. + type: str + returned: always + sample: "AccountEndpoint=https://testaccount.documents.azure.com:443/;AccountKey=fSEjathnk6ZeBTrXkud9j5kfhtSEQ + q3dpJxJga76h9BZkK2BJJrDzSO6DDn6yKads017OZBZ1YZWyq1cW4iuvA==" + tags: + description: + - Tags assigned to the resource. Dictionary of "string":"string" pairs. + returned: always + type: dict + sample: { "tag1":"abc" } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import _camel_to_snake + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.cosmosdb import CosmosDB + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMCosmosDBAccountInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str' + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ), + retrieve_keys=dict( + type='str', + choices=['all', 'readonly'] + ), + retrieve_connection_strings=dict( + type='bool' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.name = None + self.tags = None + self.retrieve_keys = None + self.retrieve_connection_strings = None + + super(AzureRMCosmosDBAccountInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_cosmosdbaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_cosmosdbaccount_facts' module has been renamed to 'azure_rm_cosmosdbaccount_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(CosmosDB, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name is not None: + self.results['accounts'] = self.get() + elif self.resource_group is not None: + self.results['accounts'] = self.list_all() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.database_accounts.get(resource_group_name=self.resource_group, + account_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Database Account.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.mgmt_client.database_accounts.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Database Account.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def list_all(self): + response = None + results = [] + try: + response = self.mgmt_client.database_accounts.list() + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Database Account.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id'), + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'name': d.get('name', None), + 'location': d.get('location', '').replace(' ', '').lower(), + 'kind': _camel_to_snake(d.get('kind', None)), + 'consistency_policy': {'default_consistency_level': _camel_to_snake(d['consistency_policy']['default_consistency_level']), + 'max_interval_in_seconds': d['consistency_policy']['max_interval_in_seconds'], + 'max_staleness_prefix': d['consistency_policy']['max_staleness_prefix']}, + 'failover_policies': [{'name': fp['location_name'].replace(' ', '').lower(), + 'failover_priority': fp['failover_priority'], + 'id': fp['id']} for fp in d['failover_policies']], + 'read_locations': [{'name': rl['location_name'].replace(' ', '').lower(), + 'failover_priority': rl['failover_priority'], + 'id': rl['id'], + 'document_endpoint': rl['document_endpoint'], + 'provisioning_state': rl['provisioning_state']} for rl in d['read_locations']], + 'write_locations': [{'name': wl['location_name'].replace(' ', '').lower(), + 'failover_priority': wl['failover_priority'], + 'id': wl['id'], + 'document_endpoint': wl['document_endpoint'], + 'provisioning_state': wl['provisioning_state']} for wl in d['write_locations']], + 'database_account_offer_type': d.get('database_account_offer_type'), + 'ip_range_filter': d['ip_range_filter'], + 'is_virtual_network_filter_enabled': d.get('is_virtual_network_filter_enabled'), + 'enable_automatic_failover': d.get('enable_automatic_failover'), + 'enable_cassandra': 'EnableCassandra' in d.get('capabilities', []), + 'enable_table': 'EnableTable' in d.get('capabilities', []), + 'enable_gremlin': 'EnableGremlin' in d.get('capabilities', []), + 'virtual_network_rules': d.get('virtual_network_rules'), + 'enable_multiple_write_locations': d.get('enable_multiple_write_locations'), + 'document_endpoint': d.get('document_endpoint'), + 'provisioning_state': d.get('provisioning_state'), + 'tags': d.get('tags', None) + } + + if self.retrieve_keys == 'all': + keys = self.mgmt_client.database_accounts.list_keys(resource_group_name=self.resource_group, + account_name=self.name) + d['primary_master_key'] = keys.primary_master_key + d['secondary_master_key'] = keys.secondary_master_key + d['primary_readonly_master_key'] = keys.primary_readonly_master_key + d['secondary_readonly_master_key'] = keys.secondary_readonly_master_key + elif self.retrieve_keys == 'readonly': + keys = self.mgmt_client.database_accounts.get_read_only_keys(resource_group_name=self.resource_group, + account_name=self.name) + d['primary_readonly_master_key'] = keys.primary_readonly_master_key + d['secondary_readonly_master_key'] = keys.secondary_readonly_master_key + if self.retrieve_connection_strings: + connection_strings = self.mgmt_client.database_accounts.list_connection_strings(resource_group_name=self.resource_group, + account_name=self.name) + d['connection_strings'] = connection_strings.as_dict() + return d + + +def main(): + AzureRMCosmosDBAccountInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_deployment_info.py b/library/azure_rm_deployment_info.py new file mode 100644 index 0000000..9b6ac71 --- /dev/null +++ b/library/azure_rm_deployment_info.py @@ -0,0 +1,250 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_deployment_info +version_added: "2.9" +short_description: Get Azure Deployment facts +description: + - Get facts of Azure Deployment. + +options: + resource_group: + description: + - The name of the resource group. + required: True + name: + description: + - The name of the deployment. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Deployment + azure_rm_deployment_info: + resource_group: myResourceGroup + name: myDeployment +''' + +RETURN = ''' +deployments: + description: + - A list of dictionaries containing facts for deployments. + returned: always + type: complex + contains: + id: + description: + - The identifier of the resource. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Resources/deployments/myD + eployment" + resource_group: + description: + - Resource group name. + returned: always + sample: myResourceGroup + name: + description: + - Deployment name. + returned: always + sample: myDeployment + provisioning_state: + description: + - Provisioning state of the deployment. + returned: always + sample: Succeeded + template_link: + description: + - Link to the template. + returned: always + sample: "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/d01a5c06f4f1bc03a049ca17bbbd6e06d62657b3/101-vm-simple-linux/ + azuredeploy.json" + parameters: + description: + - Dictionary containing deployment parameters. + returned: always + type: complex + outputs: + description: + - Dictionary containing deployment outputs. + returned: always + output_resources: + description: + - List of resources. + returned: always + type: complex + contains: + id: + description: + - Resource id. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkI + nterfaces/myNetworkInterface" + name: + description: + - Resource name. + returned: always + type: str + sample: myNetworkInterface + type: + description: + - Resource type. + returned: always + type: str + sample: Microsoft.Network/networkInterfaces + depends_on: + description: + - List of resource ids. + type: list + returned: always + sample: + - "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGropup/providers/Microsoft.Network/virtualNet + works/myVirtualNetwork" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDeploymentInfo(AzureRMModuleBase): + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + self.results = dict( + changed=False + ) + self.resource_group = None + self.name = None + + super(AzureRMDeploymentInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_deployment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_deployment_facts' module has been renamed to 'azure_rm_deployment_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name: + self.results['deployments'] = self.get() + else: + self.results['deployments'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.rm_client.deployments.get(self.resource_group, deployment_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Deployment.') + + if response: + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.rm_client.deployments.list(self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Deployment.') + + if response is not None: + for item in response: + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + output_resources = {} + for dependency in d.get('properties', {}).get('dependencies'): + # go through dependent resources + depends_on = [] + for depends_on_resource in dependency['depends_on']: + depends_on.append(depends_on_resource['id']) + # append if not in list + if not output_resources.get(depends_on_resource['id']): + sub_resource = { + 'id': depends_on_resource['id'], + 'name': depends_on_resource['resource_name'], + 'type': depends_on_resource['resource_type'], + 'depends_on': [] + } + output_resources[depends_on_resource['id']] = sub_resource + resource = { + 'id': dependency['id'], + 'name': dependency['resource_name'], + 'type': dependency['resource_type'], + 'depends_on': depends_on + } + output_resources[dependency['id']] = resource + + # convert dictionary to list + output_resources_list = [] + for r in output_resources: + output_resources_list.append(output_resources[r]) + + d = { + 'id': d.get('id'), + 'resource_group': self.resource_group, + 'name': d.get('name'), + 'provisioning_state': d.get('properties', {}).get('provisioning_state'), + 'parameters': d.get('properties', {}).get('parameters'), + 'outputs': d.get('properties', {}).get('outputs'), + 'output_resources': output_resources_list, + 'template_link': d.get('properties', {}).get('template_link').get('uri') + } + return d + + +def main(): + AzureRMDeploymentInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlab_info.py b/library/azure_rm_devtestlab_info.py new file mode 100644 index 0000000..24c52df --- /dev/null +++ b/library/azure_rm_devtestlab_info.py @@ -0,0 +1,272 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlab_info +version_added: "2.9" +short_description: Get Azure DevTest Lab facts +description: + - Get facts of Azure DevTest Lab. + +options: + resource_group: + description: + - The name of the resource group. + type: str + name: + description: + - The name of the lab. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) +''' + +EXAMPLES = ''' + - name: List instances of DevTest Lab by resource group + azure_rm_devtestlab_info: + resource_group: testrg + + - name: List instances of DevTest Lab in subscription + azure_rm_devtestlab_info: + + - name: Get instance of DevTest Lab + azure_rm_devtestlab_info: + resource_group: testrg + name: testlab +''' + +RETURN = ''' +labs: + description: + - A list of dictionaries containing facts for Lab. + returned: always + type: complex + contains: + id: + description: + - The identifier of the resource. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab + resource_group: + description: + - The name of the resource. + returned: always + type: str + sample: testrg + name: + description: + - The name of the resource. + returned: always + type: str + sample: testlab + location: + description: + - The location of the resource. + returned: always + type: str + sample: eastus + storage_type: + description: + - Lab storage type. + returned: always + type: str + sample: standard + premium_data_disks: + description: + - Are premium data disks allowed. + returned: always + type: bool + sample: false + provisioning_state: + description: + - Lab provisioning state. + returned: always + type: str + sample: Succeeded + artifacts_storage_account: + description: + - Artifacts storage account ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/myLab6346 + default_premium_storage_account: + description: + - Default premium storage account ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/myLab6346 + default_storage_account: + description: + - Default storage account ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/myLab6346 + premium_data_disk_storage_account: + description: + - Default storage account ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/myLab6346 + vault_name: + description: + - Key vault ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/myLab6788 + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag': 'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDevTestLabInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str' + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.name = None + self.tags = None + super(AzureRMDevTestLabInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlab_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlab_facts' module has been renamed to 'azure_rm_devtestlab_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.resource_group is not None: + if self.name is not None: + self.results['labs'] = self.get() + else: + self.results['labs'] = self.list_by_resource_group() + else: + self.results['labs'] = self.list_by_subscription() + return self.results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.mgmt_client.labs.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Lab.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def list_by_subscription(self): + response = None + results = [] + try: + response = self.mgmt_client.labs.list_by_subscription() + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Lab.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.labs.get(resource_group_name=self.resource_group, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Lab.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id', None), + 'resource_group': self.resource_group, + 'name': d.get('name', None), + 'location': d.get('location', '').replace(' ', '').lower(), + 'storage_type': d.get('lab_storage_type', '').lower(), + 'premium_data_disks': d.get('premium_data_disks') == 'Enabled', + 'provisioning_state': d.get('provisioning_state'), + 'artifacts_storage_account': d.get('artifacts_storage_account'), + 'default_premium_storage_account': d.get('default_premium_storage_account'), + 'default_storage_account': d.get('default_storage_account'), + 'premium_data_disk_storage_account': d.get('premium_data_disk_storage_account'), + 'vault_name': d.get('vault_name'), + 'tags': d.get('tags', None) + } + return d + + +def main(): + AzureRMDevTestLabInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabarmtemplate_info.py b/library/azure_rm_devtestlabarmtemplate_info.py new file mode 100644 index 0000000..d3189fe --- /dev/null +++ b/library/azure_rm_devtestlabarmtemplate_info.py @@ -0,0 +1,226 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabarmtemplate_info +version_added: "2.9" +short_description: Get Azure DevTest Lab ARM Template facts +description: + - Get facts of Azure DevTest Lab ARM Template. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + artifact_source_name: + description: + - The name of the artifact source. + required: True + type: str + name: + description: + - The name of the ARM template. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get information on DevTest Lab ARM Template + azure_rm_devtestlabarmtemplate_info: + resource_group: myResourceGroup + lab_name: myLab + artifact_source_name: public environment repo + name: WebApp +''' + +RETURN = ''' +arm_templates: + description: + - A list of dictionaries containing facts for DevTest Lab ARM Template. + returned: always + type: complex + contains: + id: + description: + - The identifier of the resource. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/art + ifactSources/public environment repo/armTemplates/WebApp" + resource_group: + description: + - Resource group name. + returned: always + sample: myResourceGroup + lab_name: + description: + - DevTest Lab name. + returned: always + sample: myLab + artifact_source_name: + description: + - Artifact source name. + returned: always + sample: public environment repo + name: + description: + - ARM Template name. + returned: always + sample: WebApp + display_name: + description: + - The tags of the resource. + returned: always + sample: Web App + description: + description: + - The tags of the resource. + returned: always + sample: This template creates an Azure Web App without a data store. + publisher: + description: + - The tags of the resource. + returned: always + sample: Microsoft +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlArmTemplateInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + artifact_source_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.artifact_source_name = None + self.name = None + super(AzureRMDtlArmTemplateInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabarmtemplate_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabarmtemplate_facts' module has been renamed to 'azure_rm_devtestlabarmtemplate_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['armtemplates'] = self.get() + else: + self.results['armtemplates'] = self.list() + + return self.results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.arm_templates.list(resource_group_name=self.resource_group, + lab_name=self.lab_name, + artifact_source_name=self.artifact_source_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for DTL ARM Template.') + + if response is not None: + for item in response: + results.append(self.format_response(item)) + + return results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.arm_templates.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + artifact_source_name=self.artifact_source_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for DTL ARM Template.') + + if response: + results.append(self.format_response(response)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'lab_name': self.parse_resource_to_dict(d.get('id')).get('name'), + 'artifact_source_name': self.parse_resource_to_dict(d.get('id')).get('child_name_1'), + 'id': d.get('id', None), + 'name': d.get('name'), + 'display_name': d.get('display_name'), + 'description': d.get('description'), + 'publisher': d.get('publisher') + } + return d + + +def main(): + AzureRMDtlArmTemplateInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabartifact_info.py b/library/azure_rm_devtestlabartifact_info.py new file mode 100644 index 0000000..612e143 --- /dev/null +++ b/library/azure_rm_devtestlabartifact_info.py @@ -0,0 +1,250 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabartifact_info +version_added: "2.9" +short_description: Get Azure DevTest Lab Artifact facts +description: + - Get facts of Azure DevTest Lab Artifact. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + artifact_source_name: + description: + - The name of the artifact source. + required: True + type: str + name: + description: + - The name of the artifact. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of DevTest Lab Artifact + azure_rm_devtestlabartifact_info: + resource_group: myResourceGroup + lab_name: myLab + artifact_source_name: myArtifactSource + name: myArtifact +''' + +RETURN = ''' +artifacts: + description: + - A list of dictionaries containing facts for DevTest Lab Artifact. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/ar + tifactSources/myArtifactSource/artifacts/myArtifact" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + artifact_source_name: + description: + - The name of the artifact source. + returned: always + type: str + sample: myArtifactSource + name: + description: + - The name of the artifact. + returned: always + type: str + sample: myArtifact + description: + description: + - Description of the artifact. + returned: always + type: str + sample: Installs My Software + file_path: + description: + - Artifact's path in the repo. + returned: always + type: str + sample: Artifacts/myArtifact + publisher: + description: + - Publisher name. + returned: always + type: str + sample: MyPublisher + target_os_type: + description: + - Target OS type. + returned: always + type: str + sample: Linux + title: + description: + - Title of the artifact. + returned: always + type: str + sample: My Software + parameters: + description: + - A dictionary containing parameters definition of the artifact. + returned: always + type: complex + sample: {} +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMArtifactInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + artifact_source_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.artifact_source_name = None + self.name = None + super(AzureRMArtifactInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['artifacts'] = self.get() + else: + self.results['artifacts'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.artifacts.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + artifact_source_name=self.artifact_source_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Artifact.') + + if response: + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.artifacts.list(resource_group_name=self.resource_group, + lab_name=self.lab_name, + artifact_source_name=self.artifact_source_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Artifact.') + + if response is not None: + for item in response: + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'lab_name': self.parse_resource_to_dict(d.get('id')).get('name'), + 'artifact_source_name': self.parse_resource_to_dict(d.get('id')).get('child_name_1'), + 'id': d.get('id'), + 'description': d.get('description'), + 'file_path': d.get('file_path'), + 'name': d.get('name'), + 'parameters': d.get('parameters'), + 'publisher': d.get('publisher'), + 'target_os_type': d.get('target_os_type'), + 'title': d.get('title') + } + return d + + +def main(): + AzureRMArtifactInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabartifactsource_info.py b/library/azure_rm_devtestlabartifactsource_info.py new file mode 100644 index 0000000..8446b7d --- /dev/null +++ b/library/azure_rm_devtestlabartifactsource_info.py @@ -0,0 +1,258 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabartifactsource_info +version_added: "2.9" +short_description: Get Azure DevTest Lab Artifact Source facts +description: + - Get facts of Azure DevTest Lab Artifact Source. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of DevTest Lab. + required: True + type: str + name: + description: + - The name of DevTest Lab Artifact Source. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of DevTest Lab Artifact Source + azure_rm_devtestlabartifactsource_info: + resource_group: myResourceGroup + lab_name: myLab + name: myArtifactSource +''' + +RETURN = ''' +artifactsources: + description: + - A list of dictionaries containing facts for DevTest Lab Artifact Source. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/ar + tifactSources/myArtifactSource" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - The name of the artifact source. + returned: always + type: str + sample: myArtifactSource + display_name: + description: + - The artifact source's display name. + returned: always + type: str + sample: Public Artifact Repo + source_type: + description: + - The artifact source's type. + returned: always + type: str + sample: github + is_enabled: + description: + - Is the artifact source enabled. + returned: always + type: str + sample: True + uri: + description: + - URI of the artifact source. + returned: always + type: str + sample: https://github.com/Azure/azure-devtestlab.git + folder_path: + description: + - The folder containing artifacts. + returned: always + type: str + sample: /Artifacts + arm_template_folder_path: + description: + - The folder containing Azure Resource Manager templates. + returned: always + type: str + sample: /Environments + provisioning_state: + description: + - Provisioning state of artifact source. + returned: always + type: str + sample: Succeeded + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag': 'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlArtifactSourceInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.name = None + self.tags = None + super(AzureRMDtlArtifactSourceInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabartifactsource_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabartifactsource_facts' module has been renamed to 'azure_rm_devtestlabartifactsource_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['artifactsources'] = self.get() + else: + self.results['artifactsources'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.artifact_sources.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Artifact Source.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.artifact_sources.list(resource_group_name=self.resource_group, + lab_name=self.lab_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Artifact Source.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id'), + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'lab_name': self.parse_resource_to_dict(d.get('id')).get('name'), + 'name': d.get('name'), + 'display_name': d.get('display_name'), + 'tags': d.get('tags'), + 'source_type': d.get('source_type').lower(), + 'is_enabled': d.get('status') == 'Enabled', + 'uri': d.get('uri'), + 'arm_template_folder_path': d.get('arm_template_folder_path'), + 'folder_path': d.get('folder_path'), + 'provisioning_state': d.get('provisioning_state') + } + return d + + +def main(): + AzureRMDtlArtifactSourceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabcustomimage_info.py b/library/azure_rm_devtestlabcustomimage_info.py new file mode 100644 index 0000000..8d964dc --- /dev/null +++ b/library/azure_rm_devtestlabcustomimage_info.py @@ -0,0 +1,229 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabcustomimage_info +version_added: "2.9" +short_description: Get Azure DevTest Lab Custom Image facts +description: + - Get facts of Azure Azure DevTest Lab Custom Image. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + name: + description: + - The name of the custom image. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Custom Image + azure_rm_devtestlabcustomimage_info: + resource_group: myResourceGroup + lab_name: myLab + name: myImage + + - name: List instances of Custom Image in the lab + azure_rm_devtestlabcustomimage_info: + resource_group: myResourceGroup + lab_name: myLab + name: myImage +''' + +RETURN = ''' +custom_images: + description: + - A list of dictionaries containing facts for Custom Image. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/cu + stomimages/myImage" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - The name of the image. + returned: always + type: str + sample: myImage + managed_shapshot_id: + description: + - Managed snapshot id. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.compute/snapshots/myImage" + source_vm_id: + description: + - Source VM id. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx//resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab/v + irtualmachines/myLabVm" + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag':'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlCustomImageInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + name=dict( + type='str', + required=True + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.name = None + self.tags = None + super(AzureRMDtlCustomImageInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabcustomimage_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabcustomimage_facts' module has been renamed to 'azure_rm_devtestlabcustomimage_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['custom_images'] = self.get() + else: + self.results['custom_images'] = self.list() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.custom_images.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Custom Image.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.custom_images.list(resource_group_name=self.resource_group, + lab_name=self.lab_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Custom Image.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'lab_name': self.lab_name, + 'name': d.get('name'), + 'id': d.get('id'), + 'managed_snapshot_id': d.get('managed_snapshot_id'), + 'source_vm_id': d.get('vm', {}).get('source_vm_id'), + 'tags': d.get('tags') + } + return d + + +def main(): + AzureRMDtlCustomImageInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabenvironment_info.py b/library/azure_rm_devtestlabenvironment_info.py new file mode 100644 index 0000000..d3409c2 --- /dev/null +++ b/library/azure_rm_devtestlabenvironment_info.py @@ -0,0 +1,245 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabenvironment_info +version_added: "2.9" +short_description: Get Azure Environment facts +description: + - Get facts of Azure Environment. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + user_name: + description: + - The name of the user profile. + required: True + type: str + name: + description: + - The name of the environment. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Environment + azure_rm_devtestlabenvironment_info: + resource_group: myResourceGroup + lab_name: myLab + user_name: myUser + name: myEnvironment +''' + +RETURN = ''' +environments: + description: + - A list of dictionaries containing facts for Environment. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/sc + hedules/xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxxx/environments/myEnvironment" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - The name of the environment. + returned: always + type: str + sample: myEnvironment + deployment_template: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/mylab/art + ifactSources/public environment repo/armTemplates/WebApp" + resource_group_id: + description: + - Target resource group id. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myLab-myEnvironment-982571" + state: + description: + - Deployment state. + returned: always + type: str + sample: Succeeded + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag': 'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlEnvironmentInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + user_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.user_name = None + self.name = None + self.tags = None + super(AzureRMDtlEnvironmentInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabenvironment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabenvironment_facts' module has been renamed to 'azure_rm_devtestlabenvironment_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['environments'] = self.get() + else: + self.results['environments'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.environments.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + user_name=self.user_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Environment.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.environments.list(resource_group_name=self.resource_group, + lab_name=self.lab_name, + user_name=self.user_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Environment.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'lab_name': self.lab_name, + 'name': d.get('name'), + 'user_name': self.user_name, + 'id': d.get('id', None), + 'deployment_template': d.get('deployment_properties', {}).get('arm_template_id'), + 'location': d.get('location'), + 'provisioning_state': d.get('provisioning_state'), + 'resource_group_id': d.get('resource_group_id'), + 'tags': d.get('tags', None) + } + return d + + +def main(): + AzureRMDtlEnvironmentInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabpolicy_info.py b/library/azure_rm_devtestlabpolicy_info.py new file mode 100644 index 0000000..7df4596 --- /dev/null +++ b/library/azure_rm_devtestlabpolicy_info.py @@ -0,0 +1,243 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabpolicy_info +version_added: "2.9" +short_description: Get Azure DTL Policy facts +description: + - Get facts of Azure DTL Policy. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + policy_set_name: + description: + - The name of the policy set. + required: True + type: str + name: + description: + - The name of the policy. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Policy + azure_rm_devtestlabpolicy_info: + resource_group: myResourceGroup + lab_name: myLab + policy_set_name: myPolicySet + name: myPolicy +''' + +RETURN = ''' +policies: + description: + - A list of dictionaries containing facts for Policy. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/po + licysets/myPolicySet/policies/myPolicy" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - The name of the artifact source. + returned: always + type: str + sample: myArtifactSource + fact_name: + description: + - The name of the policy fact. + returned: always + type: str + sample: UserOwnedLabVmCount + evaluator_type: + description: + - Evaluator type for policy fact. + returned: always + type: str + sample: MaxValuePolicy + threshold: + description: + - Fact's threshold. + returned: always + type: str + sample: 5 + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag': 'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlPolicyInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + policy_set_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.policy_set_name = None + self.name = None + self.tags = None + super(AzureRMDtlPolicyInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabpolicy_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabpolicy_facts' module has been renamed to 'azure_rm_devtestlabpolicy_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['policies'] = self.get() + else: + self.results['policies'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.policies.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + policy_set_name=self.policy_set_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Policy.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.policies.list(resource_group_name=self.resource_group, + lab_name=self.lab_name, + policy_set_name=self.policy_set_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Policy.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'policy_set_name': self.policy_set_name, + 'name': d.get('name'), + 'id': d.get('id'), + 'tags': d.get('tags'), + 'status': d.get('status'), + 'threshold': d.get('threshold'), + 'fact_name': d.get('fact_name'), + 'evaluator_type': d.get('evaluator_type') + } + return d + + +def main(): + AzureRMDtlPolicyInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabschedule_info.py b/library/azure_rm_devtestlabschedule_info.py new file mode 100644 index 0000000..f620d2c --- /dev/null +++ b/library/azure_rm_devtestlabschedule_info.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabschedule_info +version_added: "2.9" +short_description: Get Azure Schedule facts +description: + - Get facts of Azure Schedule. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + name: + description: + - The name of the schedule. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of Schedule + azure_rm_devtestlabschedule_info: + resource_group: myResourceGroup + lab_name: myLab + name: mySchedule +''' + +RETURN = ''' +schedules: + description: + - A list of dictionaries containing facts for Schedule. + returned: always + type: complex + contains: + id: + description: + - The identifier of the artifact source. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DevTestLab/labs/myLab/sc + hedules/labvmsshutdown" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - The name of the environment. + returned: always + type: str + sample: lab_vms_shutdown + time: + description: + - Time of the schedule. + returned: always + type: str + sample: lab_vms_shutdown + time_zone_id: + description: + - Time zone id. + returned: always + type: str + sample: UTC+12 + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'MyTag': 'MyValue' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import _camel_to_snake, _snake_to_camel + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlScheduleInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.name = None + self.tags = None + super(AzureRMDtlScheduleInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabschedule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabschedule_facts' module has been renamed to 'azure_rm_devtestlabschedule_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + if self.name: + self.results['schedules'] = self.get() + else: + self.results['schedules'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.schedules.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + name=_snake_to_camel(self.name)) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Schedule.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.schedules.list(resource_group_name=self.resource_group, + lab_name=self.lab_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Schedule.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'lab_name': self.lab_name, + 'name': _camel_to_snake(d.get('name')), + 'id': d.get('id', None), + 'tags': d.get('tags', None), + 'time': d.get('daily_recurrence', {}).get('time'), + 'time_zone_id': d.get('time_zone_id') + } + return d + + +def main(): + AzureRMDtlScheduleInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabvirtualmachine_info.py b/library/azure_rm_devtestlabvirtualmachine_info.py new file mode 100644 index 0000000..b41e100 --- /dev/null +++ b/library/azure_rm_devtestlabvirtualmachine_info.py @@ -0,0 +1,329 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabvirtualmachine_info +version_added: "2.9" +short_description: Get Azure DevTest Lab Virtual Machine facts +description: + - Get facts of Azure DevTest Lab Virtual Machine. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of the lab. + required: True + type: str + name: + description: + - The name of the virtual machine. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of DTL Virtual Machine + azure_rm_devtestlabvirtualmachine_info: + resource_group: myResourceGroup + lab_name: myLab + name: myVm +''' + +RETURN = ''' +virtualmachines: + description: + - A list of dictionaries containing facts for DevTest Lab Virtual Machine. + returned: always + type: complex + contains: + id: + description: + - The identifier of the virtual machine. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab/virt + ualmachines/myVm" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - Name of the virtual machine. + returned: always + type: str + sample: myVm + notes: + description: + - Notes of the virtual machine. + returned: always + type: str + sample: My VM notes + disallow_public_ip_address: + description: + - Whether public IP should be not allowed. + returned: always + type: bool + sample: false + expiration_date: + description: + - Virtual machine expiration date. + returned: always + type: str + sample: 2029-02-22T01:49:12.117974Z + image: + description: + - Gallery image reference. + returned: always + type: complex + contains: + offer: + description: + - The offer of the gallery image. + returned: when created from gallery image + type: str + sample: UbuntuServer + os_type: + description: + - Operating system type. + returned: when created from gallery image + type: str + sample: Linux + sku: + description: + - The SKU of the gallery image. + returned: when created from gallery image + type: str + sample: 16.04-LTS + publisher: + description: + - The publisher of the gallery image. + returned: when created from gallery image + type: str + sample: Canonical + version: + description: + - The version of the gallery image. + returned: when created from gallery image + type: str + sample: latest + os_type: + description: + - Operating system type. + returned: always + type: str + sample: linux + vm_size: + description: + - Virtual machine size. + returned: always + type: str + sample: Standard_A2_v2 + user_name: + description: + - Admin user name. + returned: always + type: str + sample: dtl_admin + storage_type: + description: + - Storage type to use for virtual machine. + returned: always + type: str + sample: standard + compute_vm_id: + description: + - Resource id of compute virtual machine. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myLab-myVm-097933/providers/Microsoft.Compute/virtualMachines/myVm + compute_vm_resource_group: + description: + - Resource group where compute virtual machine is created. + returned: always + type: str + sample: myLab-myVm-097933 + compute_vm_name: + description: + - Name of compute virtual machine. + returned: always + type: str + sample: myVm + fqdn: + description: + - Fully qualified domain name. + returned: always + type: str + sample: myvm.eastus.cloudapp.azure.com + provisioning_state: + description: + - Provisioning state of the virtual network. + returned: always + type: str + sample: Succeeded + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: "{ 'foo': 'bar' }" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDtlVirtualMachineInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.name = None + self.tags = None + super(AzureRMDtlVirtualMachineInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabvirtualmachine_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabvirtualmachine_facts' module has been renamed to 'azure_rm_devtestlabvirtualmachine_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['virtualmachines'] = self.get() + else: + self.results['virtualmachines'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.virtual_machines.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Virtual Machine.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.virtual_machines.list(resource_group_name=self.resource_group, + lab_name=self.lab_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Virtual Machine.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id', None), + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'lab_name': self.parse_resource_to_dict(d.get('id')).get('name'), + 'name': d.get('name'), + 'notes': d.get('notes'), + 'disallow_public_ip_address': d.get('disallow_public_ip_address'), + 'expiration_date': d.get('expiration_date'), + 'image': d.get('gallery_image_reference'), + 'os_type': d.get('os_type').lower(), + 'vm_size': d.get('size'), + 'user_name': d.get('user_name'), + 'storage_type': d.get('storage_type').lower(), + 'compute_vm_id': d.get('compute_id'), + 'compute_vm_resource_group': self.parse_resource_to_dict(d.get('compute_id')).get('resource_group'), + 'compute_vm_name': self.parse_resource_to_dict(d.get('compute_id')).get('name'), + 'fqdn': d.get('fqdn'), + 'provisioning_state': d.get('provisioning_state'), + 'tags': d.get('tags', None) + } + return d + + +def main(): + AzureRMDtlVirtualMachineInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_devtestlabvirtualnetwork_info.py b/library/azure_rm_devtestlabvirtualnetwork_info.py new file mode 100644 index 0000000..c96941c --- /dev/null +++ b/library/azure_rm_devtestlabvirtualnetwork_info.py @@ -0,0 +1,221 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_devtestlabvirtualnetwork_info +version_added: "2.9" +short_description: Get Azure DevTest Lab Virtual Network facts +description: + - Get facts of Azure DevTest Lab Virtual Network. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + lab_name: + description: + - The name of DevTest Lab. + required: True + type: str + name: + description: + - The name of DevTest Lab Virtual Network. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of DevTest Lab Virtual Network + azure_rm_devtestlabvirtualnetwork_info: + resource_group: myResourceGroup + lab_name: myLab + name: myVirtualNetwork + + - name: List all Virtual Networks in DevTest Lab + azure_rm_devtestlabvirtualnetwork_info: + resource_group: myResourceGroup + lab_name: myLab + name: myVirtualNetwork +''' + +RETURN = ''' +virtualnetworks: + description: + - A list of dictionaries containing facts for DevTest Lab Virtual Network. + returned: always + type: complex + contains: + id: + description: + - The identifier of the virtual network. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab/virt + ualnetworks/myVirtualNetwork" + resource_group: + description: + - Name of the resource group. + returned: always + type: str + sample: myResourceGroup + lab_name: + description: + - Name of the lab. + returned: always + type: str + sample: myLab + name: + description: + - Name of the virtual network. + returned: always + type: str + sample: myVirtualNetwork + description: + description: + - Description of the virtual network. + returned: always + type: str + sample: My Virtual Network + external_provider_resource_id: + description: + - Resource id of an external virtual network. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/my + VirtualNetwork" + provisioning_state: + description: + - Provisioning state of the virtual network. + returned: always + type: str + sample: Succeeded +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.devtestlabs import DevTestLabsClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMDevTestLabVirtualNetworkInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + lab_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.lab_name = None + self.name = None + super(AzureRMDevTestLabVirtualNetworkInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_devtestlabvirtualnetwork_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_devtestlabvirtualnetwork_facts' module has been renamed to 'azure_rm_devtestlabvirtualnetwork_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name: + self.results['virtualnetworks'] = self.get() + else: + self.results['virtualnetworks'] = self.list() + + return self.results + + def list(self): + response = None + results = [] + try: + response = self.mgmt_client.virtual_networks.list(resource_group_name=self.resource_group, + lab_name=self.lab_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not list Virtual Networks for DevTest Lab.') + + if response is not None: + for item in response: + results.append(self.format_response(item)) + + return results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.virtual_networks.get(resource_group_name=self.resource_group, + lab_name=self.lab_name, + name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Virtual Network.') + + if response: + results.append(self.format_response(response)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'lab_name': self.lab_name, + 'name': d.get('name', None), + 'id': d.get('id', None), + 'external_provider_resource_id': d.get('external_provider_resource_id', None), + 'provisioning_state': d.get('provisioning_state', None), + 'description': d.get('description', None) + } + return d + + +def main(): + AzureRMDevTestLabVirtualNetworkInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_dnsrecordset_info.py b/library/azure_rm_dnsrecordset_info.py new file mode 100644 index 0000000..e6f6220 --- /dev/null +++ b/library/azure_rm_dnsrecordset_info.py @@ -0,0 +1,293 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Obezimnaka Boms, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_dnsrecordset_info + +version_added: "2.9" + +short_description: Get DNS Record Set facts + +description: + - Get facts for a specific DNS Record Set in a Zone, or a specific type in all Zones or in one Zone etc. + +options: + relative_name: + description: + - Only show results for a Record Set. + resource_group: + description: + - Limit results by resource group. Required when filtering by name or type. + zone_name: + description: + - Limit results by zones. Required when filtering by name or type. + record_type: + description: + - Limit record sets by record type. + top: + description: + - Limit the maximum number of record sets to return. + type: int + +extends_documentation_fragment: + - azure + - azure_tags + +author: + - Ozi Boms (@ozboms) + +''' + +EXAMPLES = ''' +- name: Get facts for one Record Set + azure_rm_dnsrecordset_info: + resource_group: myResourceGroup + zone_name: example.com + relative_name: server10 + record_type: A +- name: Get facts for all Type A Record Sets in a Zone + azure_rm_dnsrecordset_info: + resource_group: myResourceGroup + zone_name: example.com + record_type: A +- name: Get all record sets in one zone + azure_rm_dnsrecordset_info: + resource_group: myResourceGroup + zone_name: example.com +''' + +RETURN = ''' +azure_dnsrecordset: + description: + - List of record set dicts. + returned: always + type: list + example: [ + { + "etag": "60ac0480-44dd-4881-a2ed-680d20b3978e", + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/dnszones/newzone.com/A/servera", + "name": "servera", + "properties": { + "ARecords": [ + { + "ipv4Address": "10.4.5.7" + }, + { + "ipv4Address": "2.4.5.8" + } + ], + "TTL": 12900 + }, + "type": "Microsoft.Network/dnszones/A" + }] +dnsrecordsets: + description: + - List of record set dicts, which shares the same hierarchy as M(azure_rm_dnsrecordset) module's parameter. + returned: always + type: list + contains: + id: + description: + - ID of the dns recordset. + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/dnszones/newzone. + com/A/servera" + relative_name: + description: + - Name of the dns recordset. + sample: servera + record_type: + description: + - The type of the record set. + - Can be C(A), C(AAAA), C(CNAME), C(MX), C(NS), C(SRV), C(TXT), C(PTR). + sample: A + time_to_live: + description: + - Time to live of the record set in seconds. + sample: 12900 + records: + description: + - List of records depending on the type of recordset. + sample: [ + { + "ipv4Address": "10.4.5.7" + }, + { + "ipv4Address": "2.4.5.8" + } + ] + provisioning_state: + description: + - Provision state of the resource. + sample: Successed + fqdn: + description: + - Fully qualified domain name of the record set. + sample: www.newzone.com +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +AZURE_OBJECT_CLASS = 'RecordSet' + + +RECORDSET_VALUE_MAP = dict( + A='arecords', + AAAA='aaaa_records', + CNAME='cname_record', + MX='mx_records', + NS='ns_records', + PTR='ptr_records', + SRV='srv_records', + TXT='txt_records', + SOA='soa_record', + CAA='caa_records' + # FUTURE: add missing record types from https://github.com/Azure/azure-sdk-for-python/blob/master/azure-mgmt-dns/azure/mgmt/dns/models/record_set.py +) + + +class AzureRMRecordSetInfo(AzureRMModuleBase): + + def __init__(self): + + # define user inputs into argument + self.module_arg_spec = dict( + relative_name=dict(type='str'), + resource_group=dict(type='str'), + zone_name=dict(type='str'), + record_type=dict(type='str'), + top=dict(type='int') + ) + + # store the results of the module operation + self.results = dict( + changed=False, + ansible_info=dict(azure_dnsrecordset=[]) + ) + + self.relative_name = None + self.resource_group = None + self.zone_name = None + self.record_type = None + self.top = None + + super(AzureRMRecordSetInfo, self).__init__(self.module_arg_spec) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_dnsrecordset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_dnsrecordset_facts' module has been renamed to 'azure_rm_dnsrecordset_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if not self.top or self.top <= 0: + self.top = None + + # create conditionals to catch errors when calling record facts + if self.relative_name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name or record type.") + if self.relative_name and not self.zone_name: + self.fail("Parameter error: DNS Zone required when filtering by name or record type.") + + results = [] + # list the conditions for what to return based on input + if self.relative_name is not None: + # if there is a name listed, they want only facts about that specific Record Set itself + results = self.get_item() + elif self.record_type: + # else, they just want all the record sets of a specific type + results = self.list_type() + elif self.zone_name: + # if there is a zone name listed, then they want all the record sets in a zone + results = self.list_zone() + + if is_old_facts: + self.results['ansible_facts']['azure_dnsrecordset'] = self.serialize_list(results) + self.results['dnsrecordsets'] = self.curated_list(results) + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.relative_name)) + item = None + results = [] + + # try to get information for specific Record Set + try: + item = self.dns_client.record_sets.get(self.resource_group, self.zone_name, self.relative_name, self.record_type) + except CloudError: + pass + + results = [item] + return results + + def list_type(self): + self.log('Lists the record sets of a specified type in a DNS zone') + try: + response = self.dns_client.record_sets.list_by_type(self.resource_group, self.zone_name, self.record_type, top=self.top) + except AzureHttpError as exc: + self.fail("Failed to list for record type {0} - {1}".format(self.record_type, str(exc))) + + results = [] + for item in response: + results.append(item) + return results + + def list_zone(self): + self.log('Lists all record sets in a DNS zone') + try: + response = self.dns_client.record_sets.list_by_dns_zone(self.resource_group, self.zone_name, top=self.top) + except AzureHttpError as exc: + self.fail("Failed to list for zone {0} - {1}".format(self.zone_name, str(exc))) + + results = [] + for item in response: + results.append(item) + return results + + def serialize_list(self, raws): + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) for item in raws] if raws else [] + + def curated_list(self, raws): + return [self.record_to_dict(item) for item in raws] if raws else [] + + def record_to_dict(self, record): + record_type = record.type[len('Microsoft.Network/dnszones/'):] + records = getattr(record, RECORDSET_VALUE_MAP.get(record_type)) + if not isinstance(records, list): + records = [records] + return dict( + id=record.id, + relative_name=record.name, + record_type=record_type, + records=[x.as_dict() for x in records], + time_to_live=record.ttl, + fqdn=record.fqdn, + provisioning_state=record.provisioning_state + ) + + +def main(): + AzureRMRecordSetInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_dnszone_info.py b/library/azure_rm_dnszone_info.py new file mode 100644 index 0000000..a09e2aa --- /dev/null +++ b/library/azure_rm_dnszone_info.py @@ -0,0 +1,258 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Obezimnaka Boms, +# +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_dnszone_info + +version_added: "2.9" + +short_description: Get DNS zone facts + +description: + - Get facts for a specific DNS zone or all DNS zones within a resource group. + +options: + resource_group: + description: + - Limit results by resource group. Required when filtering by name. + name: + description: + - Only show results for a specific zone. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + - azure_tags + +author: + - Obezimnaka Boms (@ozboms) + +''' + +EXAMPLES = ''' +- name: Get facts for one zone + azure_rm_dnszone_info: + resource_group: myResourceGroup + name: foobar22 + +- name: Get facts for all zones in a resource group + azure_rm_dnszone_info: + resource_group: myResourceGroup + +- name: Get facts by tags + azure_rm_dnszone_info: + tags: + - testing +''' + +RETURN = ''' +azure_dnszones: + description: + - List of zone dicts. + returned: always + type: list + example: [{ + "etag": "00000002-0000-0000-0dcb-df5776efd201", + "location": "global", + "properties": { + "maxNumberOfRecordSets": 5000, + "numberOfRecordSets": 15 + }, + "tags": {} + }] +dnszones: + description: + - List of zone dicts, which share the same layout as azure_rm_dnszone module parameter. + returned: always + type: list + contains: + id: + description: + - id of the DNS Zone. + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/dnszones/azure.com" + name: + description: + - name of the DNS zone. + sample: azure.com + type: + description: + - The type of this DNS zone (C(public) or C(private)). + sample: private + registration_virtual_networks: + description: + - A list of references to virtual networks that register hostnames in this DNS zone. + type: list + sample: ["/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/bar"] + resolution_virtual_networks: + description: + - A list of references to virtual networks that resolve records in this DNS zone. + type: list + sample: ["/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/deadbeef"] + number_of_record_sets: + description: + - The current number of record sets in this DNS zone. + type: int + sample: 2 + max_number_of_record_sets: + description: + - The maximum number of record sets that can be created in this DNS zone. + type: int + sample: 5000 + name_servers: + description: + - The name servers for this DNS zone. + type: list + sample: [ + "ns1-03.azure-dns.com.", + "ns2-03.azure-dns.net.", + "ns3-03.azure-dns.org.", + "ns4-03.azure-dns.info." + ] +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils._text import to_native + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +AZURE_OBJECT_CLASS = 'DnsZone' + + +class AzureRMDNSZoneInfo(AzureRMModuleBase): + + def __init__(self): + + # define user inputs into argument + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + # store the results of the module operation + self.results = dict( + changed=False, + ansible_info=dict(azure_dnszones=[]) + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMDNSZoneInfo, self).__init__(self.module_arg_spec) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_dnszone_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_dnszone_facts' module has been renamed to 'azure_rm_dnszone_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + results = [] + # list the conditions and what to return based on user input + if self.name is not None: + # if there is a name, facts about that specific zone + results = self.get_item() + elif self.resource_group: + # all the zones listed in that specific resource group + results = self.list_resource_group() + else: + # all the zones in a subscription + results = self.list_items() + + self.results['ansible_info']['azure_dnszones'] = self.serialize_items(results) + self.results['dnszones'] = self.curated_items(results) + + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + results = [] + # get specific zone + try: + item = self.dns_client.zones.get(self.resource_group, self.name) + except CloudError: + pass + + # serialize result + if item and self.has_tags(item.tags, self.tags): + results = [item] + return results + + def list_resource_group(self): + self.log('List items for resource group') + try: + response = self.dns_client.zones.list_by_resource_group(self.resource_group) + except AzureHttpError as exc: + self.fail("Failed to list for resource group {0} - {1}".format(self.resource_group, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def list_items(self): + self.log('List all items') + try: + response = self.dns_client.zones.list() + except AzureHttpError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def serialize_items(self, raws): + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) for item in raws] if raws else [] + + def curated_items(self, raws): + return [self.zone_to_dict(item) for item in raws] if raws else [] + + def zone_to_dict(self, zone): + return dict( + id=zone.id, + name=zone.name, + number_of_record_sets=zone.number_of_record_sets, + max_number_of_record_sets=zone.max_number_of_record_sets, + name_servers=zone.name_servers, + tags=zone.tags, + type=zone.zone_type.value.lower(), + registration_virtual_networks=[to_native(x.id) for x in zone.registration_virtual_networks] if zone.registration_virtual_networks else None, + resolution_virtual_networks=[to_native(x.id) for x in zone.resolution_virtual_networks] if zone.resolution_virtual_networks else None + ) + + +def main(): + AzureRMDNSZoneInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_functionapp_info.py b/library/azure_rm_functionapp_info.py new file mode 100644 index 0000000..0cd5b6f --- /dev/null +++ b/library/azure_rm_functionapp_info.py @@ -0,0 +1,206 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Thomas Stringer, + +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_functionapp_info +version_added: "2.9" +short_description: Get Azure Function App facts +description: + - Get facts for one Azure Function App or all Function Apps within a resource group. +options: + name: + description: + - Only show results for a specific Function App. + resource_group: + description: + - Limit results to a resource group. Required when filtering by name. + aliases: + - resource_group_name + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Thomas Stringer (@trstringer) +''' + +EXAMPLES = ''' + - name: Get facts for one Function App + azure_rm_functionapp_info: + resource_group: myResourceGroup + name: myfunctionapp + + - name: Get facts for all Function Apps in a resource group + azure_rm_functionapp_info: + resource_group: myResourceGroup + + - name: Get facts for all Function Apps by tags + azure_rm_functionapp_info: + tags: + - testing +''' + +RETURN = ''' +azure_functionapps: + description: + - List of Azure Function Apps dicts. + returned: always + type: list + example: + id: /subscriptions/.../resourceGroups/ansible-rg/providers/Microsoft.Web/sites/myfunctionapp + name: myfunctionapp + kind: functionapp + location: East US + type: Microsoft.Web/sites + state: Running + host_names: + - myfunctionapp.azurewebsites.net + repository_site_name: myfunctionapp + usage_state: Normal + enabled: true + enabled_host_names: + - myfunctionapp.azurewebsites.net + - myfunctionapp.scm.azurewebsites.net + availability_state: Normal + host_name_ssl_states: + - name: myfunctionapp.azurewebsites.net + ssl_state: Disabled + host_type: Standard + - name: myfunctionapp.scm.azurewebsites.net + ssl_state: Disabled + host_type: Repository + server_farm_id: /subscriptions/.../resourceGroups/ansible-rg/providers/Microsoft.Web/serverfarms/EastUSPlan + reserved: false + last_modified_time_utc: 2017-08-22T18:54:01.190Z + scm_site_also_stopped: false + client_affinity_enabled: true + client_cert_enabled: false + host_names_disabled: false + outbound_ip_addresses: ............ + container_size: 1536 + daily_memory_time_quota: 0 + resource_group: myResourceGroup + default_host_name: myfunctionapp.azurewebsites.net +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +class AzureRMFunctionAppInfo(AzureRMModuleBase): + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str', aliases=['resource_group_name']), + tags=dict(type='list'), + ) + + self.results = dict( + changed=False, + ansible_info=dict(azure_functionapps=[]) + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMFunctionAppInfo, self).__init__( + self.module_arg_spec, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_functionapp_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_functionapp_facts' module has been renamed to 'azure_rm_functionapp_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if self.name: + self.results['ansible_info']['azure_functionapps'] = self.get_functionapp() + elif self.resource_group: + self.results['ansible_info']['azure_functionapps'] = self.list_resource_group() + else: + self.results['ansible_info']['azure_functionapps'] = self.list_all() + + return self.results + + def get_functionapp(self): + self.log('Get properties for Function App {0}'.format(self.name)) + function_app = None + result = [] + + try: + function_app = self.web_client.web_apps.get( + self.resource_group, + self.name + ) + except CloudError: + pass + + if function_app and self.has_tags(function_app.tags, self.tags): + result = function_app.as_dict() + + return [result] + + def list_resource_group(self): + self.log('List items') + try: + response = self.web_client.web_apps.list_by_resource_group(self.resource_group) + except Exception as exc: + self.fail("Error listing for resource group {0} - {1}".format(self.resource_group, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item.as_dict()) + return results + + def list_all(self): + self.log('List all items') + try: + response = self.web_client.web_apps.list_by_resource_group(self.resource_group) + except Exception as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item.as_dict()) + return results + + +def main(): + AzureRMFunctionAppInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_galleryimageversion.py b/library/azure_rm_galleryimageversion.py index b731d46..1235b97 100644 --- a/library/azure_rm_galleryimageversion.py +++ b/library/azure_rm_galleryimageversion.py @@ -84,7 +84,10 @@ options: managed_image: description: - Managed image reference, could be resource id, or dictionary containing C(resource_group) and C(name) - required: true + type: raw + snapshot: + description: + - Source snapshot to be used. type: raw replica_count: description: @@ -243,6 +246,13 @@ class AzureRMGalleryImageVersions(AzureRMModuleBaseExt): '/images/{name}'), disposition='source/managedImage/id' ), + snapshot=dict( + type='raw', + pattern=('/subscriptions/{subscription_id}/resourceGroups' + '/{resource_group}/providers/Microsoft.Compute' + '/snapshots/{name}'), + disposition='source/managedImage/id' + ), replica_count=dict( type='int', disposition='replicaCount' @@ -353,6 +363,10 @@ class AzureRMGalleryImageVersions(AzureRMModuleBaseExt): if not self.default_compare(modifiers, self.body, old_response, '', self.results): self.to_do = Actions.Update + # fix leftovers (if empty structures were left) + self.body.get('properties', {}).get('publishingProfile', {}).pop('snapshot', None) + self.body.get('properties', {}).get('publishingProfile', {}).pop('managed_image', None) + if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): self.log('Need to Create / Update the GalleryImageVersion instance') diff --git a/library/azure_rm_hdinsightcluster_info.py b/library/azure_rm_hdinsightcluster_info.py new file mode 100644 index 0000000..9a703e9 --- /dev/null +++ b/library/azure_rm_hdinsightcluster_info.py @@ -0,0 +1,321 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_hdinsightcluster_info +version_added: "2.9" +short_description: Get Azure HDInsight Cluster facts +description: + - Get facts of Azure HDInsight Cluster. + +options: + resource_group: + description: + - Name of an Azure resource group. + name: + description: + - HDInsight cluster name. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of HDInsight Cluster + azure_rm_hdinsightcluster_info: + resource_group: myResourceGroup + name: myCluster + + - name: List instances of HDInsight Cluster + azure_rm_hdinsightcluster_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +clusters: + description: + - A list of dictionaries containing facts for HDInsight Cluster. + returned: always + type: complex + contains: + id: + description: + - The unique resource identifier of the HDInsight Cluster. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.HDInsight/clusters/myCluster" + resource_group: + description: + - Name of an Azure resource group. + returned: always + type: str + sample: myResourceGroup + name: + description: + - The name of the HDInsight Cluster. + returned: always + type: str + sample: testaccount + location: + description: + - The location of the resource group to which the resource belongs. + returned: always + type: str + sample: westus + cluster_version: + description: + - The version of the cluster. + returned: always + type: str + sample: 3.6.1000.67 + os_type: + description: + - The type of operating system. + returned: always + type: str + sample: linux + tier: + description: + - The cluster tier. + returned: always + type: str + sample: standard + cluster_definition: + description: + - The cluster definition. + contains: + kind: + description: + - The type of cluster. + returned: always + type: str + sample: spark + compute_profile_roles: + description: + - The list of roles in the cluster. + type: list + suboptions: + name: + description: + - The name of the role. + returned: always + type: str + sample: headnode + target_instance_count: + description: + - The instance count of the cluster. + returned: always + type: int + sample: 2 + vm_size: + description: + - The size of the VM. + returned: always + type: str + sample: Standard_D3 + linux_profile: + description: + - The Linux OS profile. + contains: + username: + description: + - User name. + returned: always + type: str + sample: myuser + connectivity_endpoints: + description: + - Cluster's connectivity endpoints. + type: list + contains: + location: + description: + - Endpoint location. + returned: always + type: str + sample: myCluster-ssh.azurehdinsight.net + name: + description: + - Endpoint name. + returned: always + type: str + sample: SSH + port: + description: + - Endpoint port. + returned: always + type: int + sample: 22 + protocol: + description: + - Endpoint protocol. + returned: always + type: str + sample: TCP + tags: + description: + - The tags of the resource. + returned: always + type: complex + sample: {} +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import _camel_to_snake + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.hdinsight import HDInsightManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMHDInsightclusterInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str' + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.name = None + self.tags = None + + super(AzureRMHDInsightclusterInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_hdinsightcluster_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_hdinsightcluster_facts' module has been renamed to 'azure_rm_hdinsightcluster_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(HDInsightManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name is not None: + self.results['clusters'] = self.get() + elif self.resource_group is not None: + self.results['clusters'] = self.list_by_resource_group() + else: + self.results['clusters'] = self.list_all() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.clusters.get(resource_group_name=self.resource_group, + cluster_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for HDInsight Cluster.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.mgmt_client.clusters.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for HDInsight Cluster.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def list_all(self): + response = None + results = [] + try: + response = self.mgmt_client.clusters.list() + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for HDInsight Cluster.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id'), + 'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'), + 'name': d.get('name', None), + 'location': d.get('location', '').replace(' ', '').lower(), + + 'cluster_version': d.get('properties', {}).get('cluster_version'), + 'os_type': d.get('properties', {}).get('os_type'), + 'tier': d.get('properties', {}).get('tier'), + 'cluster_definition': { + 'kind': d.get('properties', {}).get('cluster_definition', {}).get('kind') + }, + 'compute_profile_roles': [{ + 'name': item.get('name'), + 'target_instance_count': item.get('target_instance_count'), + 'vm_size': item.get('hardware_profile', {}).get('vm_size'), + 'linux_profile': { + 'username': item.get('os_profile', {}).get('linux_operating_system_profile', {}).get('username') + } + } for item in d.get('properties', []).get('compute_profile', {}).get('roles', [])], + 'connectivity_endpoints': d.get('properties', {}).get('connectivity_endpoints'), + 'tags': d.get('tags', None) + } + + return d + + +def main(): + AzureRMHDInsightclusterInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_image_info.py b/library/azure_rm_image_info.py new file mode 100644 index 0000000..10a53f2 --- /dev/null +++ b/library/azure_rm_image_info.py @@ -0,0 +1,307 @@ +#!/usr/bin/python +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_image_info + +version_added: "2.9" + +short_description: Get facts about azure custom images + +description: + - List azure custom images. The images can be listed where scope of listing can be based on subscription, resource group, name or tags. + +options: + resource_group: + description: + - Name of resource group. + name: + description: + - Name of the image to filter from existing images. + tags: + description: + - List of tags to be matched. + +extends_documentation_fragment: + - azure + +author: + - Madhura Naniwadekar (@Madhura-CSI) +''' + + +EXAMPLES = ''' +- name: List images with name + azure_rm_image_info: + name: test-image + resource_group: myResourceGroup + +- name: List images by resource group + azure_rm_image_info: + resource_group: myResourceGroup + tags: + - testing + - foo:bar + +- name: List all available images under current subscription + azure_rm_image_info: +''' + + +RETURN = ''' +images: + description: + - List of image dicts. + returned: always + type: complex + contains: + id: + description: + - Id of the image. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/xx + name: + description: + - Name of the image. + returned: always + type: str + resource_group: + description: + - Resource group of the image. + returned: always + type: str + sample: myResourceGroup + location: + description: + - Location of the image. + returned: always + type: str + os_disk: + description: + - Id of os disk for image. + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/xx + os_disk_caching: + description: + - Specifies caching requirements for the image. + returned: always + type: str + os_state: + description: + - Specifies image operating system state. Possible values are C(Generalized) or C(Specialized). + returned: always + type: str + sample: Generalized + os_storage_account_type: + description: + - Specifies the storage account type for the managed disk. + type: str + sample: Standard_LRS + os_type: + description: + - Type of OS for image. + returned: always + type: str + sample: Linux + provisioning_state: + description: + - State of image. + returned: always + type: str + sample: Succeeded + source: + description: + - Resource id of source VM from which the image is created. + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/xx + tags: + description: + - Dictionary of tags associated with the image. + type: complex + data_disks: + description: + - List of data disks associated with the image. + type: complex + returned: always + contains: + caching: + description: + - Type of caching of data disk. + sample: read_only + disk_size_gb: + description: + - Specifies the size of empty data disks in gigabytes. + returned: always + type: int + sample: 50 + lun: + description: + - Specifies the logical unit number of the data disk. + returned: always + type: int + sample: 0 + storage_account_type: + description: + - Specifies the storage account type for the managed disk data disk. + type: str + sample: Standard_LRS + managed_disk_id: + description: + - Id of managed disk. + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/xx + blob_uri: + description: + - The virtual hard disk. +''' + + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] + + +class AzureRMImageInfo(AzureRMModuleBase): + + def __init__(self, **kwargs): + + self.module_arg_spec = dict( + resource_group=dict(type='str'), + name=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False + ) + + self.resource_group = None + self.name = None + self.format = None + self.tags = None + + super(AzureRMImageInfo, self).__init__( + derived_arg_spec=self.module_arg_spec, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_image_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_image_facts' module has been renamed to 'azure_rm_image_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and self.resource_group: + self.results['images'] = self.get_image(self.resource_group, self.name) + elif self.name and not self.resource_group: + self.results['images'] = self.list_images(self.name) + elif not self.name and self.resource_group: + self.results['images'] = self.list_images_by_resource_group(self.resource_group) + elif not self.name and not self.resource_group: + self.results['images'] = self.list_images() + return self.results + + def get_image(self, resource_group, image_name): + ''' + Returns image details based on its name + ''' + + self.log('Get properties for {0}'.format(self.name)) + + result = [] + item = None + try: + item = self.compute_client.images.get(resource_group, image_name) + except CloudError as exc: + self.fail('Failed to list images - {0}'.format(str(exc))) + + result = [self.format_item(item)] + return result + + def list_images_by_resource_group(self, resource_group): + ''' + Returns image details based on its resource group + ''' + + self.log('List images filtered by resource group') + response = None + try: + response = self.compute_client.images.list_by_resource_group(resource_group) + except CloudError as exc: + self.fail("Failed to list images: {0}".format(str(exc))) + + return [self.format_item(x) for x in response if self.has_tags(x.tags, self.tags)] if response else [] + + def list_images(self, image_name=None): + ''' + Returns image details in current subscription + ''' + + self.log('List images within current subscription') + response = None + results = [] + try: + response = self.compute_client.images.list() + except CloudError as exc: + self.fail("Failed to list all images: {0}".format(str(exc))) + + results = [self.format_item(x) for x in response if self.has_tags(x.tags, self.tags)] if response else [] + if image_name: + results = [result for result in results if result['name'] == image_name] + return results + + def format_item(self, item): + d = item.as_dict() + + for data_disk in d['storage_profile']['data_disks']: + if 'managed_disk' in data_disk.keys(): + data_disk['managed_disk_id'] = data_disk['managed_disk']['id'] + data_disk.pop('managed_disk', None) + + d = { + 'id': d['id'], + 'resource_group': d['id'].split('/')[4], + 'name': d['name'], + 'location': d['location'], + 'tags': d.get('tags'), + 'source': d['source_virtual_machine']['id'] if 'source_virtual_machine' in d.keys() else None, + 'os_type': d['storage_profile']['os_disk']['os_type'], + 'os_state': d['storage_profile']['os_disk']['os_state'], + 'os_disk_caching': d['storage_profile']['os_disk']['caching'], + 'os_storage_account_type': d['storage_profile']['os_disk']['storage_account_type'], + 'os_disk': d['storage_profile']['os_disk']['managed_disk']['id'] if 'managed_disk' in d['storage_profile']['os_disk'].keys() else None, + 'os_blob_uri': d['storage_profile']['os_disk']['blob_uri'] if 'blob_uri' in d['storage_profile']['os_disk'].keys() else None, + 'provisioning_state': d['provisioning_state'], + 'data_disks': d['storage_profile']['data_disks'] + } + return d + + +def main(): + AzureRMImageInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_loadbalancer_info.py b/library/azure_rm_loadbalancer_info.py new file mode 100644 index 0000000..af4507c --- /dev/null +++ b/library/azure_rm_loadbalancer_info.py @@ -0,0 +1,177 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2016, Thomas Stringer +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +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_loadbalancer_info + +version_added: "2.9" + +short_description: Get load balancer facts + +description: + - Get facts for a specific load balancer or all load balancers. + +options: + name: + description: + - Limit results to a specific resource group. + resource_group: + description: + - The resource group to search for the desired load balancer. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Thomas Stringer (@trstringer) +''' + +EXAMPLES = ''' + - name: Get facts for one load balancer + azure_rm_loadbalancer_info: + name: Testing + resource_group: myResourceGroup + + - name: Get facts for all load balancers + azure_rm_loadbalancer_info: + + - name: Get facts for all load balancers in a specific resource group + azure_rm_loadbalancer_info: + resource_group: myResourceGroup + + - name: Get facts by tags + azure_rm_loadbalancer_info: + tags: + - testing +''' + +RETURN = ''' +azure_loadbalancers: + description: + - List of load balancer dicts. + returned: always + type: list +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureHttpError +except Exception: + # handled in azure_rm_common + pass + +AZURE_OBJECT_CLASS = 'LoadBalancer' + + +class AzureRMLoadBalancerInfo(AzureRMModuleBase): + """Utility class to get load balancer facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + ansible_info=dict( + azure_loadbalancers=[] + ) + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMLoadBalancerInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_loadbalancer_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_loadbalancer_facts' module has been renamed to 'azure_rm_loadbalancer_info'", version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + self.results['ansible_info']['azure_loadbalancers'] = ( + self.get_item() if self.name + else self.list_items() + ) + + return self.results + + def get_item(self): + """Get a single load balancer""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self.network_client.load_balancers.get(self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [self.serialize_obj(item, AZURE_OBJECT_CLASS)] + + return result + + def list_items(self): + """Get all load balancers""" + + self.log('List all load balancers') + + if self.resource_group: + try: + response = self.network_client.load_balancers.list(self.resource_group) + except AzureHttpError as exc: + self.fail('Failed to list items in resource group {0} - {1}'.format(self.resource_group, str(exc))) + else: + try: + response = self.network_client.load_balancers.list_all() + except AzureHttpError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_obj(item, AZURE_OBJECT_CLASS)) + + return results + + +def main(): + """Main module execution code path""" + + AzureRMLoadBalancerInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_lock_info.py b/library/azure_rm_lock_info.py new file mode 100644 index 0000000..cf8c1d1 --- /dev/null +++ b/library/azure_rm_lock_info.py @@ -0,0 +1,223 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Yuwei Zhou, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_lock_info +version_added: "2.9" +short_description: Manage Azure locks +description: + - Create, delete an Azure lock. +options: + name: + description: + - Name of the lock. + type: str + required: true + managed_resource_id: + description: + - ID of the resource where need to manage the lock. + - Get this via facts module. + - Cannot be set mutal with I(resource_group). + - Manage subscription if both I(managed_resource_id) and I(resource_group) not defined. + - "'/subscriptions/{subscriptionId}' for subscriptions." + - "'/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups." + - "'/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{namespace}/{resourceType}/{resourceName}' for resources." + - Can get all locks with 'child scope' for this resource, use I(managed_resource_id) in response for further management. + type: str + resource_group: + description: + - Resource group name where need to manage the lock. + - The lock is in the resource group level. + - Cannot be set mutal with I(managed_resource_id). + - Query subscription if both I(managed_resource_id) and I(resource_group) not defined. + - Can get all locks with 'child scope' in this resource group, use the I(managed_resource_id) in response for further management. + type: str + +extends_documentation_fragment: + - azure + +author: + - Yuwei Zhou (@yuwzho) + +''' + +EXAMPLES = ''' +- name: Get myLock details of myVM + azure_rm_lock_info: + name: myLock + managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM + +- name: List locks of myVM + azure_rm_lock_info: + managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM + +- name: List locks of myResourceGroup + azure_rm_lock_info: + resource_group: myResourceGroup + +- name: List locks of myResourceGroup + azure_rm_lock_info: + managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup + +- name: List locks of mySubscription + azure_rm_lock_info: + +- name: List locks of mySubscription + azure_rm_lock_info: + managed_resource_id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +''' + +RETURN = ''' +locks: + description: + - List of locks dicts. + returned: always + type: complex + contains: + id: + description: + - ID of the Lock. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Authorization/locks/myLock" + name: + description: + - Name of the lock. + returned: always + type: str + sample: myLock + level: + description: + - Type level of the lock. + returned: always + type: str + sample: can_not_delete + notes: + description: + - Notes of the lock added by creator. + returned: always + type: str + sample: "This is a lock" +''' # NOQA + +import json +import re +from ansible.module_utils.common.dict_transformations import _camel_to_snake +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.azure_rm_common_rest import GenericRestClient + +try: + from msrestazure.azure_exceptions import CloudError +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMLockInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + managed_resource_id=dict(type='str') + ) + + self.results = dict( + changed=False, + locks=[] + ) + + mutually_exclusive = [['resource_group', 'managed_resource_id']] + + self.name = None + self.resource_group = None + self.managed_resource_id = None + self._mgmt_client = None + self._query_parameters = {'api-version': '2016-09-01'} + self._header_parameters = {'Content-Type': 'application/json; charset=utf-8'} + + super(AzureRMLockInfo, self).__init__(self.module_arg_spec, facts_module=True, mutually_exclusive=mutually_exclusive, supports_tags=False) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_lock_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_lock_facts' module has been renamed to 'azure_rm_lock_info'", version='2.13') + + for key in self.module_arg_spec.keys(): + setattr(self, key, kwargs[key]) + + self._mgmt_client = self.get_mgmt_svc_client(GenericRestClient, base_url=self._cloud_environment.endpoints.resource_manager) + changed = False + # construct scope id + scope = self.get_scope() + url = '/{0}/providers/Microsoft.Authorization/locks'.format(scope) + if self.name: + url = '{0}/{1}'.format(url, self.name) + locks = self.list_locks(url) + resp = locks.get('value') if 'value' in locks else [locks] + self.results['locks'] = [self.to_dict(x) for x in resp] + return self.results + + def to_dict(self, lock): + resp = dict( + id=lock['id'], + name=lock['name'], + level=_camel_to_snake(lock['properties']['level']), + managed_resource_id=re.sub('/providers/Microsoft.Authorization/locks/.+', '', lock['id']) + ) + if lock['properties'].get('notes'): + resp['notes'] = lock['properties']['notes'] + if lock['properties'].get('owners'): + resp['owners'] = [x['application_id'] for x in lock['properties']['owners']] + return resp + + def list_locks(self, url): + try: + resp = self._mgmt_client.query(url=url, + method='GET', + query_parameters=self._query_parameters, + header_parameters=self._header_parameters, + body=None, + expected_status_codes=[200], + polling_timeout=None, + polling_interval=None) + return json.loads(resp.text) + except CloudError as exc: + self.fail('Error when finding locks {0}: {1}'.format(url, exc.message)) + + def get_scope(self): + ''' + Get the resource scope of the lock management. + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{namespace}/{resourceType}/{resourceName}' for resources. + ''' + if self.managed_resource_id: + return self.managed_resource_id + elif self.resource_group: + return '/subscriptions/{0}/resourcegroups/{1}'.format(self.subscription_id, self.resource_group) + else: + return '/subscriptions/{0}'.format(self.subscription_id) + + +def main(): + AzureRMLockInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_loganalyticsworkspace_info.py b/library/azure_rm_loganalyticsworkspace_info.py new file mode 100644 index 0000000..03f841e --- /dev/null +++ b/library/azure_rm_loganalyticsworkspace_info.py @@ -0,0 +1,269 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Yuwei Zhou, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_loganalyticsworkspace_info +version_added: "2.9" +short_description: Get facts of Azure Log Analytics workspaces +description: + - Get, query Azure Log Analytics workspaces. +options: + resource_group: + description: + - Name of resource group. + required: True + name: + description: + - Name of the workspace. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + show_intelligence_packs: + description: + - Show the intelligence packs for a workspace. + - Note this will cost one more network overhead for each workspace, expected slow response. + show_management_groups: + description: + - Show the management groups for a workspace. + - Note this will cost one more network overhead for each workspace, expected slow response. + show_shared_keys: + description: + - Show the shared keys for a workspace. + - Note this will cost one more network overhead for each workspace, expected slow response. + show_usages: + description: + - Show the list of usages for a workspace. + - Note this will cost one more network overhead for each workspace, expected slow response. +extends_documentation_fragment: + - azure + +author: + - Yuwei Zhou (@yuwzho) + +''' + +EXAMPLES = ''' +- name: Query a workspace + azure_rm_loganalyticsworkspace_info: + resource_group: myResourceGroup + name: myLogAnalyticsWorkspace + show_intelligence_packs: true + show_management_groups: true + show_shared_keys: true + show_usages: true +''' + +RETURN = ''' +id: + description: + - Workspace resource path. + type: str + returned: success + example: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.OperationalInsights/workspaces/m + yLogAnalyticsWorkspace" +location: + description: + - Resource location. + type: str + returned: success + example: "eastus" +sku: + description: + - The SKU of the workspace. + type: str + returned: success + example: "per_gb2018" +retention_in_days: + description: + - The workspace data retention in days. + - -1 means Unlimited retention for I(sku=unlimited). + - 730 days is the maximum allowed for all other SKUs. + type: int + returned: success + example: 40 +intelligence_packs: + description: + - Lists all the intelligence packs possible and whether they are enabled or disabled for a given workspace. + type: list + returned: success + example: [ {'name': 'CapacityPerformance', 'enabled': true} ] +management_groups: + description: + - Management groups connected to the workspace. + type: dict + returned: success + example: {'value': []} +shared_keys: + description: + - Shared keys for the workspace. + type: dict + returned: success + example: { + 'primarySharedKey': 'BozLY1JnZbxu0jWUQSY8iRPEM8ObmpP8rW+8bUl3+HpDJI+n689SxXgTgU7k1qdxo/WugRLxechxbolAfHM5uA==', + 'secondarySharedKey': '7tDt5W0JBrCQKtQA3igfFltLSzJeyr9LmuT+B/ibzd8cdC1neZ1ePOQLBx5NUzc0q2VUIK0cLhWNyFvo/hT8Ww==' + } +usages: + description: + - Usage metrics for the workspace. + type: dict + returned: success + example: { + 'value': [ + { + 'name': { + 'value': 'DataAnalyzed', + 'localizedValue': 'Data Analyzed' + }, + 'unit': 'Bytes', + 'currentValue': 0, + 'limit': 524288000, + 'nextResetTime': '2017-10-03T00:00:00Z', + 'quotaPeriod': 'P1D' + } + ] + } +''' # NOQA + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase, format_resource_id +from ansible.module_utils.common.dict_transformations import _snake_to_camel, _camel_to_snake + +try: + from msrestazure.tools import parse_resource_id + from msrestazure.azure_exceptions import CloudError +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMLogAnalyticsWorkspaceInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + resource_group=dict(type='str', required=True), + name=dict(type='str'), + tags=dict(type='list'), + show_shared_keys=dict(type='bool'), + show_intelligence_packs=dict(type='bool'), + show_usages=dict(type='bool'), + show_management_groups=dict(type='bool') + ) + + self.results = dict( + changed=False, + workspaces=[] + ) + + self.resource_group = None + self.name = None + self.tags = None + self.show_intelligence_packs = None + self.show_shared_keys = None + self.show_usages = None + self.show_management_groups = None + + super(AzureRMLogAnalyticsWorkspaceInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_loganalyticsworkspace_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_loganalyticsworkspace_facts' module has been renamed to 'azure_rm_loganalyticsworkspace_info'", + version='2.13') + + for key in list(self.module_arg_spec.keys()): + setattr(self, key, kwargs[key]) + + if self.name: + item = self.get_workspace() + response = [item] if item else [] + else: + response = self.list_by_resource_group() + + self.results['workspaces'] = [self.to_dict(x) for x in response if self.has_tags(x.tags, self.tags)] + return self.results + + def get_workspace(self): + try: + return self.log_analytics_client.workspaces.get(self.resource_group, self.name) + except CloudError: + pass + return None + + def list_by_resource_group(self): + try: + return self.log_analytics_client.workspaces.list_by_resource_group(self.resource_group) + except CloudError: + pass + return [] + + def list_intelligence_packs(self): + try: + response = self.log_analytics_client.workspaces.list_intelligence_packs(self.resource_group, self.name) + return [x.as_dict() for x in response] + except CloudError as exc: + self.fail('Error when listing intelligence packs {0}'.format(exc.message or str(exc))) + + def list_management_groups(self): + result = [] + try: + response = self.log_analytics_client.workspaces.list_management_groups(self.resource_group, self.name) + while True: + result.append(response.next().as_dict()) + except StopIteration: + pass + except CloudError as exc: + self.fail('Error when listing management groups {0}'.format(exc.message or str(exc))) + return result + + def list_usages(self): + result = [] + try: + response = self.log_analytics_client.workspaces.list_usages(self.resource_group, self.name) + while True: + result.append(response.next().as_dict()) + except StopIteration: + pass + except CloudError as exc: + self.fail('Error when listing usages {0}'.format(exc.message or str(exc))) + return result + + def get_shared_keys(self): + try: + return self.log_analytics_client.workspaces.get_shared_keys(self.resource_group, self.name).as_dict() + except CloudError as exc: + self.fail('Error when getting shared key {0}'.format(exc.message or str(exc))) + + def to_dict(self, workspace): + result = workspace.as_dict() + result['sku'] = _camel_to_snake(workspace.sku.name) + if self.show_intelligence_packs: + result['intelligence_packs'] = self.list_intelligence_packs() + if self.show_management_groups: + result['management_groups'] = self.list_management_groups() + if self.show_shared_keys: + result['shared_keys'] = self.get_shared_keys() + if self.show_usages: + result['usages'] = self.list_usages() + return result + + +def main(): + AzureRMLogAnalyticsWorkspaceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_manageddisk_info.py b/library/azure_rm_manageddisk_info.py new file mode 100644 index 0000000..cc90cb9 --- /dev/null +++ b/library/azure_rm_manageddisk_info.py @@ -0,0 +1,243 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2016, Bruno Medina Bolanos Cacho +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = r''' +--- +module: azure_rm_manageddisk_info + +version_added: "2.9" + +short_description: Get managed disk facts + +description: + - Get facts for a specific managed disk or all managed disks. + +notes: + - This module was called M(azure_rm_managed_disk_facts) before Ansible 2.8. The usage did not change. + +options: + name: + description: + - Limit results to a specific managed disk. + type: str + resource_group: + description: + - Limit results to a specific resource group. + type: str + tags: + description: + - Limit results by providing a list of tags. + - Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + - azure_tags + +author: + - Bruno Medina (@brusMX) +''' + +EXAMPLES = r''' +- name: Get facts for one managed disk + azure_rm_manageddisk_info: + name: Testing + resource_group: myResourceGroup + +- name: Get facts for all managed disks + azure_rm_manageddisk_info: + +- name: Get facts by tags + azure_rm_manageddisk_info: + tags: + - testing +''' + +RETURN = r''' +azure_managed_disk: + description: + - List of managed disk dicts. + returned: always + type: list + contains: + id: + description: + - Resource id. + type: str + name: + description: + - Name of the managed disk. + type: str + location: + description: + - Valid Azure location. + type: str + storage_account_type: + description: + - Type of storage for the managed disk. + - See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about this type. + type: str + sample: Standard_LRS + create_option: + description: + - Create option of the disk. + type: str + sample: copy + source_uri: + description: + - URI to a valid VHD file to be used or the resource ID of the managed disk to copy. + type: str + os_type: + description: + - Type of Operating System. + choices: + - linux + - windows + type: str + disk_size_gb: + description: + - Size in GB of the managed disk to be created. + type: str + managed_by: + description: + - Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group. + type: str + tags: + description: + - Tags to assign to the managed disk. + type: dict + sample: { "tag": "value" } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # handled in azure_rm_common + pass + + +# duplicated in azure_rm_manageddisk +def managed_disk_to_dict(managed_disk): + create_data = managed_disk.creation_data + return dict( + id=managed_disk.id, + name=managed_disk.name, + location=managed_disk.location, + tags=managed_disk.tags, + create_option=create_data.create_option.lower(), + source_uri=create_data.source_uri or create_data.source_resource_id, + disk_size_gb=managed_disk.disk_size_gb, + os_type=managed_disk.os_type.lower() if managed_disk.os_type else None, + storage_account_type=managed_disk.sku.name if managed_disk.sku else None, + managed_by=managed_disk.managed_by, + zone=managed_disk.zones[0] if managed_disk.zones and len(managed_disk.zones) > 0 else '' + ) + + +class AzureRMManagedDiskInfo(AzureRMModuleBase): + """Utility class to get managed disk facts""" + + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str' + ), + name=dict( + type='str' + ), + tags=dict( + type='str' + ), + ) + self.results = dict( + ansible_info=dict( + azure_managed_disk=[] + ) + ) + self.resource_group = None + self.name = None + self.create_option = None + self.source_uri = None + self.source_resource_uri = None + self.tags = None + super(AzureRMManagedDiskInfo, self).__init__( + derived_arg_spec=self.module_arg_spec, + supports_check_mode=True, + supports_tags=True) + + def exec_module(self, **kwargs): + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + self.results['ansible_info']['azure_managed_disk'] = ( + self.get_item() if self.name + else (self.list_items_by_resource_group() if self.resource_group else self.list_items()) + ) + + return self.results + + def get_item(self): + """Get a single managed disk""" + item = None + result = [] + + try: + item = self.compute_client.disks.get( + self.resource_group, + self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [managed_disk_to_dict(item)] + + return result + + def list_items(self): + """Get all managed disks""" + try: + response = self.compute_client.disks.list() + except CloudError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(managed_disk_to_dict(item)) + return results + + def list_items_by_resource_group(self): + """Get managed disks in a resource group""" + try: + response = self.compute_client.disks.list_by_resource_group(resource_group_name=self.resource_group) + except CloudError as exc: + self.fail('Failed to list items by resource group - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(managed_disk_to_dict(item)) + return results + + +def main(): + """Main module execution code path""" + + AzureRMManagedDiskInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mariadbconfiguration_info.py b/library/azure_rm_mariadbconfiguration_info.py new file mode 100644 index 0000000..ad38f12 --- /dev/null +++ b/library/azure_rm_mariadbconfiguration_info.py @@ -0,0 +1,216 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mariadbconfiguration_info +version_added: "2.9" +short_description: Get Azure MariaDB Configuration facts +description: + - Get facts of Azure MariaDB Configuration. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - Setting name. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + - Matti Ranta (@techknowlogick) + +''' + +EXAMPLES = ''' + - name: Get specific setting of MariaDB Server + azure_rm_mariadbconfiguration_info: + resource_group: myResourceGroup + server_name: testserver + name: deadlock_timeout + + - name: Get all settings of MariaDB Server + azure_rm_mariadbconfiguration_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +settings: + description: + - A list of dictionaries containing MariaDB Server settings. + returned: always + type: complex + contains: + id: + description: + - Setting resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testserver + /configurations/deadlock_timeout" + name: + description: + - Setting name. + returned: always + type: str + sample: deadlock_timeout + value: + description: + - Setting value. + returned: always + type: raw + sample: 1000 + description: + description: + - Description of the configuration. + returned: always + type: str + sample: Deadlock timeout. + source: + description: + - Source of the configuration. + returned: always + type: str + sample: system-default +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMariaDbConfigurationInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict(changed=False) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMariaDbConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbconfiguration_facts' module has been renamed to 'azure_rm_mariadbconfiguration_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(MariaDBManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name is not None: + self.results['settings'] = self.get() + else: + self.results['settings'] = self.list_by_server() + return self.results + + def get(self): + ''' + Gets facts of the specified MariaDB Configuration. + + :return: deserialized MariaDB Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.get(resource_group_name=self.resource_group, + server_name=self.server_name, + configuration_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Configurations.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + ''' + Gets facts of the specified MariaDB Configuration. + + :return: deserialized MariaDB Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Configurations.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'id': d['id'], + 'name': d['name'], + 'value': d['value'], + 'description': d['description'], + 'source': d['source'] + } + return d + + +def main(): + AzureRMMariaDbConfigurationInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mariadbdatabase_info.py b/library/azure_rm_mariadbdatabase_info.py new file mode 100644 index 0000000..61e3301 --- /dev/null +++ b/library/azure_rm_mariadbdatabase_info.py @@ -0,0 +1,211 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mariadbdatabase_info +version_added: "2.9" +short_description: Get Azure MariaDB Database facts +description: + - Get facts of MariaDB Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the database. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + - Matti Ranta (@techknowlogick) + +''' + +EXAMPLES = ''' + - name: Get instance of MariaDB Database + azure_rm_mariadbdatabase_info: + resource_group: myResourceGroup + server_name: server_name + name: database_name + + - name: List instances of MariaDB Database + azure_rm_mariadbdatabase_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +databases: + description: + - A list of dictionaries containing facts for MariaDB Databases. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testser + ver/databases/db1" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: testrg + server_name: + description: + - Server name. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: db1 + charset: + description: + - The charset of the database. + returned: always + type: str + sample: UTF8 + collation: + description: + - The collation of the database. + returned: always + type: str + sample: English_United States.1252 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMariaDbDatabaseInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMariaDbDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbdatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbdatabase_facts' module has been renamed to 'azure_rm_mariadbdatabase_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.server_name is not None and + self.name is not None): + self.results['databases'] = self.get() + elif (self.resource_group is not None and + self.server_name is not None): + self.results['databases'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mariadb_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Databases.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mariadb_client.databases.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'name': d['name'], + 'charset': d['charset'], + 'collation': d['collation'] + } + return d + + +def main(): + AzureRMMariaDbDatabaseInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mariadbfirewallrule_info.py b/library/azure_rm_mariadbfirewallrule_info.py new file mode 100644 index 0000000..45557b5 --- /dev/null +++ b/library/azure_rm_mariadbfirewallrule_info.py @@ -0,0 +1,207 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mariadbfirewallrule_info +version_added: "2.9" +short_description: Get Azure MariaDB Firewall Rule facts +description: + - Get facts of Azure MariaDB Firewall Rule. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the server firewall rule. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + - Matti Ranta (@techknowlogick) + +''' + +EXAMPLES = ''' + - name: Get instance of MariaDB Firewall Rule + azure_rm_mariadbfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name + name: firewall_rule_name + + - name: List instances of MariaDB Firewall Rule + azure_rm_mariadbfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +rules: + description: + - A list of dictionaries containing facts for MariaDB Firewall Rule. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/TestGroup/providers/Microsoft.DBforMariaDB/servers/testserver/fire + wallRules/rule1" + server_name: + description: + - The name of the server. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: rule1 + start_ip_address: + description: + - The start IP address of the MariaDB firewall rule. + returned: always + type: str + sample: 10.0.0.16 + end_ip_address: + description: + - The end IP address of the MariaDB firewall rule. + returned: always + type: str + sample: 10.0.0.18 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMariaDbFirewallRuleInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMariaDbFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbfirewallrule_facts' module has been renamed to 'azure_rm_mariadbfirewallrule_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(MariaDBManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if (self.name is not None): + self.results['rules'] = self.get() + else: + self.results['rules'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.get(resource_group_name=self.resource_group, + server_name=self.server_name, + firewall_rule_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'id': d['id'], + 'server_name': self.server_name, + 'name': d['name'], + 'start_ip_address': d['start_ip_address'], + 'end_ip_address': d['end_ip_address'] + } + return d + + +def main(): + AzureRMMariaDbFirewallRuleInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mariadbserver_info.py b/library/azure_rm_mariadbserver_info.py new file mode 100644 index 0000000..ffe52c5 --- /dev/null +++ b/library/azure_rm_mariadbserver_info.py @@ -0,0 +1,264 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mariadbserver_info +version_added: "2.9" +short_description: Get Azure MariaDB Server facts +description: + - Get facts of MariaDB Server. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + name: + description: + - The name of the server. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + - Matti Ranta (@techknowlogick) + +''' + +EXAMPLES = ''' + - name: Get instance of MariaDB Server + azure_rm_mariadbserver_info: + resource_group: myResourceGroup + name: server_name + + - name: List instances of MariaDB Server + azure_rm_mariadbserver_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +servers: + description: + - A list of dictionaries containing facts for MariaDB servers. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/myabdud1223 + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Resource name. + returned: always + type: str + sample: myabdud1223 + location: + description: + - The location the resource resides in. + returned: always + type: str + sample: eastus + sku: + description: + - The SKU of the server. + returned: always + type: complex + contains: + name: + description: + - The name of the SKU. + returned: always + type: str + sample: GP_Gen4_2 + tier: + description: + - The tier of the particular SKU. + returned: always + type: str + sample: GeneralPurpose + capacity: + description: + - The scale capacity. + returned: always + type: int + sample: 2 + storage_mb: + description: + - The maximum storage allowed for a server. + returned: always + type: int + sample: 128000 + enforce_ssl: + description: + - Enable SSL enforcement. + returned: always + type: bool + sample: False + admin_username: + description: + - The administrator's login name of a server. + returned: always + type: str + sample: serveradmin + version: + description: + - Server version. + returned: always + type: str + sample: "9.6" + user_visible_state: + description: + - A state of a server that is visible to user. + returned: always + type: str + sample: Ready + fully_qualified_domain_name: + description: + - The fully qualified domain name of a server. + returned: always + type: str + sample: myabdud1223.mys.database.azure.com + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + type: dict + sample: { tag1: abc } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMariaDbServerInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.name = None + self.tags = None + super(AzureRMMariaDbServerInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mariadbserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mariadbserver_facts' module has been renamed to 'azure_rm_mariadbserver_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.name is not None): + self.results['servers'] = self.get() + elif (self.resource_group is not None): + self.results['servers'] = self.list_by_resource_group() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mariadb_client.servers.get(resource_group_name=self.resource_group, + server_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for MariaDB Server.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.mariadb_client.servers.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for MariaDB Servers.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'id': d['id'], + 'resource_group': self.resource_group, + 'name': d['name'], + 'sku': d['sku'], + 'location': d['location'], + 'storage_mb': d['storage_profile']['storage_mb'], + 'version': d['version'], + 'enforce_ssl': (d['ssl_enforcement'] == 'Enabled'), + 'admin_username': d['administrator_login'], + 'user_visible_state': d['user_visible_state'], + 'fully_qualified_domain_name': d['fully_qualified_domain_name'], + 'tags': d.get('tags') + } + + return d + + +def main(): + AzureRMMariaDbServerInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mysqlconfiguration_info.py b/library/azure_rm_mysqlconfiguration_info.py new file mode 100644 index 0000000..8fe9113 --- /dev/null +++ b/library/azure_rm_mysqlconfiguration_info.py @@ -0,0 +1,214 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mysqlconfiguration_info +version_added: "2.9" +short_description: Get Azure MySQL Configuration facts +description: + - Get facts of Azure MySQL Configuration. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - Setting name. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get specific setting of MySQL Server + azure_rm_mysqlconfiguration_info: + resource_group: myResourceGroup + server_name: testmysqlserver + name: deadlock_timeout + + - name: Get all settings of MySQL Server + azure_rm_mysqlconfiguration_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +settings: + description: + - A list of dictionaries containing MySQL Server settings. + returned: always + type: complex + contains: + id: + description: + - Setting resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/testmysqlser + ver/configurations/deadlock_timeout" + name: + description: + - Setting name. + returned: always + type: str + sample: deadlock_timeout + value: + description: + - Setting value. + returned: always + type: raw + sample: 1000 + description: + description: + - Description of the configuration. + returned: always + type: str + sample: Deadlock timeout. + source: + description: + - Source of the configuration. + returned: always + type: str + sample: system-default +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.rdbms.mysql import MySQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMySqlConfigurationInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict(changed=False) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMySqlConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlconfiguration_facts' module has been renamed to 'azure_rm_mysqlconfiguration_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(MySQLManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name is not None: + self.results['settings'] = self.get() + else: + self.results['settings'] = self.list_by_server() + return self.results + + def get(self): + ''' + Gets facts of the specified MySQL Configuration. + + :return: deserialized MySQL Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.get(resource_group_name=self.resource_group, + server_name=self.server_name, + configuration_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Configurations.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + ''' + Gets facts of the specified MySQL Configuration. + + :return: deserialized MySQL Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Configurations.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'id': d['id'], + 'name': d['name'], + 'value': d['value'], + 'description': d['description'], + 'source': d['source'] + } + return d + + +def main(): + AzureRMMySqlConfigurationInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mysqldatabase_info.py b/library/azure_rm_mysqldatabase_info.py new file mode 100644 index 0000000..988a417 --- /dev/null +++ b/library/azure_rm_mysqldatabase_info.py @@ -0,0 +1,209 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mysqldatabase_info +version_added: "2.9" +short_description: Get Azure MySQL Database facts +description: + - Get facts of MySQL Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the database. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of MySQL Database + azure_rm_mysqldatabase_info: + resource_group: myResourceGroup + server_name: server_name + name: database_name + + - name: List instances of MySQL Database + azure_rm_mysqldatabase_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +databases: + description: + - A list of dictionaries containing facts for MySQL Databases. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/testser + ver/databases/db1" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: testrg + server_name: + description: + - Server name. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: db1 + charset: + description: + - The charset of the database. + returned: always + type: str + sample: utf8 + collation: + description: + - The collation of the database. + returned: always + type: str + sample: English_United States.1252 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.mysql import MySQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMySqlDatabaseInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMySqlDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqldatabase_facts' module has been renamed to 'azure_rm_mysqldatabase_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.server_name is not None and + self.name is not None): + self.results['databases'] = self.get() + elif (self.resource_group is not None and + self.server_name is not None): + self.results['databases'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mysql_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Databases.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mysql_client.databases.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'name': d['name'], + 'charset': d['charset'], + 'collation': d['collation'] + } + return d + + +def main(): + AzureRMMySqlDatabaseInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mysqlfirewallrule_info.py b/library/azure_rm_mysqlfirewallrule_info.py new file mode 100644 index 0000000..9fa760e --- /dev/null +++ b/library/azure_rm_mysqlfirewallrule_info.py @@ -0,0 +1,205 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mysqlfirewallrule_info +version_added: "2.9" +short_description: Get Azure MySQL Firewall Rule facts +description: + - Get facts of Azure MySQL Firewall Rule. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the server firewall rule. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of MySQL Firewall Rule + azure_rm_mysqlfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name + name: firewall_rule_name + + - name: List instances of MySQL Firewall Rule + azure_rm_mysqlfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +rules: + description: + - A list of dictionaries containing facts for MySQL Firewall Rule. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/TestGroup/providers/Microsoft.DBforMySQL/servers/testserver/fire + wallRules/rule1" + server_name: + description: + - The name of the server. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: rule1 + start_ip_address: + description: + - The start IP address of the MySQL firewall rule. + returned: always + type: str + sample: 10.0.0.16 + end_ip_address: + description: + - The end IP address of the MySQL firewall rule. + returned: always + type: str + sample: 10.0.0.18 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.rdbms.mysql import MySQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMySqlFirewallRuleInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMySqlFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlfirewallrule_facts' module has been renamed to 'azure_rm_mysqlfirewallrule_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(MySQLManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if (self.name is not None): + self.results['rules'] = self.get() + else: + self.results['rules'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.get(resource_group_name=self.resource_group, + server_name=self.server_name, + firewall_rule_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'id': d['id'], + 'server_name': self.server_name, + 'name': d['name'], + 'start_ip_address': d['start_ip_address'], + 'end_ip_address': d['end_ip_address'] + } + return d + + +def main(): + AzureRMMySqlFirewallRuleInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_mysqlserver_info.py b/library/azure_rm_mysqlserver_info.py new file mode 100644 index 0000000..3cae238 --- /dev/null +++ b/library/azure_rm_mysqlserver_info.py @@ -0,0 +1,262 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_mysqlserver_info +version_added: "2.9" +short_description: Get Azure MySQL Server facts +description: + - Get facts of MySQL Server. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + name: + description: + - The name of the server. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of MySQL Server + azure_rm_mysqlserver_info: + resource_group: myResourceGroup + name: server_name + + - name: List instances of MySQL Server + azure_rm_mysqlserver_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +servers: + description: + - A list of dictionaries containing facts for MySQL servers. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/myabdud1223 + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Resource name. + returned: always + type: str + sample: myabdud1223 + location: + description: + - The location the resource resides in. + returned: always + type: str + sample: eastus + sku: + description: + - The SKU of the server. + returned: always + type: complex + contains: + name: + description: + - The name of the SKU. + returned: always + type: str + sample: GP_Gen4_2 + tier: + description: + - The tier of the particular SKU. + returned: always + type: str + sample: GeneralPurpose + capacity: + description: + - The scale capacity. + returned: always + type: int + sample: 2 + storage_mb: + description: + - The maximum storage allowed for a server. + returned: always + type: int + sample: 128000 + enforce_ssl: + description: + - Enable SSL enforcement. + returned: always + type: bool + sample: False + admin_username: + description: + - The administrator's login name of a server. + returned: always + type: str + sample: serveradmin + version: + description: + - Server version. + returned: always + type: str + sample: "9.6" + user_visible_state: + description: + - A state of a server that is visible to user. + returned: always + type: str + sample: Ready + fully_qualified_domain_name: + description: + - The fully qualified domain name of a server. + returned: always + type: str + sample: myabdud1223.mys.database.azure.com + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + type: dict + sample: { tag1: abc } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.mysql import MySQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMySqlServerInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.name = None + self.tags = None + super(AzureRMMySqlServerInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_mysqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_mysqlserver_facts' module has been renamed to 'azure_rm_mysqlserver_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.name is not None): + self.results['servers'] = self.get() + elif (self.resource_group is not None): + self.results['servers'] = self.list_by_resource_group() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mysql_client.servers.get(resource_group_name=self.resource_group, + server_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for MySQL Server.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.mysql_client.servers.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for MySQL Servers.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'id': d['id'], + 'resource_group': self.resource_group, + 'name': d['name'], + 'sku': d['sku'], + 'location': d['location'], + 'storage_mb': d['storage_profile']['storage_mb'], + 'version': d['version'], + 'enforce_ssl': (d['ssl_enforcement'] == 'Enabled'), + 'admin_username': d['administrator_login'], + 'user_visible_state': d['user_visible_state'], + 'fully_qualified_domain_name': d['fully_qualified_domain_name'], + 'tags': d.get('tags') + } + + return d + + +def main(): + AzureRMMySqlServerInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_networkinterface_info.py b/library/azure_rm_networkinterface_info.py new file mode 100644 index 0000000..db7eded --- /dev/null +++ b/library/azure_rm_networkinterface_info.py @@ -0,0 +1,354 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, + +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_networkinterface_info + +version_added: "2.9" + +short_description: Get network interface facts + +description: + - Get facts for a specific network interface or all network interfaces within a resource group. + +options: + name: + description: + - Only show results for a specific network interface. + resource_group: + description: + - Name of the resource group containing the network interface(s). Required when searching by name. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) + +''' + +EXAMPLES = ''' + - name: Get facts for one network interface + azure_rm_networkinterface_info: + resource_group: myResourceGroup + name: nic001 + + - name: Get network interfaces within a resource group + azure_rm_networkinterface_info: + resource_group: myResourceGroup + + - name: Get network interfaces by tag + azure_rm_networkinterface_info: + resource_group: myResourceGroup + tags: + - testing + - foo:bar +''' + +RETURN = ''' +azure_networkinterfaces: + description: + - List of network interface dicts. + returned: always + type: list + example: [{ + "dns_settings": { + "applied_dns_servers": [], + "dns_servers": [], + "internal_dns_name_label": null, + "internal_fqdn": null + }, + "enable_ip_forwarding": false, + "etag": 'W/"59726bfc-08c4-44ed-b900-f6a559876a9d"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nic003", + "ip_configuration": { + "name": "default", + "private_ip_address": "10.10.0.4", + "private_ip_allocation_method": "Dynamic", + "public_ip_address": { + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/publicip001", + "name": "publicip001" + }, + "subnet": { + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet001/subnets/subnet001", + "name": "subnet001", + "virtual_network_name": "vnet001" + } + }, + "location": "westus", + "mac_address": null, + "name": "nic003", + "network_security_group": { + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001", + "name": "secgroup001" + }, + "primary": null, + "provisioning_state": "Succeeded", + "tags": {}, + "type": "Microsoft.Network/networkInterfaces" + }] +networkinterfaces: + description: + - List of network interface dicts. Each dict contains parameters can be passed to M(azure_rm_networkinterface) module. + type: list + returned: always + contains: + id: + description: + - Id of the network interface. + resource_group: + description: + - Name of a resource group where the network interface exists. + name: + description: + - Name of the network interface. + location: + description: + - Azure location. + virtual_network: + description: + - An existing virtual network with which the network interface will be associated. + - It is a dict which contains I(name) and I(resource_group) of the virtual network. + subnet: + description: + - Name of an existing subnet within the specified virtual network. + tags: + description: + - Tags of the network interface. + ip_configurations: + description: + - List of IP configurations, if contains multiple configurations. + contains: + name: + description: + - Name of the IP configuration. + private_ip_address: + description: + - Private IP address for the IP configuration. + private_ip_allocation_method: + description: + - Private IP allocation method. + public_ip_address: + description: + - Name of the public IP address. None for disable IP address. + public_ip_allocation_method: + description: + - Public IP allocation method. + load_balancer_backend_address_pools: + description: + - List of existing load-balancer backend address pools to associate with the network interface. + primary: + description: + - Whether the IP configuration is the primary one in the list. + application_security_groups: + description: + - List of Application security groups. + sample: /subscriptions//resourceGroups//providers/Microsoft.Network/applicationSecurityGroups/myASG + enable_accelerated_networking: + description: + - Specifies whether the network interface should be created with the accelerated networking feature or not. + create_with_security_group: + description: + - Specifies whether a default security group should be be created with the NIC. Only applies when creating a new NIC. + type: bool + security_group: + description: + - A security group resource ID with which to associate the network interface. + enable_ip_forwarding: + description: + - Whether to enable IP forwarding + dns_servers: + description: + - Which DNS servers should the NIC lookup. + - List of IP addresses. + mac_address: + description: + - The MAC address of the network interface. + provisioning_state: + description: + - The provisioning state of the network interface. + dns_settings: + description: + - The DNS settings in network interface. + contains: + dns_servers: + description: + - List of DNS servers IP addresses. + applied_dns_servers: + description: + - If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers + from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. + internal_dns_name_label: + description: + - Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. + internal_fqdn: + description: + - Fully qualified DNS name supporting internal communications between VMs in the same virtual network. +''' # NOQA +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict + + +AZURE_OBJECT_CLASS = 'NetworkInterface' + + +def nic_to_dict(nic): + ip_configurations = [ + dict( + name=config.name, + private_ip_address=config.private_ip_address, + private_ip_allocation_method=config.private_ip_allocation_method, + primary=config.primary, + load_balancer_backend_address_pools=([item.id for item in config.load_balancer_backend_address_pools] + if config.load_balancer_backend_address_pools else None), + public_ip_address=config.public_ip_address.id if config.public_ip_address else None, + public_ip_allocation_method=config.public_ip_address.public_ip_allocation_method if config.public_ip_address else None, + application_security_groups=([asg.id for asg in config.application_security_groups] + if config.application_security_groups else None) + ) for config in nic.ip_configurations + ] + config = nic.ip_configurations[0] if len(nic.ip_configurations) > 0 else None + subnet_dict = azure_id_to_dict(config.subnet.id) if config and config.subnet else None + subnet = subnet_dict.get('subnets') if subnet_dict else None + virtual_network = dict( + resource_group=subnet_dict.get('resourceGroups'), + name=subnet_dict.get('virtualNetworks')) if subnet_dict else None + return dict( + id=nic.id, + resource_group=azure_id_to_dict(nic.id).get('resourceGroups'), + name=nic.name, + subnet=subnet, + virtual_network=virtual_network, + location=nic.location, + tags=nic.tags, + security_group=nic.network_security_group.id if nic.network_security_group else None, + dns_settings=dict( + dns_servers=nic.dns_settings.dns_servers, + applied_dns_servers=nic.dns_settings.applied_dns_servers, + internal_dns_name_label=nic.dns_settings.internal_dns_name_label, + internal_fqdn=nic.dns_settings.internal_fqdn + ), + ip_configurations=ip_configurations, + mac_address=nic.mac_address, + enable_ip_forwarding=nic.enable_ip_forwarding, + provisioning_state=nic.provisioning_state, + enable_accelerated_networking=nic.enable_accelerated_networking, + dns_servers=nic.dns_settings.dns_servers, + ) + + +class AzureRMNetworkInterfaceInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMNetworkInterfaceInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_networkinterface_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_networkinterface_facts' module has been renamed to 'azure_rm_networkinterface_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + results = [] + + if self.name: + results = self.get_item() + elif self.resource_group: + results = self.list_resource_group() + else: + results = self.list_all() + + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_networkinterfaces': self.serialize_nics(results) + } + self.results['networkinterfaces'] = self.to_dict_list(results) + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + try: + item = self.network_client.network_interfaces.get(self.resource_group, self.name) + except Exception: + pass + + return [item] if item and self.has_tags(item.tags, self.tags) else [] + + def list_resource_group(self): + self.log('List for resource group') + try: + response = self.network_client.network_interfaces.list(self.resource_group) + return [item for item in response if self.has_tags(item.tags, self.tags)] + except Exception as exc: + self.fail("Error listing by resource group {0} - {1}".format(self.resource_group, str(exc))) + + def list_all(self): + self.log('List all') + try: + response = self.network_client.network_interfaces.list_all() + return [item for item in response if self.has_tags(item.tags, self.tags)] + except Exception as exc: + self.fail("Error listing all - {0}".format(str(exc))) + + def serialize_nics(self, raws): + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) for item in raws] if raws else [] + + def to_dict_list(self, raws): + return [nic_to_dict(item) for item in raws] if raws else [] + + +def main(): + AzureRMNetworkInterfaceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_postgresqlconfiguration_info.py b/library/azure_rm_postgresqlconfiguration_info.py new file mode 100644 index 0000000..3b45737 --- /dev/null +++ b/library/azure_rm_postgresqlconfiguration_info.py @@ -0,0 +1,217 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_postgresqlconfiguration_info +version_added: "2.9" +short_description: Get Azure PostgreSQL Configuration facts +description: + - Get facts of Azure PostgreSQL Configuration. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - Setting name. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get specific setting of PostgreSQL configuration + azure_rm_postgresqlconfiguration_info: + resource_group: myResourceGroup + server_name: testpostgresqlserver + name: deadlock_timeout + + - name: Get all settings of PostgreSQL Configuration + azure_rm_postgresqlconfiguration_info: + resource_group: myResourceGroup + server_name: testpostgresqlserver +''' + +RETURN = ''' +settings: + description: + - A list of dictionaries containing MySQL Server settings. + returned: always + type: complex + contains: + id: + description: + - Setting resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testrg/providers/Microsoft.DBforPostgreSQL/servers/testpostgresqlser + ver/configurations/deadlock_timeout" + name: + description: + - Setting name. + returned: always + type: str + sample: deadlock_timeout + value: + description: + - Setting value. + returned: always + type: raw + sample: 1000 + description: + description: + - Description of the configuration. + returned: always + type: str + sample: Deadlock timeout. + source: + description: + - Source of the configuration. + returned: always + type: str + sample: system-default +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.azure_operation import AzureOperationPoller + from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMPostgreSQLConfigurationInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMPostgreSQLConfigurationInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlconfiguration_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlconfiguration_facts' module has been renamed to 'azure_rm_postgresqlconfiguration_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(PostgreSQLManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.name is not None: + self.results['settings'] = self.get() + else: + self.results['settings'] = self.list_by_server() + return self.results + + def get(self): + ''' + Gets facts of the specified PostgreSQL Configuration. + + :return: deserialized PostgreSQL Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.get(resource_group_name=self.resource_group, + server_name=self.server_name, + configuration_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get requested setting.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + ''' + Gets facts of the specified PostgreSQL Configuration. + + :return: deserialized PostgreSQL Configurationinstance state dictionary + ''' + response = None + results = [] + try: + response = self.mgmt_client.configurations.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get settings for server.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'id': d['id'], + 'name': d['name'], + 'value': d['value'], + 'description': d['description'], + 'source': d['source'] + } + return d + + +def main(): + AzureRMPostgreSQLConfigurationInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_postgresqldatabase_info.py b/library/azure_rm_postgresqldatabase_info.py new file mode 100644 index 0000000..115b8fa --- /dev/null +++ b/library/azure_rm_postgresqldatabase_info.py @@ -0,0 +1,209 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_postgresqldatabase_info +version_added: "2.9" +short_description: Get Azure PostgreSQL Database facts +description: + - Get facts of PostgreSQL Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the database. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of PostgreSQL Database + azure_rm_postgresqldatabase_info: + resource_group: myResourceGroup + server_name: server_name + name: database_name + + - name: List instances of PostgreSQL Database + azure_rm_postgresqldatabase_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +databases: + description: + - A list of dict results where the key is the name of the PostgreSQL Database and the values are the facts for that PostgreSQL Database. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/testser + ver/databases/db1" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: testrg + server_name: + description: + - Server name. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: db1 + charset: + description: + - The charset of the database. + returned: always + type: str + sample: UTF8 + collation: + description: + - The collation of the database. + returned: always + type: str + sample: English_United States.1252 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMPostgreSqlDatabasesInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMPostgreSqlDatabasesInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqldatabase_facts' module has been renamed to 'azure_rm_postgresqldatabase_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.server_name is not None and + self.name is not None): + self.results['databases'] = self.get() + elif (self.resource_group is not None and + self.server_name is not None): + self.results['databases'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.postgresql_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Databases.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.postgresql_client.databases.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'name': d['name'], + 'charset': d['charset'], + 'collation': d['collation'] + } + return d + + +def main(): + AzureRMPostgreSqlDatabasesInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_postgresqlfirewallrule_info.py b/library/azure_rm_postgresqlfirewallrule_info.py new file mode 100644 index 0000000..dae3140 --- /dev/null +++ b/library/azure_rm_postgresqlfirewallrule_info.py @@ -0,0 +1,205 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_postgresqlfirewallrule_info +version_added: "2.9" +short_description: Get Azure PostgreSQL Firewall Rule facts +description: + - Get facts of Azure PostgreSQL Firewall Rule. + +options: + resource_group: + description: + - The name of the resource group. + required: True + type: str + server_name: + description: + - The name of the server. + required: True + type: str + name: + description: + - The name of the server firewall rule. + type: str + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of PostgreSQL Firewall Rule + azure_rm_postgresqlfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name + name: firewall_rule_name + + - name: List instances of PostgreSQL Firewall Rule + azure_rm_postgresqlfirewallrule_info: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +rules: + description: + - A list of dictionaries containing facts for PostgreSQL Firewall Rule. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/TestGroup/providers/Microsoft.DBforPostgreSQL/servers/testserver/fire + wallRules/rule1" + server_name: + description: + - The name of the server. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: rule1 + start_ip_address: + description: + - The start IP address of the PostgreSQL firewall rule. + returned: always + type: str + sample: 10.0.0.16 + end_ip_address: + description: + - The end IP address of the PostgreSQL firewall rule. + returned: always + type: str + sample: 10.0.0.18 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMPostgreSQLFirewallRulesInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMPostgreSQLFirewallRulesInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlfirewallrule_facts' module has been renamed to 'azure_rm_postgresqlfirewallrule_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(PostgreSQLManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if (self.name is not None): + self.results['rules'] = self.get() + else: + self.results['rules'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.get(resource_group_name=self.resource_group, + server_name=self.server_name, + firewall_rule_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mgmt_client.firewall_rules.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'id': d['id'], + 'server_name': self.server_name, + 'name': d['name'], + 'start_ip_address': d['start_ip_address'], + 'end_ip_address': d['end_ip_address'] + } + return d + + +def main(): + AzureRMPostgreSQLFirewallRulesInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_postgresqlserver.py b/library/azure_rm_postgresqlserver.py index 8a41573..7680452 100644 --- a/library/azure_rm_postgresqlserver.py +++ b/library/azure_rm_postgresqlserver.py @@ -63,6 +63,7 @@ options: - '9.5' - '9.6' - '10' + - '11' enforce_ssl: description: - Enable SSL enforcement. @@ -119,7 +120,7 @@ id: sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/mysqlsrv1b6dd89593 version: description: - - Server version. Possible values include C(9.5), C(9.6), C(10). + - Server version. Possible values include C(9.5), C(9.6), C(10), C(11). returned: always type: str sample: 9.6 @@ -178,7 +179,7 @@ class AzureRMPostgreSqlServers(AzureRMModuleBase): ), version=dict( type='str', - choices=['9.5', '9.6', '10'] + choices=['9.5', '9.6', '10', '11'] ), enforce_ssl=dict( type='bool', diff --git a/library/azure_rm_postgresqlserver_info.py b/library/azure_rm_postgresqlserver_info.py new file mode 100644 index 0000000..b19d649 --- /dev/null +++ b/library/azure_rm_postgresqlserver_info.py @@ -0,0 +1,263 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_postgresqlserver_info +version_added: "2.9" +short_description: Get Azure PostgreSQL Server facts +description: + - Get facts of PostgreSQL Server. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + type: str + name: + description: + - The name of the server. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of PostgreSQL Server + azure_rm_postgresqlserver_info: + resource_group: myResourceGroup + name: server_name + + - name: List instances of PostgreSQL Server + azure_rm_postgresqlserver_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +servers: + description: + - A list of dictionaries containing facts for PostgreSQL servers. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/po + stgreabdud1223" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Resource name. + returned: always + type: str + sample: postgreabdud1223 + location: + description: + - The location the resource resides in. + returned: always + type: str + sample: eastus + sku: + description: + - The SKU of the server. + returned: always + type: complex + contains: + name: + description: + - The name of the SKU. + returned: always + type: str + sample: GP_Gen4_2 + tier: + description: + - The tier of the particular SKU. + returned: always + type: str + sample: GeneralPurpose + capacity: + description: + - The scale capacity. + returned: always + type: int + sample: 2 + storage_mb: + description: + - The maximum storage allowed for a server. + returned: always + type: int + sample: 128000 + enforce_ssl: + description: + - Enable SSL enforcement. + returned: always + type: bool + sample: False + admin_username: + description: + - The administrator's login name of a server. + returned: always + type: str + sample: serveradmin + version: + description: + - Server version. + returned: always + type: str + sample: "9.6" + user_visible_state: + description: + - A state of a server that is visible to user. + returned: always + type: str + sample: Ready + fully_qualified_domain_name: + description: + - The fully qualified domain name of a server. + returned: always + type: str + sample: postgreabdud1223.postgres.database.azure.com + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + type: dict + sample: { tag1: abc } +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMPostgreSqlServersInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.name = None + self.tags = None + super(AzureRMPostgreSqlServersInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_postgresqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_postgresqlserver_facts' module has been renamed to 'azure_rm_postgresqlserver_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.name is not None): + self.results['servers'] = self.get() + elif (self.resource_group is not None): + self.results['servers'] = self.list_by_resource_group() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.postgresql_client.servers.get(resource_group_name=self.resource_group, + server_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for PostgreSQL Server.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_by_resource_group(self): + response = None + results = [] + try: + response = self.postgresql_client.servers.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for PostgreSQL Servers.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'id': d['id'], + 'resource_group': self.resource_group, + 'name': d['name'], + 'sku': d['sku'], + 'location': d['location'], + 'storage_mb': d['storage_profile']['storage_mb'], + 'version': d['version'], + 'enforce_ssl': (d['ssl_enforcement'] == 'Enabled'), + 'admin_username': d['administrator_login'], + 'user_visible_state': d['user_visible_state'], + 'fully_qualified_domain_name': d['fully_qualified_domain_name'], + 'tags': d.get('tags') + } + + return d + + +def main(): + AzureRMPostgreSqlServersInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_publicipaddress_info.py b/library/azure_rm_publicipaddress_info.py new file mode 100644 index 0000000..0be71fe --- /dev/null +++ b/library/azure_rm_publicipaddress_info.py @@ -0,0 +1,321 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_publicipaddress_info + +version_added: "2.9" + +short_description: Get public IP facts + +description: + - Get facts for a specific public IP or all public IPs within a resource group. + +options: + name: + description: + - Only show results for a specific Public IP. + resource_group: + description: + - Limit results by resource group. Required when using name parameter. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) +''' + +EXAMPLES = ''' + - name: Get facts for one Public IP + azure_rm_publicipaddress_info: + resource_group: myResourceGroup + name: publicip001 + + - name: Get facts for all Public IPs within a resource groups + azure_rm_publicipaddress_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +azure_publicipaddresses: + description: + - List of public IP address dicts. + - Please note that this option will be deprecated in 2.10 when curated format will become the only supported format. + returned: always + type: list + example: [{ + "etag": 'W/"a31a6d7d-cb18-40a5-b16d-9f4a36c1b18a"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/pip2001", + "location": "eastus2", + "name": "pip2001", + "properties": { + "idleTimeoutInMinutes": 4, + "provisioningState": "Succeeded", + "publicIPAllocationMethod": "Dynamic", + "resourceGuid": "29de82f4-a7da-440e-bd3d-9cabb79af95a" + }, + "type": "Microsoft.Network/publicIPAddresses" + }] +publicipaddresses: + description: + - List of publicipaddress. + - Contains the detail which matches azure_rm_publicipaddress parameters. + - Returned when the format parameter set to curated. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxx---xxxxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/publicIPAddresses/pipb57dc95224 + name: + description: + - Name of the public IP address. + returned: always + type: str + sample: pipb57dc95224 + type: + description: + - Resource type. + returned: always + type: str + sample: "Microsoft.Network/publicIPAddresses" + location: + description: + - Resource location. + returned: always + type: str + sample: eastus + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { + "delete": "on-exit", + "testing": "testing" + } + allocation_method: + description: + - The public IP allocation method. + - Possible values are C(static) and C(dynamic). + returned: always + type: str + sample: static + version: + description: + - The public IP address version. + - Possible values are C(ipv4) and C(ipv6). + returned: always + type: str + sample: ipv4 + dns_settings: + description: + - The FQDN of the DNS record associated with the public IP address. + returned: always + type: dict + sample: { + "domain_name_label": "ansible-b57dc95985712e45eb8b9c2e", + "fqdn": "ansible-b57dc95985712e45eb8b9c2e.eastus.cloudapp.azure.com", + "reverse_fqdn": null + } + ip_tags: + description: + - The list of tags associated with the public IP address. + returned: always + type: list + sample: [ + { + "type": "FirstPartyUsage", + "value": "Storage" + } + ] + ip_address: + description: + - The Public IP Prefix this Public IP Address should be allocated from. + returned: always + type: str + sample: 40.121.144.14 + idle_timeout: + description: + - The idle timeout of the public IP address. + returned: always + type: int + sample: 4 + provisioning_state: + description: + - The provisioning state of the PublicIP resource. + - Possible values is C(Succeeded). + returned: always + type: str + sample: Succeeded + etag: + description: + - A unique read-only string that changes whenever the resource is updated. + returned: always + type: str + sample: "W/'1905ee13-7623-45b1-bc6b-4a12b2fb9d15'" + sku: + description: + - The public IP address SKU. + returned: always + type: str + sample: Basic +''' +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +AZURE_OBJECT_CLASS = 'PublicIp' + + +class AzureRMPublicIPInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMPublicIPInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_publicipaddress_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_publicipaddress_facts' module has been renamed to 'azure_rm_publicipaddress_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + result = [] + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if self.name: + result = self.get_item() + elif self.resource_group: + result = self.list_resource_group() + else: + result = self.list_all() + + raw = self.filter(result) + + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_publicipaddresses': self.serialize(raw), + } + self.results['publicipaddresses'] = self.format(raw) + + return self.results + + def format(self, raw): + return [self.pip_to_dict(item) for item in raw] + + def serialize(self, raw): + results = [] + for item in raw: + pip = self.serialize_obj(item, AZURE_OBJECT_CLASS) + pip['name'] = item.name + pip['type'] = item.type + results.append(pip) + return results + + def filter(self, response): + return [item for item in response if self.has_tags(item.tags, self.tags)] + + # duplicate with azure_rm_publicipaddress + def pip_to_dict(self, pip): + result = dict( + id=pip.id, + name=pip.name, + type=pip.type, + location=pip.location, + tags=pip.tags, + allocation_method=pip.public_ip_allocation_method.lower(), + version=pip.public_ip_address_version.lower(), + dns_settings=dict(), + ip_tags=dict(), + ip_address=pip.ip_address, + idle_timeout=pip.idle_timeout_in_minutes, + provisioning_state=pip.provisioning_state, + etag=pip.etag, + sku=pip.sku.name + ) + if pip.dns_settings: + result['dns_settings']['domain_name_label'] = pip.dns_settings.domain_name_label + result['dns_settings']['fqdn'] = pip.dns_settings.fqdn + result['dns_settings']['reverse_fqdn'] = pip.dns_settings.reverse_fqdn + if pip.ip_tags: + result['ip_tags'] = [dict(type=x.ip_tag_type, value=x.tag) for x in pip.ip_tags] + return result + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + try: + item = self.network_client.public_ip_addresses.get(self.resource_group, self.name) + except CloudError: + pass + return [item] if item else [] + + def list_resource_group(self): + self.log('List items in resource groups') + try: + response = self.network_client.public_ip_addresses.list(self.resource_group) + except AzureHttpError as exc: + self.fail("Error listing items in resource groups {0} - {1}".format(self.resource_group, str(exc))) + return response + + def list_all(self): + self.log('List all items') + try: + response = self.network_client.public_ip_addresses.list_all() + except AzureHttpError as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + return response + + +def main(): + AzureRMPublicIPInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_rediscache_info.py b/library/azure_rm_rediscache_info.py new file mode 100644 index 0000000..d238e48 --- /dev/null +++ b/library/azure_rm_rediscache_info.py @@ -0,0 +1,354 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Yunge Zhu +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_rediscache_info + +version_added: "2.9" + +short_description: Get Azure Cache for Redis instance facts + +description: + - Get facts for Azure Cache for Redis instance. + +options: + resource_group: + description: + - The resource group to search for the desired Azure Cache for Redis. + required: True + name: + description: + - Limit results to a specific Azure Cache for Redis. + return_access_keys: + description: + - Indicate weather to return access keys of the Azure Cache for Redis. + default: False + type: bool + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get Azure Cache for Redis by name + azure_rm_rediscache_info: + resource_group: myResourceGroup + name: myRedis + + - name: Get Azure Cache for Redis with access keys by name + azure_rm_rediscache_info: + resource_group: myResourceGroup + name: myRedis + return_access_keys: true + + - name: Get Azure Cache for Redis in specific resource group + azure_rm_rediscache_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +rediscaches: + description: + - List of Azure Cache for Redis instances. + returned: always + type: complex + contains: + resource_group: + description: + - Name of a resource group where the Azure Cache for Redis belongs to. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Name of the Azure Cache for Redis. + returned: always + type: str + sample: myRedis + id: + description: + - Id of the Azure Cache for Redis. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Cache/Redis/myRedis + provisioning_state: + description: + - Provisioning state of the Redis cache. + returned: always + type: str + sample: Creating + location: + description: + - Location of the Azure Cache for Redis. + returned: always + type: str + sample: WestUS + enable_non_ssl_port: + description: + - Specifies whether the non-ssl Redis server port (6379) is enabled. + returned: always + type: bool + sample: false + sku: + description: + - Dict of SKU information. + returned: always + type: dict + contains: + name: + description: + - Name of the SKU. + returned: always + type: str + sample: standard + size: + description: + - Size of the Azure Cache for Redis. + returned: always + type: str + sample: C1 + static_ip: + description: + - Static IP address. + returned: always + type: str + sample: 10.75.0.11 + subnet: + description: + - The full resource ID of a subnet in a virtual network to deploy the Azure Cache for Redis in. + returned: always + type: str + sample: + - "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/Microsoft.Network/VirtualNetworks/myVirtualNetwo + rk/subnets/mySubnet" + configuration: + description: + - Dict of Redis configuration. + returned: always + type: dict + sample: maxmeory_reserved + host_name: + description: + - Redis host name. + returned: always + type: str + sample: testRedis.redis.cache.windows.net + shard_count: + description: + - The number of shards on a Premium Cluster Cache. + returned: always + type: int + sample: 1 + tenant_settings: + description: + - Dict of tenant settings. + returned: always + type: dict + sample: { "key1": "value1" } + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { "key1": "value1" } + access_keys: + description: + - Azure Cache for Redis access keys. + type: dict + returned: when I(return_access_keys=true) + contains: + primary: + description: + - The current primary key that clients can use to authenticate the Redis cahce. + returned: always + type: str + sample: X2xXXxx7xxxxxx5xxxx0xxxxx75xxxxxxxxXXXxxxxx= + secondary: + description: + - The current secondary key that clients can use to authenticate the Redis cahce. + returned: always + type: str + sample: X2xXXxx7xxxxxx5xxxx0xxxxx75xxxxxxxxXXXxxxxx= +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from azure.common import AzureHttpError + from azure.mgmt.redis import RedisManagementClient + from msrestazure.azure_exceptions import CloudError +except ImportError: + # handled in azure_rm_common + pass + +import re + + +class AzureRMRedisCacheInfo(AzureRMModuleBase): + """Utility class to get Azure Cache for Redis facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict( + type='str', + required=True + ), + return_access_keys=dict( + type='bool', + default=False + ), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + rediscaches=[] + ) + + self.name = None + self.resource_group = None + self.profile_name = None + self.tags = None + + self._client = None + + super(AzureRMRedisCacheInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_rediscache_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_rediscache_facts' module has been renamed to 'azure_rm_rediscache_info'", version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + # get management client + self._client = self.get_mgmt_svc_client(RedisManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + api_version='2018-03-01') + + if self.name: + self.results['rediscaches'] = self.get_item() + else: + self.results['rediscaches'] = self.list_by_resourcegroup() + + return self.results + + def get_item(self): + """Get a single Azure Cache for Redis""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self._client.redis.get(resource_group_name=self.resource_group, name=self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [self.serialize_rediscache(item)] + + return result + + def list_by_resourcegroup(self): + """Get all Azure Cache for Redis within a resource group""" + + self.log('List all Azure Cache for Redis within a resource group') + + try: + response = self._client.redis.list_by_resource_group(self.resource_group) + except CloudError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_rediscache(item)) + + return results + + def list_keys(self): + """List Azure Cache for Redis keys""" + + self.log('List keys for {0}'.format(self.name)) + + item = None + + try: + item = self._client.redis.list_keys(resource_group_name=self.resource_group, name=self.name) + except CloudError as exc: + self.fail("Failed to list redis keys of {0} - {1}".format(self.name, str(exc))) + + return item + + def serialize_rediscache(self, rediscache): + ''' + Convert an Azure Cache for Redis object to dict. + :param rediscache: Azure Cache for Redis object + :return: dict + ''' + new_result = dict( + id=rediscache.id, + resource_group=re.sub('\\/.*', '', re.sub('.*resourceGroups\\/', '', rediscache.id)), + name=rediscache.name, + location=rediscache.location, + provisioning_state=rediscache.provisioning_state, + configuration=rediscache.redis_configuration, + tenant_settings=rediscache.tenant_settings, + shard_count=rediscache.shard_count, + enable_non_ssl_port=rediscache.enable_non_ssl_port, + static_ip=rediscache.static_ip, + subnet=rediscache.subnet_id, + host_name=rediscache.host_name, + tags=rediscache.tags + ) + + if rediscache.sku: + new_result['sku'] = dict( + name=rediscache.sku.name.lower(), + size=rediscache.sku.family + str(rediscache.sku.capacity) + ) + if self.return_access_keys: + access_keys = self.list_keys() + if access_keys: + new_result['access_keys'] = dict( + primary=access_keys.primary_key, + secondary=access_keys.secondary_key + ) + return new_result + + +def main(): + """Main module execution code path""" + + AzureRMRedisCacheInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_resource_info.py b/library/azure_rm_resource_info.py new file mode 100644 index 0000000..44c6f21 --- /dev/null +++ b/library/azure_rm_resource_info.py @@ -0,0 +1,431 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_resource_info +version_added: "2.9" +short_description: Generic facts of Azure resources +description: + - Obtain facts of any resource using Azure REST API. + - This module gives access to resources that are not supported via Ansible modules. + - Refer to U(https://docs.microsoft.com/en-us/rest/api/) regarding details related to specific resource REST API. + +options: + url: + description: + - Azure RM Resource URL. + api_version: + description: + - Specific API version to be used. + provider: + description: + - Provider type, should be specified in no URL is given. + resource_group: + description: + - Resource group to be used. + - Required if URL is not specified. + resource_type: + description: + - Resource type. + resource_name: + description: + - Resource name. + subresource: + description: + - List of subresources. + suboptions: + namespace: + description: + - Subresource namespace. + type: + description: + - Subresource type. + name: + description: + - Subresource name. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get scaleset info + azure_rm_resource_info: + resource_group: myResourceGroup + provider: compute + resource_type: virtualmachinescalesets + resource_name: myVmss + api_version: "2017-12-01" + + - name: Query all the resources in the resource group + azure_rm_resource_info: + resource_group: "{{ resource_group }}" + resource_type: resources +''' + +RETURN = ''' +response: + description: + - Response specific to resource type. + returned: always + type: complex + contains: + id: + description: + - Id of the Azure resource. + type: str + returned: always + sample: "/subscriptions/xxxx...xxxx/resourceGroups/v-xisuRG/providers/Microsoft.Compute/virtualMachines/myVM" + location: + description: + - Resource location. + type: str + returned: always + sample: eastus + name: + description: + - Resource name. + type: str + returned: always + sample: myVM + properties: + description: + - Specifies the virtual machine's property. + type: complex + returned: always + contains: + diagnosticsProfile: + description: + - Specifies the boot diagnostic settings state. + type: complex + returned: always + contains: + bootDiagnostics: + description: + - A debugging feature, which to view Console Output and Screenshot to diagnose VM status. + type: dict + returned: always + sample: { + "enabled": true, + "storageUri": "https://vxisurgdiag.blob.core.windows.net/" + } + hardwareProfile: + description: + - Specifies the hardware settings for the virtual machine. + type: dict + returned: always + sample: { + "vmSize": "Standard_D2s_v3" + } + networkProfile: + description: + - Specifies the network interfaces of the virtual machine. + type: complex + returned: always + contains: + networkInterfaces: + description: + - Describes a network interface reference. + type: list + returned: always + sample: + - { + "id": "/subscriptions/xxxx...xxxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/networkInterfaces/myvm441" + } + osProfile: + description: + - Specifies the operating system settings for the virtual machine. + type: complex + returned: always + contains: + adminUsername: + description: + - Specifies the name of the administrator account. + type: str + returned: always + sample: azureuser + allowExtensionOperations: + description: + - Specifies whether extension operations should be allowed on the virtual machine. + - This may only be set to False when no extentions are present on the virtual machine. + type: bool + returned: always + sample: true + computerName: + description: + - Specifies the host OS name of the virtual machine. + type: str + returned: always + sample: myVM + requireGuestProvisionSignale: + description: + - Specifies the host require guest provision siganl or not. + type: bool + returned: always + sample: true + secrets: + description: + - Specifies set of certificates that should be installed onto the virtual machine. + type: list + returned: always + sample: [] + linuxConfiguration: + description: + - Specifies the Linux operatiing system settings on the virtual machine. + type: dict + returned: when OS type is Linux + sample: { + "disablePasswordAuthentication": false, + "provisionVMAgent": true + } + provisioningState: + description: + - The provisioning state. + type: str + returned: always + sample: Succeeded + vmID: + description: + - Specifies the VM unique ID whic is a 128-bits identifier that is encoded and stored in all Azure laaS VMs SMBIOS. + - It can be read using platform BIOS commands. + type: str + returned: always + sample: "eb86d9bb-6725-4787-a487-2e497d5b340c" + storageProfile: + description: + - Specifies the storae account type for the managed disk. + type: complex + returned: always + contains: + dataDisks: + description: + - Specifies the parameters that are used to add a data disk to virtual machine. + type: list + returned: always + sample: + - { + "caching": "None", + "createOption": "Attach", + "diskSizeGB": 1023, + "lun": 2, + "managedDisk": { + "id": "/subscriptions/xxxx....xxxx/resourceGroups/V-XISURG/providers/Microsoft.Compute/disks/testdisk2", + "storageAccountType": "StandardSSD_LRS" + }, + "name": "testdisk2" + } + - { + "caching": "None", + "createOption": "Attach", + "diskSizeGB": 1023, + "lun": 1, + "managedDisk": { + "id": "/subscriptions/xxxx...xxxx/resourceGroups/V-XISURG/providers/Microsoft.Compute/disks/testdisk3", + "storageAccountType": "StandardSSD_LRS" + }, + "name": "testdisk3" + } + + imageReference: + description: + - Specifies information about the image to use. + type: dict + returned: always + sample: { + "offer": "UbuntuServer", + "publisher": "Canonical", + "sku": "18.04-LTS", + "version": "latest" + } + osDisk: + description: + - Specifies information about the operating system disk used by the virtual machine. + type: dict + returned: always + sample: { + "caching": "ReadWrite", + "createOption": "FromImage", + "diskSizeGB": 30, + "managedDisk": { + "id": "/subscriptions/xxx...xxxx/resourceGroups/v-xisuRG/providers/Microsoft.Compute/disks/myVM_disk1_xxx", + "storageAccountType": "Premium_LRS" + }, + "name": "myVM_disk1_xxx", + "osType": "Linux" + } + type: + description: + - The type of identity used for the virtual machine. + type: str + returned: always + sample: "Microsoft.Compute/virtualMachines" +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.azure_rm_common_rest import GenericRestClient + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.service_client import ServiceClient + from msrestazure.tools import resource_id, is_valid_resource_id + import json + +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMResourceInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + url=dict( + type='str' + ), + provider=dict( + type='str' + ), + resource_group=dict( + type='str' + ), + resource_type=dict( + type='str' + ), + resource_name=dict( + type='str' + ), + subresource=dict( + type='list', + default=[] + ), + api_version=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + response=[] + ) + self.mgmt_client = None + self.url = None + self.api_version = None + self.provider = None + self.resource_group = None + self.resource_type = None + self.resource_name = None + self.subresource = [] + super(AzureRMResourceInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_resource_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_resource_facts' module has been renamed to 'azure_rm_resource_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if self.url is None: + orphan = None + rargs = dict() + rargs['subscription'] = self.subscription_id + rargs['resource_group'] = self.resource_group + if not (self.provider is None or self.provider.lower().startswith('.microsoft')): + rargs['namespace'] = "Microsoft." + self.provider + else: + rargs['namespace'] = self.provider + + if self.resource_type is not None and self.resource_name is not None: + rargs['type'] = self.resource_type + rargs['name'] = self.resource_name + for i in range(len(self.subresource)): + resource_ns = self.subresource[i].get('namespace', None) + resource_type = self.subresource[i].get('type', None) + resource_name = self.subresource[i].get('name', None) + if resource_type is not None and resource_name is not None: + rargs['child_namespace_' + str(i + 1)] = resource_ns + rargs['child_type_' + str(i + 1)] = resource_type + rargs['child_name_' + str(i + 1)] = resource_name + else: + orphan = resource_type + else: + orphan = self.resource_type + + self.url = resource_id(**rargs) + + if orphan is not None: + self.url += '/' + orphan + + # if api_version was not specified, get latest one + if not self.api_version: + try: + # extract provider and resource type + if "/providers/" in self.url: + provider = self.url.split("/providers/")[1].split("/")[0] + resourceType = self.url.split(provider + "/")[1].split("/")[0] + url = "/subscriptions/" + self.subscription_id + "/providers/" + provider + api_versions = json.loads(self.mgmt_client.query(url, "GET", {'api-version': '2015-01-01'}, None, None, [200], 0, 0).text) + for rt in api_versions['resourceTypes']: + if rt['resourceType'].lower() == resourceType.lower(): + self.api_version = rt['apiVersions'][0] + break + else: + # if there's no provider in API version, assume Microsoft.Resources + self.api_version = '2018-05-01' + if not self.api_version: + self.fail("Couldn't find api version for {0}/{1}".format(provider, resourceType)) + except Exception as exc: + self.fail("Failed to obtain API version: {0}".format(str(exc))) + + self.results['url'] = self.url + + query_parameters = {} + query_parameters['api-version'] = self.api_version + + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + skiptoken = None + + while True: + if skiptoken: + query_parameters['skiptoken'] = skiptoken + response = self.mgmt_client.query(self.url, "GET", query_parameters, header_parameters, None, [200, 404], 0, 0) + try: + response = json.loads(response.text) + if isinstance(response, dict): + if response.get('value'): + self.results['response'] = self.results['response'] + response['value'] + skiptoken = response.get('nextLink') + else: + self.results['response'] = self.results['response'] + [response] + except Exception as e: + self.fail('Failed to parse response: ' + str(e)) + if not skiptoken: + break + return self.results + + +def main(): + AzureRMResourceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_roleassignment_info.py b/library/azure_rm_roleassignment_info.py new file mode 100644 index 0000000..e12b0c2 --- /dev/null +++ b/library/azure_rm_roleassignment_info.py @@ -0,0 +1,280 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Yunge Zhu, (@yungezz) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_roleassignment_info +version_added: "2.9" +short_description: Gets Azure Role Assignment facts +description: + - Gets facts of Azure Role Assignment. + +options: + scope: + description: + - The scope that the role assignment applies to. + - For example, use /subscriptions/{subscription-id}/ for a subscription. + - /subscriptions/{subscription-id}/resourceGroups/{resourcegroup-name} for a resource group. + - /subscriptions/{subscription-id}/resourceGroups/{resourcegroup-name}/providers/{resource-provider}/{resource-type}/{resource-name} for a resource. + name: + description: + - Name of role assignment. + - Mutual exclusive with I(assignee). + assignee: + description: + - Object id of a user, group or service principal. + - Mutually exclusive with I(name). + role_definition_id: + description: + - Resource id of role definition. + +extends_documentation_fragment: + - azure + +author: + - Yunge Zhu(@yungezz) + +''' + +EXAMPLES = ''' + - name: Get role assignments for specific service principal + azure_rm_roleassignment_info: + assignee: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + + - name: Get role assignments for specific scope + azure_rm_roleassignment_info: + scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +''' + +RETURN = ''' +roleassignments: + description: + - List of role assignments. + returned: always + type: complex + contains: + id: + description: + - Id of role assignment. + type: str + returned: always + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleAssignments/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + name: + description: + - Name of role assignment. + type: str + returned: always + sample: myRoleAssignment + type: + descripition: + - Type of role assignment. + type: str + returned: always + sample: custom + principal_id: + description: + - Principal Id of the role assigned to. + type: str + returned: always + sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + role_definition_id: + description: + - Role definition id that was assigned to principal_id. + type: str + returned: always + sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + scope: + description: + - The role assignment scope. + type: str + returned: always + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +''' + +import time +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.serialization import Model + from azure.mgmt.authorization import AuthorizationManagementClient + +except ImportError: + # This is handled in azure_rm_common + pass + + +def roleassignment_to_dict(assignment): + return dict( + id=assignment.id, + name=assignment.name, + type=assignment.type, + principal_id=assignment.principal_id, + role_definition_id=assignment.role_definition_id, + scope=assignment.scope + ) + + +class AzureRMRoleAssignmentInfo(AzureRMModuleBase): + + def __init__(self): + self.module_arg_spec = dict( + name=dict( + type='str' + ), + scope=dict( + type='str' + ), + assignee=dict( + type='str' + ), + role_definition_id=dict( + type='str' + ) + ) + + self.name = None + self.scope = None + self.assignee = None + self.role_definition_id = None + + self.results = dict( + changed=False + ) + + self._client = None + + mutually_exclusive = [['name', 'assignee']] + + super(AzureRMRoleAssignmentInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False, + mutually_exclusive=mutually_exclusive) + + def exec_module(self, **kwargs): + """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_roleassignment_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_roleassignment_facts' module has been renamed to 'azure_rm_roleassignment_info'", version='2.13') + + for key in list(self.module_arg_spec.keys()): + if hasattr(self, key): + setattr(self, key, kwargs[key]) + + # get management client + self._client = self.get_mgmt_svc_client(AuthorizationManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + api_version="2018-01-01-preview") + + if self.name: + self.results['roleassignments'] = self.get_by_name() + elif self.assignee: + self.results['roleassignments'] = self.get_by_assignee() + elif self.scope: + self.results['roleassignments'] = self.list_by_scope() + else: + self.fail("Please specify name or assignee") + + return self.results + + def get_by_name(self): + ''' + Gets the properties of the specified role assignment by name. + + :return: deserialized role assignment dictionary + ''' + self.log("Gets role assignment {0} by name".format(self.name)) + + results = [] + + try: + response = self._client.role_assignments.get(scope=self.scope, role_assignment_name=self.name) + + if response: + response = roleassignment_to_dict(response) + + if self.role_definition_id: + if self.role_definition_id == response['role_definition_id']: + results = [response] + else: + results = [response] + + except CloudError as ex: + self.log("Didn't find role assignment {0} in scope {1}".format(self.name, self.scope)) + + return results + + def get_by_assignee(self): + ''' + Gets the role assignments by assignee. + + :return: deserialized role assignment dictionary + ''' + self.log("Gets role assignment {0} by name".format(self.name)) + + results = [] + filter = "principalId eq '{0}'".format(self.assignee) + try: + response = list(self._client.role_assignments.list(filter=filter)) + + if response and len(response) > 0: + response = [roleassignment_to_dict(a) for a in response] + + if self.role_definition_id: + for r in response: + if r['role_definition_id'] == self.role_definition_id: + results.append(r) + else: + results = response + + except CloudError as ex: + self.log("Didn't find role assignments to assignee {0}".format(self.assignee)) + + return results + + def list_by_scope(self): + ''' + Lists the role assignments by specific scope. + + :return: deserialized role assignment dictionary + ''' + self.log("Lists role assignment by scope {0}".format(self.scope)) + + results = [] + try: + response = list(self._client.role_assignments.list_for_scope(scope=self.scope, filter='atScope()')) + + if response and len(response) > 0: + response = [roleassignment_to_dict(a) for a in response] + + if self.role_definition_id: + for r in response: + if r['role_definition_id'] == self.role_definition_id: + results.append(r) + else: + results = response + + except CloudError as ex: + self.log("Didn't find role assignments to scope {0}".format(self.scope)) + + return results + + +def main(): + """Main execution""" + AzureRMRoleAssignmentInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_roledefinition_info.py b/library/azure_rm_roledefinition_info.py new file mode 100644 index 0000000..e887732 --- /dev/null +++ b/library/azure_rm_roledefinition_info.py @@ -0,0 +1,310 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Yunge Zhu, (@yungezz) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_roledefinition_info +version_added: "2.9" +short_description: Get Azure Role Definition facts +description: + - Get facts of Azure Role Definition. + +options: + scope: + description: + - The scope of role defintion. + required: True + id: + description: + - Role definition id. + role_name: + description: + - Role name. + type: + description: + - Type of role. + choices: + - system + - custom + +extends_documentation_fragment: + - azure + +author: + - Yunge Zhu(@yungezz) + +''' + +EXAMPLES = ''' + - name: List Role Definitions in scope + azure_rm_roledefinition_info: + scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup + + - name: Get Role Definition by name + azure_rm_roledefinition_info: + scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup + name: myRoleDefinition +''' + +RETURN = ''' +roledefinitions: + description: + - A list of Role Definition facts. + returned: always + type: complex + contains: + id: + description: + - Role Definition ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + role_name: + description: + - Role name. + returned: always + type: str + sample: myCustomRoleDefinition + name: + description: + - System assigned role name. + returned: always + type: str + sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + assignable_scopes: + description: + - List of assignable scopes of this definition. + returned: always + type: list + sample: [ "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup" ] + permissions: + description: + - List of Role Definition permissions. + returned: always + contains: + actions: + description: + - List of allowed actions. + returned: always + type: list + sample: [ 'Microsoft.Compute/virtualMachines/read' ] + not_actions: + description: + - List of denied actions. + returned: always + type: list + sample: [ 'Microsoft.Compute/virtualMachines/write' ] + data_actions: + description: + - List of allowed data actions. + returned: always + type: list + sample: [ 'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read' ] + not_data_actions: + description: + - List of denied data actions. + returned: always + type: list + sample: [ 'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write' ] +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils._text import to_native + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.serialization import Model + from azure.mgmt.authorization import AuthorizationManagementClient + +except ImportError: + # This is handled in azure_rm_common + pass + + +def roledefinition_to_dict(role): + result = dict( + id=role.id, + name=role.name, + type=role.role_type, + assignable_scopes=role.assignable_scopes, + description=role.description, + role_name=role.role_name + ) + if role.permissions: + result['permissions'] = [dict( + actions=p.actions, + not_actions=p.not_actions, + data_actions=p.data_actions, + not_data_actions=p.not_data_actions + ) for p in role.permissions] + return result + + +class AzureRMRoleDefinitionInfo(AzureRMModuleBase): + def __init__(self): + self.module_arg_spec = dict( + scope=dict( + type='str', + required='true' + ), + role_name=dict(type='str'), + id=dict(type='str'), + type=dict( + type='str', + choices=['custom', 'system']) + ) + + self.role_name = None + self.scope = None + self.id = None + self.type = None + + self.results = dict( + changed=False + ) + + self._client = None + + super(AzureRMRoleDefinitionInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False) + + def exec_module(self, **kwargs): + """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_roledefinition_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_roledefinition_facts' module has been renamed to 'azure_rm_roledefinition_info'", version='2.13') + + for key in list(self.module_arg_spec.keys()): + if hasattr(self, key): + setattr(self, key, kwargs[key]) + + if self.type: + self.type = self.get_role_type(self.type) + + # get management client + self._client = self.get_mgmt_svc_client(AuthorizationManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + api_version="2018-01-01-preview") + + if self.id: + self.results['roledefinitions'] = self.get_by_id() + elif self.role_name: + self.results['roledefinitions'] = self.get_by_role_name() + else: + self.results['roledefinitions'] = self.list() + + return self.results + + def get_role_type(self, role_type): + if role_type: + if role_type == 'custom': + return 'CustomRole' + else: + return 'SystemRole' + return role_type + + def list(self): + ''' + List Role Definition in scope. + + :return: deserialized Role Definition state dictionary + ''' + self.log("List Role Definition in scope {0}".format(self.scope)) + + response = [] + + try: + response = list(self._client.role_definitions.list(scope=self.scope)) + + if len(response) > 0: + self.log("Response : {0}".format(response)) + roles = [] + + if self.type: + roles = [r for r in response if r.role_type == self.type] + else: + roles = response + + if len(roles) > 0: + return [roledefinition_to_dict(r) for r in roles] + + except CloudError as ex: + self.log("Didn't find role definition in scope {0}".format(self.scope)) + + return response + + def get_by_id(self): + ''' + Get Role Definition in scope by id. + + :return: deserialized Role Definition state dictionary + ''' + self.log("Get Role Definition by id {0}".format(self.id)) + + response = None + + try: + response = self._client.role_definitions.get(scope=self.scope, role_definition_id=self.id) + if response: + response = roledefinition_to_dict(response) + if self.type: + if response.role_type == self.type: + return [response] + else: + return [response] + + except CloudError as ex: + self.log("Didn't find role definition by id {0}".format(self.id)) + + return [] + + def get_by_role_name(self): + ''' + Get Role Definition in scope by role name. + + :return: deserialized role definition state dictionary + ''' + self.log("Get Role Definition by name {0}".format(self.role_name)) + + response = [] + + try: + response = self.list() + + if len(response) > 0: + roles = [] + for r in response: + if r['role_name'] == self.role_name: + roles.append(r) + + if len(roles) == 1: + self.log("Role Definition : {0} found".format(self.role_name)) + return roles + if len(roles) > 1: + self.fail("Found multiple Role Definitions with name: {0}".format(self.role_name)) + + except CloudError as ex: + self.log("Didn't find Role Definition by name {0}".format(self.role_name)) + + return [] + + +def main(): + """Main execution""" + AzureRMRoleDefinitionInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_routetable_info.py b/library/azure_rm_routetable_info.py new file mode 100644 index 0000000..4ef342a --- /dev/null +++ b/library/azure_rm_routetable_info.py @@ -0,0 +1,219 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Yuwei Zhou, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_routetable_info + +version_added: "2.9" + +short_description: Get route table facts + +description: + - Get facts for a specific route table or all route table in a resource group or subscription. + +options: + name: + description: + - Limit results to a specific route table. + resource_group: + description: + - Limit results in a specific resource group. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Yuwei Zhou (@yuwzho) + +''' + +EXAMPLES = ''' + - name: Get facts for one route table + azure_rm_routetable_info: + name: Testing + resource_group: myResourceGroup + + - name: Get facts for all route tables + azure_rm_routetable_info: + resource_group: myResourceGroup + + - name: Get facts by tags + azure_rm_routetable_info: + tags: + - testing + - foo:bar +''' +RETURN = ''' +id: + description: + - Resource ID. + returned: success + type: str + sample: "/subscriptions/xxxx...xxxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/routeTables/tableb57dc95236" +name: + description: + - Name of the resource. + returned: success + type: str + sample: tableb57dc95236 +resource_group: + description: + - Resource group of the route table. + returned: success + type: str + sample: v-xisuRG +disable_bgp_route_propagation: + description: + - Whether the routes learned by BGP on that route table disabled. + returned: success + type: bool + sample: false +tags: + description: + - Tags of the route table. + returned: success + type: dict + sample: { 'key1':'value1', 'key2':'value2'} +routes: + description: + - Current routes of the route table. + returned: success + type: list + sample: [ + { + "id": "/subscriptions/xxx...xxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/routeTables/tableb57dc95236/routes/routeb57dc95540", + "name": "routeb57dc95540", + "resource_group": "v-xisuRG", + "route_table_name": "tableb57dc95236", + "address_prefix": "10.1.0.0/24", + "next_hop_type": "virtual_network_gateway", + "next_hop_ip_address": null + } + ] +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict +from ansible.module_utils.common.dict_transformations import _camel_to_snake + + +def route_to_dict(route): + id_dict = azure_id_to_dict(route.id) + return dict( + id=route.id, + name=route.name, + resource_group=id_dict.get('resourceGroups'), + route_table_name=id_dict.get('routeTables'), + address_prefix=route.address_prefix, + next_hop_type=_camel_to_snake(route.next_hop_type), + next_hop_ip_address=route.next_hop_ip_address + ) + + +def instance_to_dict(table): + return dict( + id=table.id, + name=table.name, + resource_group=azure_id_to_dict(table.id).get('resourceGroups'), + location=table.location, + routes=[route_to_dict(i) for i in table.routes] if table.routes else [], + disable_bgp_route_propagation=table.disable_bgp_route_propagation, + tags=table.tags + ) + + +class AzureRMRouteTableInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + route_tables=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMRouteTableInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_routetable_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_routetable_facts' module has been renamed to 'azure_rm_routetable_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + response = [] + if self.name: + response = self.get_item() + elif self.resource_group: + response = self.list_items() + else: + response = self.list_all_items() + + self.results['route_tables'] = [instance_to_dict(x) for x in response if self.has_tags(x.tags, self.tags)] + return self.results + + def get_item(self): + self.log('Get route table for {0}-{1}'.format(self.resource_group, self.name)) + try: + item = self.network_client.route_tables.get(self.resource_group, self.name) + return [item] + except CloudError: + pass + return [] + + def list_items(self): + self.log('List all items in resource group') + try: + return self.network_client.route_tables.list(self.resource_group) + except CloudError as exc: + self.fail("Failed to list items - {0}".format(str(exc))) + return [] + + def list_all_items(self): + self.log("List all items in subscription") + try: + return self.network_client.route_tables.list_all() + except CloudError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + return [] + + +def main(): + AzureRMRouteTableInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_securitygroup_info.py b/library/azure_rm_securitygroup_info.py new file mode 100644 index 0000000..dfb00bb --- /dev/null +++ b/library/azure_rm_securitygroup_info.py @@ -0,0 +1,320 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_securitygroup_info + +version_added: "2.9" + +short_description: Get security group facts + +description: + - Get facts for a specific security group or all security groups within a resource group. + +options: + name: + description: + - Only show results for a specific security group. + resource_group: + description: + - Name of the resource group to use. + required: true + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) + +''' + +EXAMPLES = ''' + - name: Get facts for one security group + azure_rm_securitygroup_info: + resource_group: myResourceGroup + name: secgroup001 + + - name: Get facts for all security groups + azure_rm_securitygroup_info: + resource_group: myResourceGroup + +''' + +RETURN = ''' +securitygroups: + description: + - List containing security group dicts. + returned: always + type: complex + contains: + etag: + description: + - A unique read-only string that changes whenever the resource is updated. + returned: always + type: str + sample: 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"' + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001" + location: + description: + - Resource location. + returned: always + type: str + sample: "eastus2" + name: + description: + - Resource name. + returned: always + type: str + sample: "secgroup001" + properties: + description: + - List of security group's properties. + returned: always + type: dict + sample: { + "defaultSecurityRules": [ + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/AllowVnetInBound", + "name": "AllowVnetInBound", + "properties": { + "access": "Allow", + "description": "Allow inbound traffic from all VMs in VNET", + "destinationAddressPrefix": "VirtualNetwork", + "destinationPortRange": "*", + "direction": "Inbound", + "priority": 65000, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "VirtualNetwork", + "sourcePortRange": "*" + } + }, + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/AllowAzureLoadBalancerInBound", + "name": "AllowAzureLoadBalancerInBound", + "properties": { + "access": "Allow", + "description": "Allow inbound traffic from azure load balancer", + "destinationAddressPrefix": "*", + "destinationPortRange": "*", + "direction": "Inbound", + "priority": 65001, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "AzureLoadBalancer", + "sourcePortRange": "*" + } + }, + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/DenyAllInBound", + "name": "DenyAllInBound", + "properties": { + "access": "Deny", + "description": "Deny all inbound traffic", + "destinationAddressPrefix": "*", + "destinationPortRange": "*", + "direction": "Inbound", + "priority": 65500, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "*", + "sourcePortRange": "*" + } + }, + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/AllowVnetOutBound", + "name": "AllowVnetOutBound", + "properties": { + "access": "Allow", + "description": "Allow outbound traffic from all VMs to all VMs in VNET", + "destinationAddressPrefix": "VirtualNetwork", + "destinationPortRange": "*", + "direction": "Outbound", + "priority": 65000, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "VirtualNetwork", + "sourcePortRange": "*" + } + }, + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/AllowInternetOutBound", + "name": "AllowInternetOutBound", + "properties": { + "access": "Allow", + "description": "Allow outbound traffic from all VMs to Internet", + "destinationAddressPrefix": "Internet", + "destinationPortRange": "*", + "direction": "Outbound", + "priority": 65001, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "*", + "sourcePortRange": "*" + } + }, + { + "etag": 'W/"d036f4d7-d977-429a-a8c6-879bc2523399"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroup001/defaultSecurityRules/DenyAllOutBound", + "name": "DenyAllOutBound", + "properties": { + "access": "Deny", + "description": "Deny all outbound traffic", + "destinationAddressPrefix": "*", + "destinationPortRange": "*", + "direction": "Outbound", + "priority": 65500, + "protocol": "*", + "provisioningState": "Succeeded", + "sourceAddressPrefix": "*", + "sourcePortRange": "*" + } + } + ], + "networkInterfaces": [ + { + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nic004" + } + ], + "provisioningState": "Succeeded", + "resourceGuid": "ebd00afa-5dc8-446f-810a-50dd6f671588", + "securityRules": [] + } + tags: + descripition: + - Tags to assign to the security group. + returned: always + type: dict + sample: { 'tag': 'value' } + type: + description: + - Type of the resource. + returned: always + type: str + sample: "Microsoft.Network/networkSecurityGroups" + +''' # NOQA + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +AZURE_OBJECT_CLASS = 'NetworkSecurityGroup' + + +class AzureRMSecurityGroupInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(required=True, type='str'), + tags=dict(type='list'), + ) + + self.results = dict( + changed=False, + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMSecurityGroupInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_securitygroup_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_securitygroup_facts' module has been renamed to 'azure_rm_securitygroup_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + info = self.get_item() + else: + info = self.list_items() + + if is_old_facts: + self.results['ansible_facts'] = { + 'azure_securitygroups': info + } + self.results['securitygroups'] = info + + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + result = [] + + try: + item = self.network_client.network_security_groups.get(self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + grp = self.serialize_obj(item, AZURE_OBJECT_CLASS) + grp['name'] = item.name + result = [grp] + + return result + + def list_items(self): + self.log('List all items') + try: + response = self.network_client.network_security_groups.list(self.resource_group) + except Exception as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + grp = self.serialize_obj(item, AZURE_OBJECT_CLASS) + grp['name'] = item.name + results.append(grp) + return results + + +def main(): + AzureRMSecurityGroupInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_servicebus_info.py b/library/azure_rm_servicebus_info.py new file mode 100644 index 0000000..672edfc --- /dev/null +++ b/library/azure_rm_servicebus_info.py @@ -0,0 +1,584 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Yuwei Zhou, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_servicebus_info + +version_added: "2.9" + +short_description: Get servicebus facts + +description: + - Get facts for a specific servicebus or all servicebus in a resource group or subscription. + +options: + name: + description: + - Limit results to a specific servicebus. + resource_group: + description: + - Limit results in a specific resource group. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + namespace: + description: + - Servicebus namespace name. + - A namespace is a scoping container for all messaging components. + - Multiple queues and topics can reside within a single namespace, and namespaces often serve as application containers. + - Required when I(type=namespace). + type: + description: + - Type of the resource. + choices: + - namespace + - queue + - topic + - subscription + topic: + description: + - Topic name. + - Required when I(type=subscription). + show_sas_policies: + description: + - Whether to show the SAS policies. + - Not support when I(type=subscription). + - Note if enable this option, the facts module will raise two more HTTP call for each resources, need more network overhead. + type: bool +extends_documentation_fragment: + - azure + +author: + - Yuwei Zhou (@yuwzho) + +''' + +EXAMPLES = ''' +- name: Get all namespaces under a resource group + azure_rm_servicebus_info: + resource_group: myResourceGroup + type: namespace + +- name: Get all topics under a namespace + azure_rm_servicebus_info: + resource_group: myResourceGroup + namespace: bar + type: topic + +- name: Get a single queue with SAS policies + azure_rm_servicebus_info: + resource_group: myResourceGroup + namespace: bar + type: queue + name: sbqueue + show_sas_policies: true + +- name: Get all subscriptions under a resource group + azure_rm_servicebus_info: + resource_group: myResourceGroup + type: subscription + namespace: bar + topic: sbtopic +''' +RETURN = ''' +servicebuses: + description: + - List of servicebus dicts. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/foo/providers/Microsoft.ServiceBus/ + namespaces/bar/topics/baz/subscriptions/qux" + name: + description: + - Resource name. + returned: always + type: str + sample: qux + location: + description: + - The Geo-location where the resource lives. + returned: always + type: str + sample: eastus + namespace: + description: + - I(namespace) name of the C(queue) or C(topic), C(subscription). + returned: always + type: str + sample: bar + topic: + description: + - Topic name of a subscription. + returned: always + type: str + sample: baz + tags: + description: + - Resource tags. + returned: always + type: dict + sample: {env: sandbox} + sku: + description: + - Properties of namespace's SKU. + returned: always + type: str + sample: Standard + provisioning_state: + description: + - Provisioning state of the namespace. + returned: always + type: str + sample: Succeeded + service_bus_endpoint: + description: + - Endpoint you can use to perform Service Bus operations. + returned: always + type: str + sample: "https://bar.servicebus.windows.net:443/" + metric_id: + description: + - Identifier for Azure Insights metrics of namespace. + returned: always + type: str + sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX:bar" + type: + description: + - Resource type. + - Namespace is a scoping container for all messaging components. + - Queue enables you to store messages until the receiving application is available to receive and process them. + - Topic and subscriptions enable 1:n relationships between publishers and subscribers. + returned: always + type: str + sample: "Microsoft.ServiceBus/Namespaces/Topics" + created_at: + description: + - Exact time the message was created. + returned: always + type: str + sample: "2019-01-25 02:46:55.543953+00:00" + updated_at: + description: + - The exact time the message was updated. + returned: always + type: str + sample: "2019-01-25 02:46:55.543953+00:00" + accessed_at: + description: + - Last time the message was sent, or a request was received for this topic. + returned: always + type: str + sample: "2019-01-25 02:46:55.543953+00:00" + subscription_count: + description: + - Number of subscriptions under a topic. + returned: always + type: int + sample: 1 + count_details: + description: + - Message count deatils. + returned: always + type: complex + contains: + active_message_count: + description: + - Number of active messages in the C(queue), C(topic), or C(subscription). + returned: always + type: int + sample: 0 + dead_letter_message_count: + description: + - Number of messages that are dead lettered. + returned: always + type: int + sample: 0 + scheduled_message_count: + description: + - Number of scheduled messages. + returned: always + type: int + sample: 0 + transfer_message_count: + description: + - Number of messages transferred to another C(queue), C(topic), or C(subscription). + returned: always + type: int + sample: 0 + transfer_dead_letter_message_count: + description: + - Number of messages transferred into dead letters. + returned: always + type: int + sample: 0 + support_ordering: + description: + - Value that indicates whether the C(topic) supports ordering. + returned: always + type: bool + sample: true + status: + description: + - The status of a messaging entity. + returned: always + type: str + sample: active + requires_session: + description: + - A value that indicates whether the C(queue) or C(topic) supports the concept of sessions. + returned: always + type: bool + sample: true + requires_duplicate_detection: + description: + - A value indicating if this C(queue) or C(topic) requires duplicate detection. + returned: always + type: bool + sample: true + max_size_in_mb: + description: + - Maximum size of the C(queue) or C(topic) in megabytes, which is the size of the memory allocated for the C(topic). + returned: always + type: int + sample: 5120 + max_delivery_count: + description: + - The maximum delivery count. + - A message is automatically deadlettered after this number of deliveries. + returned: always + type: int + sample: 10 + lock_duration_in_seconds: + description: + - ISO 8601 timespan duration of a peek-lock. + - The amount of time that the message is locked for other receivers. + - The maximum value for LockDuration is 5 minutes. + returned: always + type: int + sample: 60 + forward_to: + description: + - C(queue) or C(topic) name to forward the messages. + returned: always + type: str + sample: quux + forward_dead_lettered_messages_to: + description: + - C(queue) or C(topic) name to forward the Dead Letter message. + returned: always + type: str + sample: corge + enable_partitioning: + description: + - Value that indicates whether the C(queue) or C(topic) to be partitioned across multiple message brokers is enabled. + returned: always + type: bool + sample: true + enable_express: + description: + - Value that indicates whether Express Entities are enabled. + - An express topic holds a message in memory temporarily before writing it to persistent storage. + returned: always + type: bool + sample: true + enable_batched_operations: + description: + - Value that indicates whether server-side batched operations are enabled. + returned: always + type: bool + sample: true + duplicate_detection_time_in_seconds: + description: + - ISO 8601 timeSpan structure that defines the duration of the duplicate detection history. + returned: always + type: int + sample: 600 + default_message_time_to_live_seconds: + description: + - ISO 8061 Default message timespan to live value. + - This is the duration after which the message expires, starting from when the message is sent to Service Bus. + - This is the default value used when TimeToLive is not set on a message itself. + returned: always + type: int + sample: 0 + dead_lettering_on_message_expiration: + description: + - A value that indicates whether this C(queue) or C(topic) has dead letter support when a message expires. + returned: always + type: int + sample: 0 + dead_lettering_on_filter_evaluation_exceptions: + description: + - Value that indicates whether a subscription has dead letter support on filter evaluation exceptions. + returned: always + type: int + sample: 0 + auto_delete_on_idle_in_seconds: + description: + - ISO 8061 timeSpan idle interval after which the queue or topic is automatically deleted. + - The minimum duration is 5 minutes. + returned: always + type: int + sample: true + size_in_bytes: + description: + - The size of the C(queue) or C(topic) in bytes. + returned: always + type: int + sample: 0 + message_count: + description: + - Number of messages. + returned: always + type: int + sample: 10 + sas_policies: + description: + - Dict of SAS policies. + - Will not be returned until I(show_sas_policy) set. + returned: always + type: dict + sample: { + "testpolicy1": { + "id": "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/ + foo/providers/Microsoft.ServiceBus/namespaces/bar/queues/qux/authorizationRules/testpolicy1", + "keys": { + "key_name": "testpolicy1", + "primary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/; + SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXXXX;EntityPath=qux", + "primary_key": "XXXXXXXXXXXXXXXXX", + "secondary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/; + SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXX;EntityPath=qux", + "secondary_key": "XXXXXXXXXXXXXXX" + }, + "name": "testpolicy1", + "rights": "listen_send", + "type": "Microsoft.ServiceBus/Namespaces/Queues/AuthorizationRules" + } + } +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict +from ansible.module_utils.common.dict_transformations import _camel_to_snake +from ansible.module_utils._text import to_native +from datetime import datetime, timedelta + +duration_spec_map = dict( + default_message_time_to_live='default_message_time_to_live_seconds', + duplicate_detection_history_time_window='duplicate_detection_time_in_seconds', + auto_delete_on_idle='auto_delete_on_idle_in_seconds', + lock_duration='lock_duration_in_seconds' +) + + +def is_valid_timedelta(value): + if value == timedelta(10675199, 10085, 477581): + return None + return value + + +class AzureRMServiceBusInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list'), + type=dict(type='str', required=True, choices=['namespace', 'topic', 'queue', 'subscription']), + namespace=dict(type='str'), + topic=dict(type='str'), + show_sas_policies=dict(type='bool') + ) + + required_if = [ + ('type', 'subscription', ['topic', 'resource_group', 'namespace']), + ('type', 'topic', ['resource_group', 'namespace']), + ('type', 'queue', ['resource_group', 'namespace']) + ] + + self.results = dict( + changed=False, + servicebuses=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + self.type = None + self.namespace = None + self.topic = None + self.show_sas_policies = None + + super(AzureRMServiceBusInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + required_if=required_if, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_servicebus_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_servicebus_facts' module has been renamed to 'azure_rm_servicebus_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + response = [] + if self.name: + response = self.get_item() + elif self.resource_group: + response = self.list_items() + else: + response = self.list_all_items() + + self.results['servicebuses'] = [self.instance_to_dict(x) for x in response] + return self.results + + def instance_to_dict(self, instance): + result = dict() + instance_type = getattr(self.servicebus_models, 'SB{0}'.format(str.capitalize(self.type))) + attribute_map = instance_type._attribute_map + for attribute in attribute_map.keys(): + value = getattr(instance, attribute) + if attribute_map[attribute]['type'] == 'duration': + if is_valid_timedelta(value): + key = duration_spec_map.get(attribute) or attribute + result[key] = int(value.total_seconds()) + elif attribute == 'status': + result['status'] = _camel_to_snake(value) + elif isinstance(value, self.servicebus_models.MessageCountDetails): + result[attribute] = value.as_dict() + elif isinstance(value, self.servicebus_models.SBSku): + result[attribute] = value.name.lower() + elif isinstance(value, datetime): + result[attribute] = str(value) + elif isinstance(value, str): + result[attribute] = to_native(value) + elif attribute == 'max_size_in_megabytes': + result['max_size_in_mb'] = value + else: + result[attribute] = value + if self.show_sas_policies and self.type != 'subscription': + policies = self.get_auth_rules() + for name in policies.keys(): + policies[name]['keys'] = self.get_sas_key(name) + result['sas_policies'] = policies + if self.namespace: + result['namespace'] = self.namespace + if self.topic: + result['topic'] = self.topic + return result + + def _get_client(self): + return getattr(self.servicebus_client, '{0}s'.format(self.type)) + + def get_item(self): + try: + client = self._get_client() + if self.type == 'namespace': + item = client.get(self.resource_group, self.name) + return [item] if self.has_tags(item.tags, self.tags) else [] + elif self.type == 'subscription': + return [client.get(self.resource_group, self.namespace, self.topic, self.name)] + else: + return [client.get(self.resource_group, self.namespace, self.name)] + except Exception: + pass + return [] + + def list_items(self): + try: + client = self._get_client() + if self.type == 'namespace': + response = client.list_by_resource_group(self.resource_group) + return [x for x in response if self.has_tags(x.tags, self.tags)] + elif self.type == 'subscription': + return client.list_by_topic(self.resource_group, self.namespace, self.topic) + else: + return client.list_by_namespace(self.resource_group, self.namespace) + except CloudError as exc: + self.fail("Failed to list items - {0}".format(str(exc))) + return [] + + def list_all_items(self): + self.log("List all items in subscription") + try: + if self.type != 'namespace': + return [] + response = self.servicebus_client.namespaces.list() + return [x for x in response if self.has_tags(x.tags, self.tags)] + except CloudError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + return [] + + def get_auth_rules(self): + result = dict() + try: + client = self._get_client() + if self.type == 'namespace': + rules = client.list_authorization_rules(self.resource_group, self.name) + else: + rules = client.list_authorization_rules(self.resource_group, self.namespace, self.name) + while True: + rule = rules.next() + result[rule.name] = self.policy_to_dict(rule) + except StopIteration: + pass + except Exception as exc: + self.fail('Error when getting SAS policies for {0} {1}: {2}'.format(self.type, self.name, exc.message or str(exc))) + return result + + def get_sas_key(self, name): + try: + client = self._get_client() + if self.type == 'namespace': + return client.list_keys(self.resource_group, self.name, name).as_dict() + else: + return client.list_keys(self.resource_group, self.namespace, self.name, name).as_dict() + except Exception as exc: + self.fail('Error when getting SAS policy {0}\'s key - {1}'.format(name, exc.message or str(exc))) + return None + + def policy_to_dict(self, rule): + result = rule.as_dict() + rights = result['rights'] + if 'Manage' in rights: + result['rights'] = 'manage' + elif 'Listen' in rights and 'Send' in rights: + result['rights'] = 'listen_send' + else: + result['rights'] = rights[0].lower() + return result + + +def main(): + AzureRMServiceBusInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_sqldatabase_info.py b/library/azure_rm_sqldatabase_info.py new file mode 100644 index 0000000..e0535b8 --- /dev/null +++ b/library/azure_rm_sqldatabase_info.py @@ -0,0 +1,288 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_sqldatabase_info +version_added: "2.8" +short_description: Get Azure SQL Database facts +description: + - Get facts of Azure SQL Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + server_name: + description: + - The name of the server. + required: True + name: + description: + - The name of the database. + elastic_pool_name: + description: + - The name of the elastic pool. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of SQL Database + azure_rm_sqldatabase_info: + resource_group: testrg + server_name: testserver + name: testdb + + - name: List instances of SQL Database + azure_rm_sqldatabase_info: + resource_group: testrg + server_name: testserver + elastic_pool_name: testep + + - name: List instances of SQL Database + azure_rm_sqldatabase_info: + resource_group: testrg + server_name: testserver +''' + +RETURN = ''' +databases: + description: + - A list of dictionaries containing facts for SQL Database. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testrg/providers/Microsoft.Sql/servers/testserver/databases/testdb + name: + description: + - Database name. + returned: always + type: str + sample: testdb + location: + description: + - Resource location. + returned: always + type: str + sample: southeastasia + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { 'taga':'aaa', 'tagb':'bbb' } + sku: + description: + - The name and tier of the SKU. + returned: always + type: complex + contains: + name: + description: + - The name of the SKU. + returned: always + type: str + sample: BC_Gen4_2 + tier: + description: + - The SKU tier. + returned: always + type: str + sample: BusinessCritical + capacity: + description: + - The SKU capacity. + returned: always + type: int + sample: 2 + kind: + description: + - Kind of database. This is metadata used for the Azure portal experience. + returned: always + type: str + sample: v12.0,user + collation: + description: + - The collation of the database. + returned: always + type: str + sample: SQL_Latin1_General_CP1_CI_AS + status: + description: + - The status of the database. + returned: always + type: str + sample: Online + zone_redundant: + description: + - Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones. + returned: always + type: bool + sample: true +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.sql import SqlManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMSqlDatabaseInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + elastic_pool_name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + self.elastic_pool_name = None + self.tags = None + super(AzureRMSqlDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqldatabase_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqldatabase_facts' module has been renamed to 'azure_rm_sqldatabase_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + self.results['databases'] = self.get() + elif self.elastic_pool_name is not None: + self.results['databases'] = self.list_by_elastic_pool() + else: + self.results['databases'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.sql_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Databases.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_item(response)) + + return results + + def list_by_elastic_pool(self): + response = None + results = [] + try: + response = self.sql_client.databases.list_by_elastic_pool(resource_group_name=self.resource_group, + server_name=self.server_name, + elastic_pool_name=self.elastic_pool_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Databases.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.sql_client.databases.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Databases.') + + if response is not None: + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'id': d.get('id', None), + 'name': d.get('name', None), + 'location': d.get('location', None), + 'tags': d.get('tags', None), + 'sku': { + 'name': d.get('sku', {}).get('name', None), + 'tier': d.get('sku', {}).get('tier', None), + 'capacity': d.get('sku', {}).get('capacity', None) + }, + 'kind': d.get('kind', None), + 'collation': d.get('collation', None), + 'status': d.get('status', None), + 'zone_redundant': d.get('zone_redundant', None) + } + return d + + +def main(): + AzureRMSqlDatabaseInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_sqlfirewallrule_info.py b/library/azure_rm_sqlfirewallrule_info.py new file mode 100644 index 0000000..8885820 --- /dev/null +++ b/library/azure_rm_sqlfirewallrule_info.py @@ -0,0 +1,215 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_sqlfirewallrule_info +version_added: "2.8" +short_description: Get Azure SQL Firewall Rule facts +description: + - Get facts of SQL Firewall Rule. + +options: + resource_group: + description: + - The name of the resource group that contains the server. + required: True + server_name: + description: + - The name of the server. + required: True + name: + description: + - The name of the firewall rule. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of SQL Firewall Rule + azure_rm_sqlfirewallrule_info: + resource_group: myResourceGroup + server_name: testserver + name: testrule + + - name: List instances of SQL Firewall Rule + azure_rm_sqlfirewallrule_info: + resource_group: myResourceGroup + server_name: testserver +''' + +RETURN = ''' +rules: + description: + - A list of dict results containing the facts for matching SQL firewall rules. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/testser + ver/firewallRules/testrule" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: testgroup + server_name: + description: + - SQL server name. + returned: always + type: str + sample: testserver + name: + description: + - Firewall rule name. + returned: always + type: str + sample: testrule + start_ip_address: + description: + - The start IP address of the firewall rule. + returned: always + type: str + sample: 10.0.0.1 + end_ip_address: + description: + - The end IP address of the firewall rule. + returned: always + type: str + sample: 10.0.0.5 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.polling import LROPoller + from azure.mgmt.sql import SqlManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMSqlFirewallRuleInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMSqlFirewallRuleInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqlfirewallrule_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqlfirewallrule_facts' module has been renamed to 'azure_rm_sqlfirewallrule_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.name is not None): + self.results['rules'] = self.get() + else: + self.results['rules'] = self.list_by_server() + return self.results + + def get(self): + ''' + Gets facts of the specified SQL Firewall Rule. + + :return: deserialized SQL Firewall Ruleinstance state dictionary + ''' + response = None + results = [] + try: + response = self.sql_client.firewall_rules.get(resource_group_name=self.resource_group, + server_name=self.server_name, + firewall_rule_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + ''' + Gets facts of the specified SQL Firewall Rule. + + :return: deserialized SQL Firewall Ruleinstance state dictionary + ''' + response = None + results = [] + try: + response = self.sql_client.firewall_rules.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for FirewallRules.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'id': d['id'], + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'name': d['name'], + 'start_ip_address': d['start_ip_address'], + 'end_ip_address': d['end_ip_address'] + } + return d + + +def main(): + AzureRMSqlFirewallRuleInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_sqlserver_info.py b/library/azure_rm_sqlserver_info.py new file mode 100644 index 0000000..bae4ab8 --- /dev/null +++ b/library/azure_rm_sqlserver_info.py @@ -0,0 +1,208 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_sqlserver_info +version_added: "2.9" +short_description: Get SQL Server facts +description: + - Get facts of SQL Server. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + server_name: + description: + - The name of the server. + +extends_documentation_fragment: + - azure + - azure_tags + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get instance of SQL Server + azure_rm_sqlserver_info: + resource_group: myResourceGroup + server_name: server_name + + - name: List instances of SQL Server + azure_rm_sqlserver_info: + resource_group: myResourceGroup +''' + +RETURN = ''' +servers: + description: + - A list of dict results where the key is the name of the SQL Server and the values are the facts for that SQL Server. + returned: always + type: complex + contains: + sqlserver_name: + description: + - The key is the name of the server that the values relate to. + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/sqlcrudtest-4645 + name: + description: + - Resource name. + returned: always + type: str + sample: sqlcrudtest-4645 + type: + description: + - Resource type. + returned: always + type: str + sample: Microsoft.Sql/servers + location: + description: + - Resource location. + returned: always + type: str + sample: japaneast + kind: + description: + - Kind of sql server. This is metadata used for the Azure portal experience. + returned: always + type: str + sample: v12.0 + version: + description: + - The version of the server. + returned: always + type: str + sample: 12.0 + state: + description: + - The state of the server. + returned: always + type: str + sample: Ready + fully_qualified_domain_name: + description: + - The fully qualified domain name of the server. + returned: always + type: str + sample: fully_qualified_domain_name +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.sql import SqlManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMSqlServerInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False, + ansible_facts=dict() + ) + self.resource_group = None + self.server_name = None + super(AzureRMSqlServerInfo, self).__init__(self.module_arg_spec) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_sqlserver_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_sqlserver_facts' module has been renamed to 'azure_rm_sqlserver_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.server_name is not None): + self.results['servers'] = self.get() + elif (self.resource_group is not None): + self.results['servers'] = self.list_by_resource_group() + return self.results + + def get(self): + ''' + Gets facts of the specified SQL Server. + + :return: deserialized SQL Serverinstance state dictionary + ''' + response = None + results = {} + try: + response = self.sql_client.servers.get(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Servers.') + + if response is not None: + results[response.name] = response.as_dict() + + return results + + def list_by_resource_group(self): + ''' + Gets facts of the specified SQL Server. + + :return: deserialized SQL Serverinstance state dictionary + ''' + response = None + results = {} + try: + response = self.sql_client.servers.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Servers.') + + if response is not None: + for item in response: + results[item.name] = item.as_dict() + + return results + + +def main(): + AzureRMSqlServerInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_storageaccount_info.py b/library/azure_rm_storageaccount_info.py new file mode 100644 index 0000000..82906c9 --- /dev/null +++ b/library/azure_rm_storageaccount_info.py @@ -0,0 +1,556 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, + +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_storageaccount_info + +version_added: "2.9" + +short_description: Get storage account facts + +description: + - Get facts for one storage account or all storage accounts within a resource group. + +options: + name: + description: + - Only show results for a specific account. + resource_group: + description: + - Limit results to a resource group. Required when filtering by name. + aliases: + - resource_group_name + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + show_connection_string: + description: + - Show the connection string for each of the storageaccount's endpoints. + - For convenient usage, C(show_connection_string) will also show the access keys for each of the storageaccount's endpoints. + - Note that it will cost a lot of time when list all storageaccount rather than query a single one. + type: bool + version_added: "2.8" + show_blob_cors: + description: + - Show the blob CORS settings for each blob related to the storage account. + - Querying all storage accounts will take a long time. + type: bool + version_added: "2.8" + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) + +''' + +EXAMPLES = ''' + - name: Get facts for one account + azure_rm_storageaccount_info: + resource_group: myResourceGroup + name: clh0002 + + - name: Get facts for all accounts in a resource group + azure_rm_storageaccount_info: + resource_group: myResourceGroup + + - name: Get facts for all accounts by tags + azure_rm_storageaccount_info: + tags: + - testing + - foo:bar +''' + +RETURN = ''' +azure_storageaccounts: + description: + - List of storage account dicts. + returned: always + type: list + example: [{ + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/myResourceGroups/testing/providers/Microsoft.Storage/storageAccounts/testaccount001", + "location": "eastus2", + "name": "testaccount001", + "properties": { + "accountType": "Standard_LRS", + "creationTime": "2016-03-28T02:46:58.290113Z", + "primaryEndpoints": { + "blob": "https://testaccount001.blob.core.windows.net/", + "file": "https://testaccount001.file.core.windows.net/", + "queue": "https://testaccount001.queue.core.windows.net/", + "table": "https://testaccount001.table.core.windows.net/" + }, + "primaryLocation": "eastus2", + "provisioningState": "Succeeded", + "statusOfPrimary": "Available" + }, + "tags": {}, + "type": "Microsoft.Storage/storageAccounts" + }] +storageaccounts: + description: + - List of storage account dicts in resource module's parameter format. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/t + estaccount001" + name: + description: + - Name of the storage account to update or create. + returned: always + type: str + sample: testaccount001 + location: + description: + - Valid Azure location. Defaults to location of the resource group. + returned: always + type: str + sample: eastus + account_type: + description: + - Type of storage account. + - C(Standard_ZRS) and C(Premium_LRS) accounts cannot be changed to other account types. + - Other account types cannot be changed to C(Standard_ZRS) or C(Premium_LRS). + returned: always + type: str + sample: Standard_ZRS + custom_domain: + description: + - User domain assigned to the storage account. + - Must be a dictionary with I(name) and I(use_sub_domain) keys where I(name) is the CNAME source. + returned: always + type: complex + contains: + name: + description: + - CNAME source. + returned: always + type: str + sample: testaccount + use_sub_domain: + description: + - Whether to use sub domain. + returned: always + type: bool + sample: true + kind: + description: + - The kind of storage. + returned: always + type: str + sample: Storage + access_tier: + description: + - The access tier for this storage account. + returned: always + type: str + sample: Hot + https_only: + description: + - Allows https traffic only to storage service when set to C(true). + returned: always + type: bool + sample: false + provisioning_state: + description: + - The status of the storage account at the time the operation was called. + - Possible values include C(Creating), C(ResolvingDNS), C(Succeeded). + returned: always + type: str + sample: Succeeded + secondary_location: + description: + - The location of the geo-replicated secondary for the storage account. + - Only available if the I(account_type=Standard_GRS) or I(account_type=Standard_RAGRS). + returned: always + type: str + sample: westus + status_of_primary: + description: + - Status of the primary location of the storage account; either C(available) or C(unavailable). + returned: always + type: str + sample: available + status_of_secondary: + description: + - Status of the secondary location of the storage account; either C(available) or C(unavailable). + returned: always + type: str + sample: available + primary_location: + description: + - The location of the primary data center for the storage account. + returned: always + type: str + sample: eastus + primary_endpoints: + description: + - URLs to retrieve a public I(blob), I(queue), or I(table) object. + - Note that C(Standard_ZRS) and C(Premium_LRS) accounts only return the blob endpoint. + returned: always + type: complex + contains: + blob: + description: + - The primary blob endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The primary blob endpoint. + returned: always + type: str + sample: "https://testaccount001.blob.core.windows.net/" + connectionstring: + description: + - Connectionstring of the blob endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;BlobEndpoint=X" + queue: + description: + - The primary queue endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The primary queue endpoint. + returned: always + type: str + sample: "https://testaccount001.queue.core.windows.net/" + connectionstring: + description: + - Connectionstring of the queue endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;QueueEndpoint=X" + table: + description: + - The primary table endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The primary table endpoint. + returned: always + type: str + sample: "https://testaccount001.table.core.windows.net/" + connectionstring: + description: + - Connectionstring of the table endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;TableEndpoint=X" + key: + description: + - The account key for the primary_endpoints + returned: always + type: str + sample: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + secondary_endpoints: + description: + - The URLs to retrieve a public I(blob), I(queue), or I(table) object from the secondary location. + - Only available if the SKU I(name=Standard_RAGRS). + returned: always + type: complex + contains: + blob: + description: + - The secondary blob endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The secondary blob endpoint. + returned: always + type: str + sample: "https://testaccount001.blob.core.windows.net/" + connectionstring: + description: + - Connectionstring of the blob endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;BlobEndpoint=X" + queue: + description: + - The secondary queue endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The secondary queue endpoint. + returned: always + type: str + sample: "https://testaccount001.queue.core.windows.net/" + connectionstring: + description: + - Connectionstring of the queue endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;QueueEndpoint=X" + table: + description: + - The secondary table endpoint and connection string. + returned: always + type: complex + contains: + endpoint: + description: + - The secondary table endpoint. + returned: always + type: str + sample: "https://testaccount001.table.core.windows.net/" + connectionstring: + description: + - Connectionstring of the table endpoint. + returned: always + type: str + sample: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=X;AccountKey=X;TableEndpoint=X" + key: + description: + - The account key for the secondary_endpoints + sample: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { "tag1": "abc" } +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils._text import to_native + + +AZURE_OBJECT_CLASS = 'StorageAccount' + + +class AzureRMStorageAccountInfo(AzureRMModuleBase): + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str', aliases=['resource_group_name']), + tags=dict(type='list'), + show_connection_string=dict(type='bool'), + show_blob_cors=dict(type='bool') + ) + + self.results = dict( + changed=False, + ansible_facts=dict(azure_storageaccounts=[]), + storageaccounts=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + self.show_connection_string = None + self.show_blob_cors = None + + super(AzureRMStorageAccountInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_storageaccount_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_storageaccount_facts' module has been renamed to 'azure_rm_storageaccount_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + results = [] + if self.name: + results = self.get_account() + elif self.resource_group: + results = self.list_resource_group() + else: + results = self.list_all() + + filtered = self.filter_tag(results) + + if is_old_facts: + self.results['ansible_facts']['azure_storageaccounts'] = self.serialize(filtered) + self.results['ansible_facts']['storageaccounts'] = self.format_to_dict(filtered) + self.results['storageaccounts'] = self.format_to_dict(filtered) + return self.results + + def get_account(self): + self.log('Get properties for account {0}'.format(self.name)) + account = None + try: + account = self.storage_client.storage_accounts.get_properties(self.resource_group, self.name) + return [account] + except CloudError: + pass + return [] + + def list_resource_group(self): + self.log('List items') + try: + response = self.storage_client.storage_accounts.list_by_resource_group(self.resource_group) + except Exception as exc: + self.fail("Error listing for resource group {0} - {1}".format(self.resource_group, str(exc))) + + return response + + def list_all(self): + self.log('List all items') + try: + response = self.storage_client.storage_accounts.list_by_resource_group(self.resource_group) + except Exception as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + + return response + + def filter_tag(self, raw): + return [item for item in raw if self.has_tags(item.tags, self.tags)] + + def serialize(self, raw): + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) for item in raw] + + def format_to_dict(self, raw): + return [self.account_obj_to_dict(item) for item in raw] + + def account_obj_to_dict(self, account_obj, blob_service_props=None): + account_dict = dict( + id=account_obj.id, + name=account_obj.name, + location=account_obj.location, + access_tier=(account_obj.access_tier.value + if account_obj.access_tier is not None else None), + account_type=account_obj.sku.name.value, + kind=account_obj.kind.value if account_obj.kind else None, + provisioning_state=account_obj.provisioning_state.value, + secondary_location=account_obj.secondary_location, + status_of_primary=(account_obj.status_of_primary.value + if account_obj.status_of_primary is not None else None), + status_of_secondary=(account_obj.status_of_secondary.value + if account_obj.status_of_secondary is not None else None), + primary_location=account_obj.primary_location, + https_only=account_obj.enable_https_traffic_only + ) + + id_dict = self.parse_resource_to_dict(account_obj.id) + account_dict['resource_group'] = id_dict.get('resource_group') + account_key = self.get_connectionstring(account_dict['resource_group'], account_dict['name']) + account_dict['custom_domain'] = None + if account_obj.custom_domain: + account_dict['custom_domain'] = dict( + name=account_obj.custom_domain.name, + use_sub_domain=account_obj.custom_domain.use_sub_domain + ) + + account_dict['primary_endpoints'] = None + if account_obj.primary_endpoints: + account_dict['primary_endpoints'] = dict( + blob=self.format_endpoint_dict(account_dict['name'], account_key[0], account_obj.primary_endpoints.blob, 'blob'), + queue=self.format_endpoint_dict(account_dict['name'], account_key[0], account_obj.primary_endpoints.queue, 'queue'), + table=self.format_endpoint_dict(account_dict['name'], account_key[0], account_obj.primary_endpoints.table, 'table') + ) + if account_key[0]: + account_dict['primary_endpoints']['key'] = '{0}'.format(account_key[0]) + account_dict['secondary_endpoints'] = None + if account_obj.secondary_endpoints: + account_dict['secondary_endpoints'] = dict( + blob=self.format_endpoint_dict(account_dict['name'], account_key[1], account_obj.primary_endpoints.blob, 'blob'), + queue=self.format_endpoint_dict(account_dict['name'], account_key[1], account_obj.primary_endpoints.queue, 'queue'), + table=self.format_endpoint_dict(account_dict['name'], account_key[1], account_obj.primary_endpoints.table, 'table'), + ) + if account_key[1]: + account_dict['secondary_endpoints']['key'] = '{0}'.format(account_key[1]) + account_dict['tags'] = None + if account_obj.tags: + account_dict['tags'] = account_obj.tags + blob_service_props = self.get_blob_service_props(account_dict['resource_group'], account_dict['name']) + if blob_service_props and blob_service_props.cors and blob_service_props.cors.cors_rules: + account_dict['blob_cors'] = [dict( + allowed_origins=to_native(x.allowed_origins), + allowed_methods=to_native(x.allowed_methods), + max_age_in_seconds=x.max_age_in_seconds, + exposed_headers=to_native(x.exposed_headers), + allowed_headers=to_native(x.allowed_headers) + ) for x in blob_service_props.cors.cors_rules] + return account_dict + + def format_endpoint_dict(self, name, key, endpoint, storagetype, protocol='https'): + result = dict(endpoint=endpoint) + if key: + result['connectionstring'] = 'DefaultEndpointsProtocol={0};EndpointSuffix={1};AccountName={2};AccountKey={3};{4}Endpoint={5}'.format( + protocol, + self._cloud_environment.suffixes.storage_endpoint, + name, + key, + str.title(storagetype), + endpoint) + return result + + def get_blob_service_props(self, resource_group, name): + if not self.show_blob_cors: + return None + try: + blob_service_props = self.storage_client.blob_services.get_service_properties(resource_group, name) + return blob_service_props + except Exception: + pass + return None + + def get_connectionstring(self, resource_group, name): + keys = ['', ''] + if not self.show_connection_string: + return keys + try: + cred = self.storage_client.storage_accounts.list_keys(resource_group, name) + # get the following try catch from CLI + try: + keys = [cred.keys[0].value, cred.keys[1].value] + except AttributeError: + keys = [cred.key1, cred.key2] + except Exception: + pass + return keys + + +def main(): + AzureRMStorageAccountInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_subnet_info.py b/library/azure_rm_subnet_info.py new file mode 100644 index 0000000..697f7a0 --- /dev/null +++ b/library/azure_rm_subnet_info.py @@ -0,0 +1,247 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_subnet_info +version_added: "2.8" +short_description: Get Azure Subnet facts +description: + - Get facts of Azure Subnet. + +options: + resource_group: + description: + - The name of the resource group. + required: True + virtual_network_name: + description: + - The name of the virtual network. + required: True + name: + description: + - The name of the subnet. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get facts of specific subnet + azure_rm_subnet_info: + resource_group: myResourceGroup + virtual_network_name: myVirtualNetwork + name: mySubnet + + - name: List facts for all subnets in virtual network + azure_rm_subnet_info: + resource_group: myResourceGroup + virtual_network_name: myVirtualNetwork + name: mySubnet +''' + +RETURN = ''' +subnets: + description: + - A list of dictionaries containing facts for subnet. + returned: always + type: complex + contains: + id: + description: + - Subnet resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/my + VirtualNetwork/subnets/mySubnet" + resource_group: + description: + - Name of resource group. + returned: always + type: str + sample: myResourceGroup + virtual_network_name: + description: + - Name of the containing virtual network. + returned: always + type: str + sample: myVirtualNetwork + name: + description: + - Name of the subnet. + returned: always + type: str + sample: mySubnet + address_prefix_cidr: + description: + - CIDR defining the IPv4 address space of the subnet. + returned: always + type: str + sample: "10.1.0.0/16" + route_table: + description: + - Associated route table ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/routeTables/myRouteTable + security_group: + description: + - Associated security group ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkSecurityGr + oups/myNsg" + service_endpoints: + description: + - List of service endpoints. + type: list + returned: when available + contains: + service: + description: + - The type of the endpoint service. + returned: always + type: str + required: True + sample: Microsoft.Sql + locations: + description: + - A list of location names. + type: list + returned: always + sample: [ 'eastus', 'westus' ] + provisioning_state: + description: + - Provisioning state. + returned: always + type: str + sample: Succeeded + provisioning_state: + description: + - Provisioning state. + returned: always + type: str + sample: Succeeded +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.network import NetworkManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMSubnetInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + virtual_network_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.virtual_network_name = None + self.name = None + super(AzureRMSubnetInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_subnet_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_subnet_facts' module has been renamed to 'azure_rm_subnet_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + self.results['subnets'] = self.get() + else: + self.results['subnets'] = self.list() + + return self.results + + def get(self): + response = None + results = [] + try: + response = self.network_client.subnets.get(resource_group_name=self.resource_group, + virtual_network_name=self.virtual_network_name, + subnet_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Subnet.') + + if response is not None: + results.append(self.format_response(response)) + + return results + + def list(self): + response = None + results = [] + try: + response = self.network_client.subnets.get(resource_group_name=self.resource_group, + virtual_network_name=self.virtual_network_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail('Could not get facts for Subnet.') + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'virtual_network_name': self.parse_resource_to_dict(d.get('id')).get('name'), + 'name': d.get('name'), + 'id': d.get('id'), + 'address_prefix_cidr': d.get('address_prefix'), + 'route_table': d.get('route_table', {}).get('id'), + 'security_group': d.get('network_security_group', {}).get('id'), + 'provisioning_state': d.get('provisioning_state'), + 'service_endpoints': d.get('service_endpoints') + } + return d + + +def main(): + AzureRMSubnetInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_trafficmanagerendpoint_info.py b/library/azure_rm_trafficmanagerendpoint_info.py new file mode 100644 index 0000000..f2a565c --- /dev/null +++ b/library/azure_rm_trafficmanagerendpoint_info.py @@ -0,0 +1,311 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Hai Cao, , Yunge Zhu +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_trafficmanagerendpoint_info + +version_added: "2.9" + +short_description: Get Azure Traffic Manager endpoint facts + +description: + - Get facts for a specific Traffic Manager endpoints or all endpoints in a Traffic Manager profile. + +options: + name: + description: + - Limit results to a specific Traffic Manager endpoint. + resource_group: + description: + - The resource group to search for the desired Traffic Manager profile. + required: True + profile_name: + description: + - Name of Traffic Manager Profile. + required: True + type: + description: + - Type of endpoint. + choices: + - azure_endpoints + - external_endpoints + - nested_endpoints + +extends_documentation_fragment: + - azure + +author: + - Hai Cao (@caohai) + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get endpoints facts of a Traffic Manager profile + azure_rm_trafficmanagerendpoint_info: + resource_group: myResourceGroup + profile_name: Testing + + - name: Get specific endpoint of a Traffic Manager profile + azure_rm_trafficmanager_info: + resource_group: myResourceGroup + profile_name: Testing + name: test_external_endpoint + +''' + +RETURN = ''' +endpoints: + description: + - List of Traffic Manager endpoints. + returned: always + type: complex + contains: + resource_group: + description: + - Name of a resource group. + returned: always + type: str + sample: myResourceGroup + name: + description: + - Name of the Traffic Manager endpoint. + returned: always + type: str + sample: testendpoint + type: + description: + - The type of the endpoint. + returned: always + type: str + sample: external_endpoints + target_resource_id: + description: + - The Azure Resource URI of the of the endpoint. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ClassicCompute/domainNames/vscjavaci + target: + description: + - The fully-qualified DNS name of the endpoint. + returned: always + type: str + sample: 8.8.8.8 + enabled: + description: + - The status of the endpoint. + returned: always + type: str + sample: Enabled + weight: + description: + - The weight of this endpoint when using the 'Weighted' traffic routing method. + returned: always + type: int + sample: 10 + priority: + description: + - The priority of this endpoint when using the 'Priority' traffic routing method. + returned: always + type: str + sample: 3 + location: + description: + - The location of the external or nested endpoints when using the 'Performance' traffic routing method. + returned: always + type: str + sample: East US + min_child_endpoints: + description: + - The minimum number of endpoints that must be available in the child profile to make the parent profile available. + returned: always + type: int + sample: 3 + geo_mapping: + description: + - The list of countries/regions mapped to this endpoint when using the 'Geographic' traffic routing method. + returned: always + type: list + sample: [ + "GEO-NA", + "GEO-AS" + ] +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import ( + _snake_to_camel, _camel_to_snake +) + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureHttpError +except Exception: + # handled in azure_rm_common + pass + +import re + +AZURE_OBJECT_CLASS = 'TrafficManagerEndpoints' + + +def serialize_endpoint(endpoint, resource_group): + result = dict( + id=endpoint.id, + name=endpoint.name, + target_resource_id=endpoint.target_resource_id, + target=endpoint.target, + enabled=True, + weight=endpoint.weight, + priority=endpoint.priority, + location=endpoint.endpoint_location, + min_child_endpoints=endpoint.min_child_endpoints, + geo_mapping=endpoint.geo_mapping, + monitor_status=endpoint.endpoint_monitor_status, + resource_group=resource_group + ) + + if endpoint.endpoint_status and endpoint.endpoint_status == 'Disabled': + result['enabled'] = False + + if endpoint.type: + result['type'] = _camel_to_snake(endpoint.type.split("/")[-1]) + + return result + + +class AzureRMTrafficManagerEndpointInfo(AzureRMModuleBase): + """Utility class to get Azure Traffic Manager Endpoint facts""" + + def __init__(self): + + self.module_args = dict( + profile_name=dict( + type='str', + required=True), + resource_group=dict( + type='str', + required=True), + name=dict(type='str'), + type=dict( + type='str', + choices=[ + 'azure_endpoints', + 'external_endpoints', + 'nested_endpoints' + ]) + ) + + self.results = dict( + changed=False, + endpoints=[] + ) + + self.profile_name = None + self.name = None + self.resource_group = None + self.type = None + + super(AzureRMTrafficManagerEndpointInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_trafficmanagerendpoint_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_trafficmanagerendpoint_facts' module has been renamed to 'azure_rm_trafficmanagerendpoint_info'", + version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + if self.type: + self.type = _snake_to_camel(self.type) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if self.name: + self.results['endpoints'] = self.get_item() + elif self.type: + self.results['endpoints'] = self.list_by_type() + else: + self.results['endpoints'] = self.list_by_profile() + + return self.results + + def get_item(self): + """Get a single Azure Traffic Manager endpoint""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self.traffic_manager_management_client.endpoints.get( + self.resource_group, self.profile_name, self.type, self.name) + except CloudError: + pass + + if item: + if (self.type and self.type == item.type) or self.type is None: + result = [self.serialize_tm(item)] + + return result + + def list_by_profile(self): + """Get all Azure Traffic Manager endpoints of a profile""" + + self.log('List all endpoints belongs to a Traffic Manager profile') + + try: + response = self.traffic_manager_management_client.profiles.get(self.resource_group, self.profile_name) + except AzureHttpError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + if response and response.endpoints: + for endpoint in response.endpoints: + results.append(serialize_endpoint(endpoint, self.resource_group)) + + return results + + def list_by_type(self): + """Get all Azure Traffic Managers endpoints of a profile by type""" + self.log('List all Traffic Manager endpoints of a profile by type') + try: + response = self.traffic_manager_management_client.profiles.get(self.resource_group, self.profile_name) + except AzureHttpError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if item.endpoints: + for endpoint in item.endpoints: + if endpoint.type == self.type: + results.append(serialize_endpoint(endpoint, self.resource_group)) + return results + + +def main(): + """Main module execution code path""" + + AzureRMTrafficManagerEndpointInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_trafficmanagerprofile_info.py b/library/azure_rm_trafficmanagerprofile_info.py new file mode 100644 index 0000000..2b6ed59 --- /dev/null +++ b/library/azure_rm_trafficmanagerprofile_info.py @@ -0,0 +1,422 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Hai Cao, , Yunge Zhu +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_trafficmanagerprofile_info + +version_added: "2.9" + +short_description: Get Azure Traffic Manager profile facts + +description: + - Get facts for a Azure specific Traffic Manager profile or all Traffic Manager profiles. + +options: + name: + description: + - Limit results to a specific Traffic Manager profile. + resource_group: + description: + - The resource group to search for the desired Traffic Manager profile. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Hai Cao (@caohai) + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get facts for one Traffic Manager profile + azure_rm_trafficmanager_info: + name: Testing + resource_group: myResourceGroup + + - name: Get facts for all Traffic Manager profiles + azure_rm_trafficmanager_info: + + - name: Get facts by tags + azure_rm_trafficmanager_info: + tags: + - Environment:Test +''' + +RETURN = ''' +tms: + description: + - List of Traffic Manager profiles. + returned: always + type: complex + contains: + resource_group: + description: + - Name of a resource group where the Traffic Manager profile exists. + returned: always + type: str + sample: testGroup + name: + description: + - Name of the Traffic Manager profile. + returned: always + type: str + sample: testTm + state: + description: + - The state of the Traffic Manager profile. + returned: always + type: str + sample: present + location: + description: + - Location of the Traffic Manager profile. + returned: always + type: str + sample: global + profile_status: + description: + - The status of the Traffic Manager profile. + returned: always + type: str + sample: Enabled + routing_method: + description: + - The traffic routing method of the Traffic Manager profile. + returned: always + type: str + sample: performance + dns_config: + description: + - The DNS settings of the Traffic Manager profile. + returned: always + type: complex + contains: + relative_name: + description: + - The relative DNS name provided by the Traffic Manager profile. + returned: always + type: str + sample: testTm + fqdn: + description: + - The fully-qualified domain name(FQDN) of the Traffic Manager profile. + returned: always + type: str + sample: testTm.trafficmanager.net + ttl: + description: + - The DNS Time-To-Live(TTL), in seconds. + returned: always + type: int + sample: 60 + monitor_config: + description: + - The endpoint monitoring settings of the Traffic Manager profile. + returned: always + type: complex + contains: + protocol: + description: + - The protocol C(HTTP), C(HTTPS) or C(TCP) used to probe for endpoint health. + returned: always + type: str + sample: HTTP + port: + description: + - The TCP port used to probe for endpoint health. + returned: always + type: int + sample: 80 + path: + description: + - The path relative to the endpoint domain name used to probe for endpoint health. + returned: always + type: str + sample: / + interval: + description: + - The monitor interval for endpoints in this profile in seconds. + returned: always + type: int + sample: 10 + timeout: + description: + - The monitor timeout for endpoints in this profile in seconds. + returned: always + type: int + sample: 30 + tolerated_failures: + description: + - The number of consecutive failed health check before declaring an endpoint Degraded after the next failed health check. + returned: always + type: int + sample: 3 + endpoints: + description: + - The list of endpoints in the Traffic Manager profile. + returned: always + type: complex + contains: + id: + description: + - Fully qualified resource ID for the resource. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/trafficMan + agerProfiles/tmtest/externalEndpoints/e1" + name: + description: + - The name of the endpoint. + returned: always + type: str + sample: e1 + type: + description: + - The type of the endpoint. + returned: always + type: str + sample: external_endpoints + target_resource_id: + description: + - The Azure Resource URI of the of the endpoint. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ClassicCompute/dom + ainNames/vscjavaci" + target: + description: + - The fully-qualified DNS name of the endpoint. + returned: always + type: str + sample: 8.8.8.8 + status: + description: + - The status of the endpoint. + returned: always + type: str + sample: Enabled + weight: + description: + - The weight of this endpoint when the profile has I(routing_method=weighted). + returned: always + type: int + sample: 10 + priority: + description: + - The priority of this endpoint when the profile has I(routing_method=priority). + returned: always + type: str + sample: 3 + location: + description: + - The location of endpoints when I(type=external_endpoints) or I(type=nested_endpoints), and profile I(routing_method=performance). + returned: always + type: str + sample: East US + min_child_endpoints: + description: + - The minimum number of endpoints that must be available in the child profile to make the parent profile available. + returned: always + type: int + sample: 3 + geo_mapping: + description: + - The list of countries/regions mapped to this endpoint when the profile has routing_method C(geographic). + returned: always + type: list + sample: [ + "GEO-NA", + "GEO-AS" + ] +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.common.dict_transformations import _camel_to_snake + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureHttpError +except Exception: + # handled in azure_rm_common + pass + +import re + +AZURE_OBJECT_CLASS = 'trafficManagerProfiles' + + +def serialize_endpoint(endpoint): + result = dict( + id=endpoint.id, + name=endpoint.name, + target_resource_id=endpoint.target_resource_id, + target=endpoint.target, + status=endpoint.endpoint_status, + weight=endpoint.weight, + priority=endpoint.priority, + location=endpoint.endpoint_location, + min_child_endpoints=endpoint.min_child_endpoints, + geo_mapping=endpoint.geo_mapping, + ) + + if endpoint.type: + result['type'] = _camel_to_snake(endpoint.type.split("/")[-1]) + + return result + + +class AzureRMTrafficManagerProfileInfo(AzureRMModuleBase): + """Utility class to get Azure Traffic Manager profile facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + tms=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMTrafficManagerProfileInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_trafficmanagerprofile_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_trafficmanagerprofile_facts' module has been renamed to 'azure_rm_trafficmanagerprofile_info'", version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if self.name: + self.results['tms'] = self.get_item() + elif self.resource_group: + self.results['tms'] = self.list_resource_group() + else: + self.results['tms'] = self.list_all() + + return self.results + + def get_item(self): + """Get a single Azure Traffic Manager profile""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + result = [] + + try: + item = self.traffic_manager_management_client.profiles.get( + self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + result = [self.serialize_tm(item)] + + return result + + def list_resource_group(self): + """Get all Azure Traffic Managers profiles within a resource group""" + + self.log('List all Azure Traffic Managers within a resource group') + + try: + response = self.traffic_manager_management_client.profiles.list_by_resource_group( + self.resource_group) + except AzureHttpError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_tm(item)) + + return results + + def list_all(self): + """Get all Azure Traffic Manager profiles within a subscription""" + self.log('List all Traffic Manager profiles within a subscription') + try: + response = self.traffic_manager_management_client.profiles.list_by_subscription() + except Exception as exc: + self.fail("Error listing all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_tm(item)) + return results + + def serialize_tm(self, tm): + ''' + Convert a Traffic Manager profile object to dict. + :param tm: Traffic Manager profile object + :return: dict + ''' + result = self.serialize_obj(tm, AZURE_OBJECT_CLASS) + + new_result = {} + new_result['id'] = tm.id + new_result['resource_group'] = re.sub('\\/.*', '', re.sub('.*resourceGroups\\/', '', result['id'])) + new_result['name'] = tm.name + new_result['state'] = 'present' + new_result['location'] = tm.location + new_result['profile_status'] = tm.profile_status + new_result['routing_method'] = tm.traffic_routing_method.lower() + new_result['dns_config'] = dict( + relative_name=tm.dns_config.relative_name, + fqdn=tm.dns_config.fqdn, + ttl=tm.dns_config.ttl + ) + new_result['monitor_config'] = dict( + profile_monitor_status=tm.monitor_config.profile_monitor_status, + protocol=tm.monitor_config.protocol, + port=tm.monitor_config.port, + path=tm.monitor_config.path, + interval=tm.monitor_config.interval_in_seconds, + timeout=tm.monitor_config.timeout_in_seconds, + tolerated_failures=tm.monitor_config.tolerated_number_of_failures + ) + new_result['endpoints'] = [serialize_endpoint(endpoint) for endpoint in tm.endpoints] + new_result['tags'] = tm.tags + return new_result + + +def main(): + """Main module execution code path""" + + AzureRMTrafficManagerProfileInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachine_info.py b/library/azure_rm_virtualmachine_info.py new file mode 100644 index 0000000..f6cb8ec --- /dev/null +++ b/library/azure_rm_virtualmachine_info.py @@ -0,0 +1,456 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 +# Gustavo Muniz do Carmo +# Zim Kalinowski +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachine_info + +version_added: "2.9" + +short_description: Get virtual machine facts + +description: + - Get facts for one or all virtual machines in a resource group. + +options: + resource_group: + description: + - Name of the resource group containing the virtual machines (required when filtering by vm name). + name: + description: + - Name of the virtual machine. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Gustavo Muniz do Carmo (@gustavomcarmo) + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get facts for all virtual machines of a resource group + azure_rm_virtualmachine_info: + resource_group: myResourceGroup + + - name: Get facts by name + azure_rm_virtualmachine_info: + resource_group: myResourceGroup + name: myVm + + - name: Get facts by tags + azure_rm_virtualmachine_info: + resource_group: myResourceGroup + tags: + - testing + - foo:bar +''' + +RETURN = ''' +vms: + description: + - List of virtual machines. + returned: always + type: complex + contains: + admin_username: + description: + - Administrator user name. + returned: always + type: str + sample: admin + boot_diagnostics: + description: + - Information about the boot diagnostics settings. + returned: always + type: complex + contains: + enabled: + description: + - Indicates if boot diagnostics are enabled. + returned: always + type: bool + sample: true + storage_uri: + description: + - Indicates the storage account used by boot diagnostics. + returned: always + type: str + sample: https://mystorageaccountname.blob.core.windows.net/ + console_screenshot_uri: + description: + - Contains a URI to grab a console screenshot. + - Only present if enabled. + returned: always + type: str + sample: https://mystorageaccountname.blob.core.windows.net/bootdiagnostics-myvm01-a4db09a6-ab7f-4d80-9da8-fbceaef9288a/ + myVm.a4db09a6-ab7f-4d80-9da8-fbceaef9288a.screenshot.bmp + serial_console_log_uri: + description: + - Contains a URI to grab the serial console log. + - Only present if enabled. + returned: always + type: str + sample: https://mystorageaccountname.blob.core.windows.net/bootdiagnostics-myvm01-a4db09a6-ab7f-4d80-9da8-fbceaef9288a/ + myVm.a4db09a6-ab7f-4d80-9da8-fbceaef9288a.serialconsole.log + data_disks: + description: + - List of attached data disks. + returned: always + type: complex + contains: + caching: + description: + - Type of data disk caching. + returned: always + type: str + sample: ReadOnly + disk_size_gb: + description: + - The initial disk size in GB for blank data disks. + returned: always + type: int + sample: 64 + lun: + description: + - The logical unit number for data disk. + returned: always + type: int + sample: 0 + managed_disk_type: + description: + - Managed data disk type. + returned: always + type: str + sample: Standard_LRS + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVm + image: + description: + - Image specification. + returned: always + type: complex + contains: + offer: + description: + - The offer of the platform image or marketplace image used to create the virtual machine. + type: str + returned: when created from marketplace image + sample: RHEL + publisher: + description: + - Publisher name. + type: str + returned: when created from marketplace image + sample: RedHat + sku: + description: + - SKU name. + type: str + returned: when created from marketplace image + sample: 7-RAW + version: + description: + - Image version. + type: str + returned: when created from marketplace image + sample: 7.5.2018050901 + id: + description: + - Custom image resource ID. + type: str + returned: when created from custom image + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/myImage + location: + description: + - Resource location. + returned: always + type: str + sample: japaneast + name: + description: + - Resource name. + returned: always + type: str + sample: myVm + network_interface_names: + description: + - List of attached network interfaces. + returned: always + type: list + sample: [ + "myNetworkInterface" + ] + os_disk_caching: + description: + - Type of OS disk caching. + returned: always + type: str + sample: ReadOnly + os_type: + description: + - Base type of operating system. + returned: always + type: str + sample: Linux + resource_group: + description: + - Resource group. + returned: always + type: str + sample: myResourceGroup + state: + description: + - State of the resource. + returned: always + type: str + sample: present + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { "key1":"value1" } + vm_size: + description: + - Virtual machine size. + returned: always + type: str + sample: Standard_D4 + power_state: + description: + - Power state of the virtual machine. + returned: always + type: str + sample: running +''' + +try: + from msrestazure.azure_exceptions import CloudError + from msrestazure.tools import parse_resource_id +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils.six.moves.urllib.parse import urlparse +import re + + +AZURE_OBJECT_CLASS = 'VirtualMachine' + +AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] + + +class AzureRMVirtualMachineInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + resource_group=dict(type='str'), + name=dict(type='str'), + tags=dict(type='list') + ) + + self.results = dict( + changed=False, + vms=[] + ) + + self.resource_group = None + self.name = None + self.tags = None + + super(AzureRMVirtualMachineInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachine_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachine_facts' module has been renamed to 'azure_rm_virtualmachine_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + if self.name: + self.results['vms'] = self.get_item() + elif self.resource_group: + self.results['vms'] = self.list_items_by_resourcegroup() + else: + self.results['vms'] = self.list_all_items() + + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + result = [] + + item = self.get_vm(self.resource_group, self.name) + + if item and self.has_tags(item.get('tags'), self.tags): + result = [item] + + return result + + def list_items_by_resourcegroup(self): + self.log('List all items') + try: + items = self.compute_client.virtual_machines.list(self.resource_group) + except CloudError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + + results = [] + for item in items: + if self.has_tags(item.tags, self.tags): + results.append(self.get_vm(self.resource_group, item.name)) + return results + + def list_all_items(self): + self.log('List all items') + try: + items = self.compute_client.virtual_machines.list_all() + except CloudError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + + results = [] + for item in items: + if self.has_tags(item.tags, self.tags): + results.append(self.get_vm(parse_resource_id(item.id).get('resource_group'), item.name)) + return results + + def get_vm(self, resource_group, name): + ''' + Get the VM with expanded instanceView + + :return: VirtualMachine object + ''' + try: + vm = self.compute_client.virtual_machines.get(resource_group, name, expand='instanceview') + return self.serialize_vm(vm) + except Exception as exc: + self.fail("Error getting virtual machine {0} - {1}".format(self.name, str(exc))) + + def serialize_vm(self, vm): + ''' + Convert a VirtualMachine object to dict. + + :param vm: VirtualMachine object + :return: dict + ''' + + result = self.serialize_obj(vm, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES) + resource_group = parse_resource_id(result['id']).get('resource_group') + instance = None + power_state = None + + try: + instance = self.compute_client.virtual_machines.instance_view(resource_group, vm.name) + instance = self.serialize_obj(instance, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES) + except Exception as exc: + self.fail("Error getting virtual machine {0} instance view - {1}".format(vm.name, str(exc))) + + for index in range(len(instance['statuses'])): + code = instance['statuses'][index]['code'].split('/') + if code[0] == 'PowerState': + power_state = code[1] + elif code[0] == 'OSState' and code[1] == 'generalized': + power_state = 'generalized' + break + + new_result = {} + new_result['power_state'] = power_state + new_result['id'] = vm.id + new_result['resource_group'] = resource_group + new_result['name'] = vm.name + new_result['state'] = 'present' + new_result['location'] = vm.location + new_result['vm_size'] = result['properties']['hardwareProfile']['vmSize'] + os_profile = result['properties'].get('osProfile') + if os_profile is not None: + new_result['admin_username'] = os_profile.get('adminUsername') + image = result['properties']['storageProfile'].get('imageReference') + if image is not None: + if image.get('publisher', None) is not None: + new_result['image'] = { + 'publisher': image['publisher'], + 'sku': image['sku'], + 'offer': image['offer'], + 'version': image['version'] + } + else: + new_result['image'] = { + 'id': image.get('id', None) + } + + new_result['boot_diagnostics'] = { + 'enabled': 'diagnosticsProfile' in result['properties'] and + 'bootDiagnostics' in result['properties']['diagnosticsProfile'] and + result['properties']['diagnosticsProfile']['bootDiagnostics']['enabled'] or False, + 'storage_uri': 'diagnosticsProfile' in result['properties'] and + 'bootDiagnostics' in result['properties']['diagnosticsProfile'] and + result['properties']['diagnosticsProfile']['bootDiagnostics']['storageUri'] or None + } + if new_result['boot_diagnostics']['enabled']: + new_result['boot_diagnostics']['console_screenshot_uri'] = result['properties']['instanceView']['bootDiagnostics']['consoleScreenshotBlobUri'] + new_result['boot_diagnostics']['serial_console_log_uri'] = result['properties']['instanceView']['bootDiagnostics']['serialConsoleLogBlobUri'] + + vhd = result['properties']['storageProfile']['osDisk'].get('vhd') + if vhd is not None: + url = urlparse(vhd['uri']) + new_result['storage_account_name'] = url.netloc.split('.')[0] + new_result['storage_container_name'] = url.path.split('/')[1] + new_result['storage_blob_name'] = url.path.split('/')[-1] + + new_result['os_disk_caching'] = result['properties']['storageProfile']['osDisk']['caching'] + new_result['os_type'] = result['properties']['storageProfile']['osDisk']['osType'] + new_result['data_disks'] = [] + disks = result['properties']['storageProfile']['dataDisks'] + for disk_index in range(len(disks)): + new_result['data_disks'].append({ + 'lun': disks[disk_index].get('lun'), + 'disk_size_gb': disks[disk_index].get('diskSizeGB'), + 'managed_disk_type': disks[disk_index].get('managedDisk', {}).get('storageAccountType'), + 'caching': disks[disk_index].get('caching') + }) + + new_result['network_interface_names'] = [] + nics = result['properties']['networkProfile']['networkInterfaces'] + for nic_index in range(len(nics)): + new_result['network_interface_names'].append(re.sub('.*networkInterfaces/', '', nics[nic_index]['id'])) + + new_result['tags'] = vm.tags + return new_result + + +def main(): + AzureRMVirtualMachineInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachineextension_info.py b/library/azure_rm_virtualmachineextension_info.py new file mode 100644 index 0000000..de9d797 --- /dev/null +++ b/library/azure_rm_virtualmachineextension_info.py @@ -0,0 +1,248 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachineextension_info +version_added: "2.9" +short_description: Get Azure Virtual Machine Extension facts +description: + - Get facts of Azure Virtual Machine Extension. + +options: + resource_group: + description: + - The name of the resource group. + required: True + virtual_machine_name: + description: + - The name of the virtual machine containing the extension. + required: True + name: + description: + - The name of the virtual machine extension. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get information on specific Virtual Machine Extension + azure_rm_virtualmachineextension_info: + resource_group: myResourceGroup + virtual_machine_name: myvm + name: myextension + + - name: List installed Virtual Machine Extensions + azure_rm_virtualmachineextension_info: + resource_group: myResourceGroup + virtual_machine_name: myvm +''' + +RETURN = ''' +extensions: + description: + - A list of dictionaries containing facts for Virtual Machine Extension. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/myvm/testVM/extens + ions/myextension" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: myResourceGroup + virtual_machine_name: + description: + - Virtual machine name. + returned: always + type: str + sample: myvm + name: + description: + - Virtual machine name. + returned: always + type: str + sample: myextension + location: + description: + - The resource location. + returned: always + type: str + sample: eastus + publisher: + description: + - Extension publisher. + returned: always + type: str + sample: Microsoft.Azure.Extensions + type: + description: + - Extension type. + returned: always + type: str + sample: CustomScript + settings: + description: + - Extension specific settings dictionary. + returned: always + type: dict + sample: { 'commandToExecute':'hostname' } + auto_upgrade_minor_version: + description: + - Autoupgrade minor version flag. + returned: always + type: bool + sample: true + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { "mytag":"abc" } + provisioning_state: + description: + - Provisioning state of the extension. + returned: always + type: str + sample: Succeeded +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMVirtualMachineExtensionInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + virtual_machine_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.virtual_machine_name = None + self.name = None + self.tags = None + super(AzureRMVirtualMachineExtensionInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachineextension_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachineextension_facts' module has been renamed to 'azure_rm_virtualmachineextension_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + self.results['extensions'] = self.get_extensions() + else: + self.results['extensions'] = self.list_extensions() + + return self.results + + def get_extensions(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_extensions.get(resource_group_name=self.resource_group, + vm_name=self.virtual_machine_name, + vm_extension_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine Extension.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list_extensions(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_extensions.list(resource_group_name=self.resource_group, + vm_name=self.virtual_machine_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine Extension.') + + if response is not None and response.value is not None: + for item in response.value: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + d = item.as_dict() + d = { + 'id': d.get('id', None), + 'resource_group': self.resource_group, + 'virtual_machine_name': self.virtual_machine_name, + 'location': d.get('location'), + 'name': d.get('name'), + 'publisher': d.get('publisher'), + 'type': d.get('virtual_machine_extension_type'), + 'settings': d.get('settings'), + 'auto_upgrade_minor_version': d.get('auto_upgrade_minor_version'), + 'tags': d.get('tags', None), + 'provisioning_state': d.get('provisioning_state') + } + return d + + +def main(): + AzureRMVirtualMachineExtensionInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachineimage_info.py b/library/azure_rm_virtualmachineimage_info.py new file mode 100644 index 0000000..c598432 --- /dev/null +++ b/library/azure_rm_virtualmachineimage_info.py @@ -0,0 +1,258 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachineimage_info + +version_added: "2.9" + +short_description: Get virtual machine image facts + +description: + - Get facts for virtual machine images. + +options: + location: + description: + - Azure location value, for example C(westus), C(eastus), C(eastus2), C(northcentralus), etc. + - Supplying only a location value will yield a list of available publishers for the location. + required: true + publisher: + description: + - Name of an image publisher. List image offerings associated with a particular publisher. + offer: + description: + - Name of an image offering. Combine with SKU to see a list of available image versions. + sku: + description: + - Image offering SKU. Combine with offer to see a list of available versions. + version: + description: + - Specific version number of an image. + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) + +''' + +EXAMPLES = ''' + - name: Get facts for a specific image + azure_rm_virtualmachineimage_info: + location: eastus + publisher: OpenLogic + offer: CentOS + sku: '7.1' + version: '7.1.20160308' + + - name: List available versions + azure_rm_virtualmachineimage_info: + location: eastus + publisher: OpenLogic + offer: CentOS + sku: '7.1' + + - name: List available offers + azure_rm_virtualmachineimage_info: + location: eastus + publisher: OpenLogic + + - name: List available publishers + azure_rm_virtualmachineimage_info: + location: eastus + +''' + +RETURN = ''' +azure_vmimages: + description: + - List of image dicts. + returned: always + type: list + example: [ { + "id": "/Subscriptions/xxx...xxx/Providers/Microsoft.Compute/Locations/eastus/ + Publishers/OpenLogic/ArtifactTypes/VMImage/Offers/CentOS/Skus/7.1/Versions/7.1.20150410", + "location": "eastus", + "name": "7.1.20150410" + }, + { + "id": "/Subscriptions/xxx...xxx/Providers/Microsoft.Compute/Locations/eastus/ + Publishers/OpenLogic/ArtifactTypes/VMImage/Offers/CentOS/Skus/7.1/Versions/7.1.20150605", + "location": "eastus", + "name": "7.1.20150605" + }, + { + "id": "/Subscriptions/xxx...xxx/Providers/Microsoft.Compute/Locations/eastus/ + Publishers/OpenLogic/ArtifactTypes/VMImage/Offers/CentOS/Skus/7.1/Versions/7.1.20150731", + "location": "eastus", + "name": "7.1.20150731" + }, + { + "id": "/Subscriptions/xxx...xxx/Providers/Microsoft.Compute/Locations/eastus/ + Publishers/OpenLogic/ArtifactTypes/VMImage/Offers/CentOS/Skus/7.1/Versions/7.1.20160308", + "location": "eastus", + "name": "7.1.20160308" + } + ] +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] + + +class AzureRMVirtualMachineImageInfo(AzureRMModuleBase): + + def __init__(self, **kwargs): + + self.module_arg_spec = dict( + location=dict(type='str', required=True), + publisher=dict(type='str'), + offer=dict(type='str'), + sku=dict(type='str'), + version=dict(type='str') + ) + + self.results = dict( + changed=False, + ansible_facts=dict(azure_vmimages=[]) + ) + + self.location = None + self.publisher = None + self.offer = None + self.sku = None + self.version = None + + super(AzureRMVirtualMachineImageInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachineimage_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachineimage_facts' module has been renamed to 'azure_rm_virtualmachineimage_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if is_old_facts: + if self.location and self.publisher and self.offer and self.sku and self.version: + self.results['ansible_facts']['azure_vmimages'] = self.get_item() + elif self.location and self.publisher and self.offer and self.sku: + self.results['ansible_facts']['azure_vmimages'] = self.list_images() + elif self.location and self.publisher: + self.results['ansible_facts']['azure_vmimages'] = self.list_offers() + elif self.location: + self.results['ansible_facts']['azure_vmimages'] = self.list_publishers() + else: + if self.location and self.publisher and self.offer and self.sku and self.version: + self.results['vmimages'] = self.get_item() + elif self.location and self.publisher and self.offer and self.sku: + self.results['vmimages'] = self.list_images() + elif self.location and self.publisher: + self.results['vmimages'] = self.list_offers() + elif self.location: + self.results['vmimages'] = self.list_publishers() + + return self.results + + def get_item(self): + item = None + result = [] + + try: + item = self.compute_client.virtual_machine_images.get(self.location, + self.publisher, + self.offer, + self.sku, + self.version) + except CloudError: + pass + + if item: + result = [self.serialize_obj(item, 'VirtualMachineImage', enum_modules=AZURE_ENUM_MODULES)] + + return result + + def list_images(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_images.list(self.location, + self.publisher, + self.offer, + self.sku,) + except CloudError: + pass + except Exception as exc: + self.fail("Failed to list images: {0}".format(str(exc))) + + if response: + for item in response: + results.append(self.serialize_obj(item, 'VirtualMachineImageResource', + enum_modules=AZURE_ENUM_MODULES)) + return results + + def list_offers(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_images.list_offers(self.location, + self.publisher) + except CloudError: + pass + except Exception as exc: + self.fail("Failed to list offers: {0}".format(str(exc))) + + if response: + for item in response: + results.append(self.serialize_obj(item, 'VirtualMachineImageResource', + enum_modules=AZURE_ENUM_MODULES)) + return results + + def list_publishers(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_images.list_publishers(self.location) + except CloudError: + pass + except Exception as exc: + self.fail("Failed to list publishers: {0}".format(str(exc))) + + if response: + for item in response: + results.append(self.serialize_obj(item, 'VirtualMachineImageResource', + enum_modules=AZURE_ENUM_MODULES)) + return results + + +def main(): + AzureRMVirtualMachineImageInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachinescaleset.py b/library/azure_rm_virtualmachinescaleset.py index 8e8596d..24396ec 100644 --- a/library/azure_rm_virtualmachinescaleset.py +++ b/library/azure_rm_virtualmachinescaleset.py @@ -890,7 +890,7 @@ class AzureRMVirtualMachineScaleSet(AzureRMModuleBase): create_option=self.compute_models.DiskCreateOptionTypes.empty, disk_size_gb=data_disk['disk_size_gb'], managed_disk=self.compute_models.VirtualMachineScaleSetManagedDiskParameters( - storage_account_type=data_disk['managed_disk_type'] + storage_account_type=data_disk.get('managed_disk_type', None) ), )) vmss_resource.virtual_machine_profile.storage_profile.data_disks = data_disks diff --git a/library/azure_rm_virtualmachinescaleset_info.py b/library/azure_rm_virtualmachinescaleset_info.py new file mode 100644 index 0000000..849b35e --- /dev/null +++ b/library/azure_rm_virtualmachinescaleset_info.py @@ -0,0 +1,441 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2017, Sertac Ozercan +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachinescaleset_info + +version_added: "2.9" + +short_description: Get Virtual Machine Scale Set facts + +description: + - Get facts for a virtual machine scale set. + - Note that this module was called M(azure_rm_virtualmachine_scaleset_facts) before Ansible 2.8. The usage did not change. + +options: + name: + description: + - Limit results to a specific virtual machine scale set. + resource_group: + description: + - The resource group to search for the desired virtual machine scale set. + tags: + description: + - List of tags to be matched. + format: + description: + - Format of the data returned. + - If C(raw) is selected information will be returned in raw format from Azure Python SDK. + - If C(curated) is selected the structure will be identical to input parameters of M(azure_rm_virtualmachinescaleset) module. + - In Ansible 2.5 and lower facts are always returned in raw format. + - Please note that this option will be deprecated in 2.10 when curated format will become the only supported format. + default: 'raw' + choices: + - 'curated' + - 'raw' + version_added: "2.6" + +extends_documentation_fragment: + - azure + +author: + - Sertac Ozercan (@sozercan) +''' + +EXAMPLES = ''' + - name: Get facts for a virtual machine scale set + azure_rm_virtualmachinescaleset_info: + resource_group: myResourceGroup + name: testvmss001 + format: curated + + - name: Get facts for all virtual networks + azure_rm_virtualmachinescaleset_info: + resource_group: myResourceGroup + + - name: Get facts by tags + azure_rm_virtualmachinescaleset_info: + resource_group: myResourceGroup + tags: + - testing +''' + +RETURN = ''' +vmss: + description: + - List of virtual machine scale sets. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/scalesets/myscaleset + admin_username: + description: + - Admin username used to access the host after it is created. + returned: always + type: str + sample: adminuser + capacity: + description: + - Capacity of VMSS. + returned: always + type: int + sample: 2 + data_disks: + description: + - List of attached data disks. + returned: always + type: complex + contains: + caching: + description: + - Type of data disk caching. + returned: always + type: str + sample: ReadOnly + disk_size_gb: + description: + - The initial disk size in GB for blank data disks. + returned: always + type: int + sample: 64 + lun: + description: + - The logical unit number for data disk. + returned: always + type: int + sample: 0 + managed_disk_type: + description: + - Managed data disk type. + returned: always + type: str + sample: Standard_LRS + image: + description: + - Image specification. + returned: always + type: complex + contains: + offer: + description: + - The offer of the platform image or marketplace image used to create the virtual machine. + returned: always + type: str + sample: RHEL + publisher: + description: + - Publisher name. + returned: always + type: str + sample: RedHat + sku: + description: + - SKU name. + returned: always + type: str + sample: 7-RAW + version: + description: + - Image version. + returned: always + type: str + sample: 7.5.2018050901 + load_balancer: + description: + - Load balancer name. + returned: always + type: str + sample: testlb + location: + description: + - Resource location. + type: str + returned: always + sample: japaneast + managed_disk_type: + description: + - Managed data disk type. + type: str + returned: always + sample: Standard_LRS + name: + description: + - Resource name. + returned: always + type: str + sample: myvmss + os_disk_caching: + description: + - Type of OS disk caching. + type: str + returned: always + sample: ReadOnly + os_type: + description: + - Base type of operating system. + type: str + returned: always + sample: Linux + overprovision: + description: + - Specifies whether the Virtual Machine Scale Set should be overprovisioned. + type: bool + sample: true + resource_group: + description: + - Resource group. + type: str + returned: always + sample: myResourceGroup + ssh_password_enabled: + description: + - Is SSH password authentication enabled. Valid only for Linux. + type: bool + returned: always + sample: true + subnet_name: + description: + - Subnet name. + type: str + returned: always + sample: testsubnet + tier: + description: + - SKU Tier. + type: str + returned: always + sample: Basic + upgrade_policy: + description: + - Upgrade policy. + type: str + returned: always + sample: Manual + virtual_network_name: + description: + - Associated virtual network name. + type: str + returned: always + sample: testvn + vm_size: + description: + - Virtual machine size. + type: str + returned: always + sample: Standard_D4 + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + returned: always + type: dict + sample: { "tag1": "abc" } +''' # NOQA + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase +import re + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # handled in azure_rm_common + pass + +AZURE_OBJECT_CLASS = 'VirtualMachineScaleSet' + +AZURE_ENUM_MODULES = ['azure.mgmt.compute.models'] + + +class AzureRMVirtualMachineScaleSetInfo(AzureRMModuleBase): + """Utility class to get virtual machine scale set facts""" + + def __init__(self): + + self.module_args = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list'), + format=dict( + type='str', + choices=['curated', + 'raw'], + default='raw' + ) + ) + + self.results = dict( + changed=False, + ansible_facts=dict( + azure_vmss=[] + ) + ) + + self.name = None + self.resource_group = None + self.format = None + self.tags = None + + super(AzureRMVirtualMachineScaleSetInfo, self).__init__( + derived_arg_spec=self.module_args, + supports_tags=False, + facts_module=True + ) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescaleset_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescaleset_facts' module has been renamed to 'azure_rm_virtualmachinescaleset_info'", + version='2.13') + + for key in self.module_args: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail("Parameter error: resource group required when filtering by name.") + + if is_old_facts: + if self.name: + self.results['ansible_facts']['azure_vmss'] = self.get_item() + else: + self.results['ansible_facts']['azure_vmss'] = self.list_items() + else: + if self.name: + self.results['vmss'] = self.get_item() + else: + self.results['vmss'] = self.list_items() + + if self.format == 'curated': + for index in range(len(self.results['ansible_facts']['azure_vmss'])): + vmss = self.results['ansible_facts']['azure_vmss'][index] + subnet_name = None + load_balancer_name = None + virtual_network_name = None + ssh_password_enabled = False + + try: + subnet_id = (vmss['properties']['virtualMachineProfile']['networkProfile']['networkInterfaceConfigurations'][0] + ['properties']['ipConfigurations'][0]['properties']['subnet']['id']) + subnet_name = re.sub('.*subnets\\/', '', subnet_id) + except Exception: + self.log('Could not extract subnet name') + + try: + backend_address_pool_id = (vmss['properties']['virtualMachineProfile']['networkProfile']['networkInterfaceConfigurations'][0] + ['properties']['ipConfigurations'][0]['properties']['loadBalancerBackendAddressPools'][0]['id']) + load_balancer_name = re.sub('\\/backendAddressPools.*', '', re.sub('.*loadBalancers\\/', '', backend_address_pool_id)) + virtual_network_name = re.sub('.*virtualNetworks\\/', '', re.sub('\\/subnets.*', '', subnet_id)) + except Exception: + self.log('Could not extract load balancer / virtual network name') + + try: + ssh_password_enabled = (not vmss['properties']['virtualMachineProfile']['osProfile'] + ['linuxConfiguration']['disablePasswordAuthentication']) + except Exception: + self.log('Could not extract SSH password enabled') + + data_disks = vmss['properties']['virtualMachineProfile']['storageProfile'].get('dataDisks', []) + + for disk_index in range(len(data_disks)): + old_disk = data_disks[disk_index] + new_disk = { + 'lun': old_disk['lun'], + 'disk_size_gb': old_disk['diskSizeGB'], + 'managed_disk_type': old_disk['managedDisk']['storageAccountType'], + 'caching': old_disk['caching'] + } + data_disks[disk_index] = new_disk + + updated = { + 'id': vmss['id'], + 'resource_group': self.resource_group, + 'name': vmss['name'], + 'state': 'present', + 'location': vmss['location'], + 'vm_size': vmss['sku']['name'], + 'capacity': vmss['sku']['capacity'], + 'tier': vmss['sku']['tier'], + 'upgrade_policy': vmss['properties']['upgradePolicy']['mode'], + 'admin_username': vmss['properties']['virtualMachineProfile']['osProfile']['adminUsername'], + 'admin_password': vmss['properties']['virtualMachineProfile']['osProfile'].get('adminPassword'), + 'ssh_password_enabled': ssh_password_enabled, + 'image': vmss['properties']['virtualMachineProfile']['storageProfile']['imageReference'], + 'os_disk_caching': vmss['properties']['virtualMachineProfile']['storageProfile']['osDisk']['caching'], + 'os_type': 'Linux' if (vmss['properties']['virtualMachineProfile']['osProfile'].get('linuxConfiguration') is not None) else 'Windows', + 'overprovision': vmss['properties']['overprovision'], + 'managed_disk_type': vmss['properties']['virtualMachineProfile']['storageProfile']['osDisk']['managedDisk']['storageAccountType'], + 'data_disks': data_disks, + 'virtual_network_name': virtual_network_name, + 'subnet_name': subnet_name, + 'load_balancer': load_balancer_name, + 'tags': vmss.get('tags') + } + + self.results['ansible_facts']['azure_vmss'][index] = updated + + # proper result format we want to support in the future + # dropping 'ansible_facts' and shorter name 'vmss' + self.results['vmss'] = self.results['ansible_facts']['azure_vmss'] + if not is_old_facts: + self.results.pop('ansible_facts', None) + + return self.results + + def get_item(self): + """Get a single virtual machine scale set""" + + self.log('Get properties for {0}'.format(self.name)) + + item = None + results = [] + + try: + item = self.compute_client.virtual_machine_scale_sets.get(self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + results = [self.serialize_obj(item, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES)] + + return results + + def list_items(self): + """Get all virtual machine scale sets""" + + self.log('List all virtual machine scale sets') + + try: + response = self.compute_client.virtual_machine_scale_sets.list(self.resource_group) + except CloudError as exc: + self.fail('Failed to list all items - {0}'.format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(self.serialize_obj(item, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES)) + + return results + + +def main(): + """Main module execution code path""" + + AzureRMVirtualMachineScaleSetInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachinescalesetextension_info.py b/library/azure_rm_virtualmachinescalesetextension_info.py new file mode 100644 index 0000000..a5e11d1 --- /dev/null +++ b/library/azure_rm_virtualmachinescalesetextension_info.py @@ -0,0 +1,228 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Zim Kalinowski, (@zikalino) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachinescalesetextension_info +version_added: "2.9" +short_description: Get Azure Virtual Machine Scale Set Extension facts +description: + - Get facts of Azure Virtual Machine Scale Set Extension. + +options: + resource_group: + description: + - The name of the resource group. + required: True + vmss_name: + description: + - The name of VMSS containing the extension. + required: True + name: + description: + - The name of the virtual machine extension. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: Get information on specific Virtual Machine Scale Set Extension + azure_rm_virtualmachineextension_info: + resource_group: myResourceGroup + vmss_name: myvmss + name: myextension + + - name: List installed Virtual Machine Scale Set Extensions + azure_rm_virtualmachineextension_info: + resource_group: myrg + vmss_name: myvmss +''' + +RETURN = ''' +extensions: + description: + - A list of dictionaries containing facts for Virtual Machine Extension. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/ + myvmss/extensions/myextension" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: myrg + vmss_name: + description: + - Virtual machine scale set name. + returned: always + type: str + sample: myvmss + name: + description: + - Virtual machine extension name. + returned: always + type: str + sample: myextension + publisher: + description: + - Extension publisher. + returned: always + type: str + sample: Microsoft.Azure.Extensions + type: + description: + - Extension type. + returned: always + type: str + sample: CustomScript + settings: + description: + - Extension specific settings dictionary. + returned: always + type: dict + sample: { 'commandToExecute':'hostname' } + auto_upgrade_minor_version: + description: + - Autoupgrade minor version flag. + returned: always + type: bool + sample: true + provisioning_state: + description: + - Provisioning state of the extension. + returned: always + type: str + sample: Succeeded +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMVirtualMachineScaleSetExtensionInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + vmss_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.vmss_name = None + self.name = None + super(AzureRMVirtualMachineScaleSetExtensionInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescalesetextension_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescalesetextension_facts' module has been renamed to" + + " 'azure_rm_virtualmachinescalesetextension_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + self.results['extensions'] = self.get_extensions() + else: + self.results['extensions'] = self.list_extensions() + + return self.results + + def get_extensions(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_scale_set_extensions.get(resource_group_name=self.resource_group, + vm_scale_set_name=self.vmss_name, + vmss_extension_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine Extension.') + + if response: + results.append(self.format_response(response)) + + return results + + def list_extensions(self): + response = None + results = [] + try: + response = self.compute_client.virtual_machine_scale_set_extensions.list(resource_group_name=self.resource_group, + vm_scale_set_name=self.vmss_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine Extension.') + + if response is not None: + for item in response: + results.append(self.format_response(item)) + + return results + + def format_response(self, item): + id_template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachineScaleSets/{2}/extensions/{3}" + d = item.as_dict() + d = { + 'id': id_template.format(self.subscription_id, self.resource_group, self.vmss_name, d.get('name')), + 'resource_group': self.resource_group, + 'vmss_name': self.vmss_name, + 'name': d.get('name'), + 'publisher': d.get('publisher'), + 'type': d.get('type'), + 'settings': d.get('settings'), + 'auto_upgrade_minor_version': d.get('auto_upgrade_minor_version'), + 'provisioning_state': d.get('provisioning_state') + } + return d + + +def main(): + AzureRMVirtualMachineScaleSetExtensionInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualmachinescalesetinstance_info.py b/library/azure_rm_virtualmachinescalesetinstance_info.py new file mode 100644 index 0000000..12a8e3e --- /dev/null +++ b/library/azure_rm_virtualmachinescalesetinstance_info.py @@ -0,0 +1,234 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Zim Kalinowski, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualmachinescalesetinstance_info +version_added: "2.9" +short_description: Get Azure Virtual Machine Scale Set Instance facts +description: + - Get facts of Azure Virtual Machine Scale Set VMs. + +options: + resource_group: + description: + - The name of the resource group. + required: True + vmss_name: + description: + - The name of the VM scale set. + required: True + instance_id: + description: + - The instance ID of the virtual machine. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Zim Kalinowski (@zikalino) + +''' + +EXAMPLES = ''' + - name: List VM instances in Virtual Machine ScaleSet + azure_rm_computevirtualmachinescalesetinstance_info: + resource_group: myResourceGroup + vmss_name: myVMSS +''' + +RETURN = ''' +instances: + description: + - A list of dictionaries containing facts for Virtual Machine Scale Set VM. + returned: always + type: complex + contains: + id: + description: + - Resource ID. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/my + VMSS/virtualMachines/2" + tags: + description: + - Resource tags. + returned: always + type: dict + sample: { 'tag1': 'abc' } + instance_id: + description: + - Virtual Machine instance ID. + returned: always + type: str + sample: 0 + name: + description: + - Virtual Machine name. + returned: always + type: str + sample: myVMSS_2 + latest_model: + description: + - Whether applied latest model. + returned: always + type: bool + sample: True + provisioning_state: + description: + - Provisioning state of the Virtual Machine. + returned: always + type: str + sample: Succeeded + power_state: + description: + - Provisioning state of the Virtual Machine's power. + returned: always + type: str + sample: running + vm_id: + description: + - Virtual Machine ID + returned: always + type: str + sample: 94a141a9-4530-46ac-b151-2c7ff09aa823 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.compute import ComputeManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMVirtualMachineScaleSetVMInfo(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + vmss_name=dict( + type='str', + required=True + ), + instance_id=dict( + type='str' + ), + tags=dict( + type='list' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.mgmt_client = None + self.resource_group = None + self.vmss_name = None + self.instance_id = None + self.tags = None + super(AzureRMVirtualMachineScaleSetVMInfo, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualmachinescalesetinstance_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualmachinescalesetinstance_facts' module has been renamed to" + + " 'azure_rm_virtualmachinescalesetinstance_info'", + version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + self.mgmt_client = self.get_mgmt_svc_client(ComputeManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + if (self.instance_id is None): + self.results['instances'] = self.list() + else: + self.results['instances'] = self.get() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mgmt_client.virtual_machine_scale_set_vms.get(resource_group_name=self.resource_group, + vm_scale_set_name=self.vmss_name, + instance_id=self.instance_id) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine Scale Set VM.') + + if response and self.has_tags(response.tags, self.tags): + results.append(self.format_response(response)) + + return results + + def list(self): + items = None + try: + items = self.mgmt_client.virtual_machine_scale_set_vms.list(resource_group_name=self.resource_group, + virtual_machine_scale_set_name=self.vmss_name) + self.log("Response : {0}".format(items)) + except CloudError as e: + self.log('Could not get facts for Virtual Machine ScaleSet VM.') + + results = [] + for item in items: + if self.has_tags(item.tags, self.tags): + results.append(self.format_response(item)) + return results + + def format_response(self, item): + d = item.as_dict() + + iv = self.mgmt_client.virtual_machine_scale_set_vms.get_instance_view(resource_group_name=self.resource_group, + vm_scale_set_name=self.vmss_name, + instance_id=d.get('instance_id', None)).as_dict() + power_state = "" + for index in range(len(iv['statuses'])): + code = iv['statuses'][index]['code'].split('/') + if code[0] == 'PowerState': + power_state = code[1] + break + d = { + 'resource_group': self.resource_group, + 'id': d.get('id', None), + 'tags': d.get('tags', None), + 'instance_id': d.get('instance_id', None), + 'latest_model': d.get('latest_model_applied', None), + 'name': d.get('name', None), + 'provisioning_state': d.get('provisioning_state', None), + 'power_state': power_state, + 'vm_id': d.get('vm_id', None) + } + return d + + +def main(): + AzureRMVirtualMachineScaleSetVMInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualnetwork_info.py b/library/azure_rm_virtualnetwork_info.py new file mode 100644 index 0000000..5e785ff --- /dev/null +++ b/library/azure_rm_virtualnetwork_info.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# +# Copyright (c) 2016 Matt Davis, +# Chris Houseknecht, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualnetwork_info + +version_added: "2.9" + +short_description: Get virtual network facts + +description: + - Get facts for a specific virtual network or all virtual networks within a resource group. + +options: + name: + description: + - Only show results for a specific security group. + resource_group: + description: + - Limit results by resource group. Required when filtering by name. + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Chris Houseknecht (@chouseknecht) + - Matt Davis (@nitzmahone) + +''' + +EXAMPLES = ''' + - name: Get facts for one virtual network + azure_rm_virtualnetwork_info: + resource_group: myResourceGroup + name: secgroup001 + + - name: Get facts for all virtual networks + azure_rm_virtualnetwork_info: + resource_group: myResourceGroup + + - name: Get facts by tags + azure_rm_virtualnetwork_info: + tags: + - testing +''' +RETURN = ''' +azure_virtualnetworks: + description: + - List of virtual network dicts. + returned: always + type: list + example: [{ + "etag": 'W/"532ba1be-ae71-40f2-9232-3b1d9cf5e37e"', + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet2001", + "location": "eastus2", + "name": "vnet2001", + "properties": { + "addressSpace": { + "addressPrefixes": [ + "10.10.0.0/16" + ] + }, + "provisioningState": "Succeeded", + "resourceGuid": "a7ba285f-f7e7-4e17-992a-de4d39f28612", + "subnets": [] + }, + "type": "Microsoft.Network/virtualNetworks" + }] +virtualnetworks: + description: + - List of virtual network dicts with same format as M(azure_rm_virtualnetwork) module parameters. + returned: always + type: complex + contains: + id: + description: + - Resource ID of the virtual network. + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/vnet2001 + returned: always + type: str + address_prefixes: + description: + - List of IPv4 address ranges where each is formatted using CIDR notation. + sample: ["10.10.0.0/16"] + returned: always + type: list + dns_servers: + description: + - Custom list of DNS servers. + returned: always + type: list + sample: ["www.azure.com"] + location: + description: + - Valid Azure location. + returned: always + type: str + sample: eastus + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + returned: always + type: dict + sample: { "tag1": "abc" } + provisioning_state: + description: + - Provisioning state of the resource. + returned: always + sample: Succeeded + type: str + name: + description: + - Name of the virtual network. + returned: always + type: str + sample: foo + subnets: + description: + - Subnets associated with the virtual network. + returned: always + type: list + contains: + id: + description: + - Resource ID of the subnet. + returned: always + type: str + sample: "/subscriptions/f64d4ee8-be94-457d-ba26-3fa6b6506cef/resourceGroups/v-xisuRG/providers/ + Microsoft.Network/virtualNetworks/vnetb57dc95232/subnets/vnetb57dc95232" + name: + description: + - Name of the subnet. + returned: always + type: str + sample: vnetb57dc95232 + provisioning_state: + description: + - Provisioning state of the subnet. + returned: always + type: str + sample: Succeeded + address_prefix: + description: + - The address prefix for the subnet. + returned: always + type: str + sample: '10.1.0.0/16' + network_security_group: + description: + - Existing security group ID with which to associate the subnet. + returned: always + type: str + sample: null + route_table: + description: + - The reference of the RouteTable resource. + returned: always + type: str + sample: null + service_endpoints: + description: + - An array of service endpoints. + returned: always + type: list + sample: [ + { + "locations": [ + "southeastasia", + "eastasia" + ], + "service": "Microsoft.Storage" + } + ] +''' + +try: + from msrestazure.azure_exceptions import CloudError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +AZURE_OBJECT_CLASS = 'VirtualNetwork' + + +class AzureRMNetworkInterfaceInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list'), + ) + + self.results = dict( + changed=False, + ansible_facts=dict(azure_virtualnetworks=[]), + virtualnetworks=[] + ) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzureRMNetworkInterfaceInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_virtualnetwork_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualnetwork_facts' module has been renamed to 'azure_rm_virtualnetwork_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name is not None: + results = self.get_item() + elif self.resource_group is not None: + results = self.list_resource_group() + else: + results = self.list_items() + + if is_old_facts: + self.results['ansible_facts']['azure_virtualnetworks'] = self.serialize(results) + self.results['virtualnetworks'] = self.curated(results) + + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + results = [] + + try: + item = self.network_client.virtual_networks.get(self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + results = [item] + return results + + def list_resource_group(self): + self.log('List items for resource group') + try: + response = self.network_client.virtual_networks.list(self.resource_group) + except CloudError as exc: + self.fail("Failed to list for resource group {0} - {1}".format(self.resource_group, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def list_items(self): + self.log('List all for items') + try: + response = self.network_client.virtual_networks.list_all() + except CloudError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def serialize(self, raws): + self.log("Serialize all items") + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) for item in raws] if raws else [] + + def curated(self, raws): + self.log("Format all items") + return [self.virtualnetwork_to_dict(x) for x in raws] if raws else [] + + def virtualnetwork_to_dict(self, vnet): + results = dict( + id=vnet.id, + name=vnet.name, + location=vnet.location, + tags=vnet.tags, + provisioning_state=vnet.provisioning_state + ) + if vnet.dhcp_options and len(vnet.dhcp_options.dns_servers) > 0: + results['dns_servers'] = [] + for server in vnet.dhcp_options.dns_servers: + results['dns_servers'].append(server) + if vnet.address_space and len(vnet.address_space.address_prefixes) > 0: + results['address_prefixes'] = [] + for space in vnet.address_space.address_prefixes: + results['address_prefixes'].append(space) + if vnet.subnets and len(vnet.subnets) > 0: + results['subnets'] = [self.subnet_to_dict(x) for x in vnet.subnets] + return results + + def subnet_to_dict(self, subnet): + result = dict( + id=subnet.id, + name=subnet.name, + provisioning_state=subnet.provisioning_state, + address_prefix=subnet.address_prefix, + network_security_group=subnet.network_security_group.id if subnet.network_security_group else None, + route_table=subnet.route_table.id if subnet.route_table else None + ) + if subnet.service_endpoints: + result['service_endpoints'] = [{'service': item.service, 'locations': item.locations} for item in subnet.service_endpoints] + return result + + +def main(): + AzureRMNetworkInterfaceInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_virtualnetworkpeering_info.py b/library/azure_rm_virtualnetworkpeering_info.py new file mode 100644 index 0000000..4548894 --- /dev/null +++ b/library/azure_rm_virtualnetworkpeering_info.py @@ -0,0 +1,256 @@ +#!/usr/bin/python +# +# Copyright (c) 2019 Yunge Zhu (@yungezz) +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_virtualnetworkpeering_info +version_added: "2.9" +short_description: Get facts of Azure Virtual Network Peering +description: + - Get facts of Azure Virtual Network Peering. + +options: + resource_group: + description: + - Name of a resource group where the vnet exists. + required: True + virtual_network: + description: + - Name or resource ID of a virtual network. + required: True + name: + description: + - Name of the virtual network peering. + +extends_documentation_fragment: + - azure + +author: + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get virtual network peering by name + azure_rm_virtualnetworkpeering_info: + resource_group: myResourceGroup + virtual_network: myVnet1 + name: myVnetPeer + + - name: List virtual network peering of virtual network + azure_rm_virtualnetworkpeering: + resource_group: myResourceGroup + virtual_network: myVnet1 +''' + +RETURN = ''' +vnetpeerings: + description: + - A list of Virtual Network Peering facts. + returned: always + type: complex + contains: + id: + description: ID of current Virtual Network peering. + returned: always + type: str + sample: + "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/virtualNetworkPeerings/peer1" + name: + description: + - Name of Virtual Network peering. + returned: always + type: str + sample: myPeering + remote_virtual_network: + description: + - ID of remote Virtual Network to be peered to. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet2 + remote_address_space: + description: + - The reference of the remote Virtual Network address space. + type: complex + returned: always + contains: + address_prefixes: + description: + - A list of address blocks reserved for this Virtual Network in CIDR notation. + returned: always + type: list + sample: 10.1.0.0/16 + peering_state: + description: + - The state of the virtual network peering. + returned: always + type: str + sample: Connected + provisioning_state: + description: + - The provisioning state of the resource. + returned: always + type: str + sample: Succeeded + allow_forwarded_traffic: + description: + - Whether forwarded traffic from the VMs in the remote Virtual Network will be allowed/disallowed. + returned: always + type: bool + sample: False + allow_gateway_transit: + description: + - Whether gateway links can be used in remote Virtual Networking to link to this Virtual Network. + returned: always + type: bool + sample: False + allow_virtual_network_access: + description: + - Whether the VMs in the linked Virtual Network space can access all the VMs in local Virtual Network space. + returned: always + type: bool + sample: False + use_remote_gateways: + description: + - Whether remote gateways can be used on this Virtual Network. + returned: always + type: bool + sample: False +''' + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.polling import LROPoller +except ImportError: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + + +def vnetpeering_to_dict(vnetpeering): + ''' + Convert a virtual network peering object to a dict. + ''' + results = dict( + id=vnetpeering.id, + name=vnetpeering.name, + remote_virtual_network=vnetpeering.remote_virtual_network.id, + remote_address_space=dict( + address_prefixes=vnetpeering.remote_address_space.address_prefixes + ), + peering_state=vnetpeering.peering_state, + provisioning_state=vnetpeering.provisioning_state, + use_remote_gateways=vnetpeering.use_remote_gateways, + allow_gateway_transit=vnetpeering.allow_gateway_transit, + allow_forwarded_traffic=vnetpeering.allow_forwarded_traffic, + allow_virtual_network_access=vnetpeering.allow_virtual_network_access + ) + return results + + +class AzureRMVirtualNetworkPeeringInfo(AzureRMModuleBase): + + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + name=dict( + type='str' + ), + virtual_network=dict( + type='raw', + required=True + ) + ) + + self.resource_group = None + self.name = None + self.virtual_network = None + + self.results = dict(changed=False) + + super(AzureRMVirtualNetworkPeeringInfo, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_tags=False) + + def exec_module(self, **kwargs): + """Main module execution method""" + is_old_facts = self.module._name == 'azure_rm_virtualnetworkpeering_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_virtualnetworkpeering_facts' module has been renamed to 'azure_rm_virtualnetworkpeering_info'", version='2.13') + + for key in list(self.module_arg_spec.keys()): + setattr(self, key, kwargs[key]) + + # parse virtual_network + self.virtual_network = self.parse_resource_to_dict(self.virtual_network) + if self.virtual_network['resource_group'] != self.resource_group: + self.fail('Resource group of virtual_network is not same as param resource_group') + + self.results['vnetpeerings'] = [] + # get vnet peering + if self.name: + self.results['vnetpeerings'] = self.get_by_name() + else: + self.results['vnetpeerings'] = self.list_by_vnet() + + return self.results + + def get_by_name(self): + ''' + Gets the Virtual Network Peering. + + :return: List of Virtual Network Peering + ''' + self.log( + "Get Virtual Network Peering {0}".format(self.name)) + results = [] + try: + response = self.network_client.virtual_network_peerings.get(resource_group_name=self.resource_group, + virtual_network_name=self.virtual_network['name'], + virtual_network_peering_name=self.name) + self.log("Response : {0}".format(response)) + results.append(vnetpeering_to_dict(response)) + except CloudError: + self.log('Did not find the Virtual Network Peering.') + return results + + def list_by_vnet(self): + ''' + Lists the Virtual Network Peering in specific Virtual Network. + + :return: List of Virtual Network Peering + ''' + self.log( + "List Virtual Network Peering in Virtual Network {0}".format(self.virtual_network['name'])) + results = [] + try: + response = self.network_client.virtual_network_peerings.list(resource_group_name=self.resource_group, + virtual_network_name=self.virtual_network['name']) + self.log("Response : {0}".format(response)) + if response: + for p in response: + results.append(vnetpeering_to_dict(p)) + except CloudError: + self.log('Did not find the Virtual Network Peering.') + return results + + +def main(): + """Main execution""" + AzureRMVirtualNetworkPeeringInfo() + + +if __name__ == '__main__': + main() diff --git a/library/azure_rm_webapp_info.py b/library/azure_rm_webapp_info.py new file mode 100644 index 0000000..4a3b4cd --- /dev/null +++ b/library/azure_rm_webapp_info.py @@ -0,0 +1,488 @@ +#!/usr/bin/python +# +# Copyright (c) 2018 Yunge Zhu, +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +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_webapp_info + +version_added: "2.9" + +short_description: Get Azure web app facts + +description: + - Get facts for a specific web app or all web app in a resource group, or all web app in current subscription. + +options: + name: + description: + - Only show results for a specific web app. + resource_group: + description: + - Limit results by resource group. + return_publish_profile: + description: + - Indicate whether to return publishing profile of the web app. + default: False + type: bool + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + +extends_documentation_fragment: + - azure + +author: + - Yunge Zhu (@yungezz) +''' + +EXAMPLES = ''' + - name: Get facts for web app by name + azure_rm_webapp_info: + resource_group: myResourceGroup + name: winwebapp1 + + - name: Get facts for web apps in resource group + azure_rm_webapp_info: + resource_group: myResourceGroup + + - name: Get facts for web apps with tags + azure_rm_webapp_info: + tags: + - testtag + - foo:bar +''' + +RETURN = ''' +webapps: + description: + - List of web apps. + returned: always + type: complex + contains: + id: + description: + - ID of the web app. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Web/sites/myWebApp + name: + description: + - Name of the web app. + returned: always + type: str + sample: winwebapp1 + resource_group: + description: + - Resource group of the web app. + returned: always + type: str + sample: myResourceGroup + location: + description: + - Location of the web app. + returned: always + type: str + sample: eastus + plan: + description: + - ID of app service plan used by the web app. + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan + app_settings: + description: + - App settings of the application. Only returned when web app has app settings. + returned: always + type: dict + sample: { + "testkey": "testvalue", + "testkey2": "testvalue2" + } + frameworks: + description: + - Frameworks of the application. Only returned when web app has frameworks. + returned: always + type: list + sample: [ + { + "name": "net_framework", + "version": "v4.0" + }, + { + "name": "java", + "settings": { + "java_container": "tomcat", + "java_container_version": "8.5" + }, + "version": "1.7" + }, + { + "name": "php", + "version": "5.6" + } + ] + availability_state: + description: + - Availability of this web app. + returned: always + type: str + sample: Normal + default_host_name: + description: + - Host name of the web app. + returned: always + type: str + sample: vxxisurg397winapp4.azurewebsites.net + enabled: + description: + - Indicates the web app enabled or not. + returned: always + type: bool + sample: true + enabled_host_names: + description: + - Enabled host names of the web app. + returned: always + type: list + sample: [ + "vxxisurg397winapp4.azurewebsites.net", + "vxxisurg397winapp4.scm.azurewebsites.net" + ] + host_name_ssl_states: + description: + - SSL state per host names of the web app. + returned: always + type: list + sample: [ + { + "hostType": "Standard", + "name": "vxxisurg397winapp4.azurewebsites.net", + "sslState": "Disabled" + }, + { + "hostType": "Repository", + "name": "vxxisurg397winapp4.scm.azurewebsites.net", + "sslState": "Disabled" + } + ] + host_names: + description: + - Host names of the web app. + returned: always + type: list + sample: [ + "vxxisurg397winapp4.azurewebsites.net" + ] + outbound_ip_addresses: + description: + - Outbound IP address of the web app. + returned: always + type: str + sample: "40.71.11.131,40.85.166.200,168.62.166.67,137.135.126.248,137.135.121.45" + ftp_publish_url: + description: + - Publishing URL of the web app when deployment type is FTP. + returned: always + type: str + sample: ftp://xxxx.ftp.azurewebsites.windows.net + state: + description: + - State of the web app. + returned: always + type: str + sample: running + publishing_username: + description: + - Publishing profile user name. + returned: only when I(return_publish_profile=True). + type: str + sample: "$vxxisuRG397winapp4" + publishing_password: + description: + - Publishing profile password. + returned: only when I(return_publish_profile=True). + type: str + sample: "uvANsPQpGjWJmrFfm4Ssd5rpBSqGhjMk11pMSgW2vCsQtNx9tcgZ0xN26s9A" + tags: + description: + - Tags assigned to the resource. Dictionary of string:string pairs. + returned: always + type: dict + sample: { tag1: abc } +''' +try: + from msrestazure.azure_exceptions import CloudError + from msrest.polling import LROPoller + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +AZURE_OBJECT_CLASS = 'WebApp' + + +class AzureRMWebAppInfo(AzureRMModuleBase): + + def __init__(self): + + self.module_arg_spec = dict( + name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list'), + return_publish_profile=dict(type='bool', default=False), + ) + + self.results = dict( + changed=False, + webapps=[], + ) + + self.name = None + self.resource_group = None + self.tags = None + self.return_publish_profile = False + + self.framework_names = ['net_framework', 'java', 'php', 'node', 'python', 'dotnetcore', 'ruby'] + + super(AzureRMWebAppInfo, self).__init__(self.module_arg_spec, + supports_tags=False, + facts_module=True) + + def exec_module(self, **kwargs): + is_old_facts = self.module._name == 'azure_rm_webapp_facts' + if is_old_facts: + self.module.deprecate("The 'azure_rm_webapp_facts' module has been renamed to 'azure_rm_webapp_info'", version='2.13') + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name: + self.results['webapps'] = self.list_by_name() + elif self.resource_group: + self.results['webapps'] = self.list_by_resource_group() + else: + self.results['webapps'] = self.list_all() + + return self.results + + def list_by_name(self): + self.log('Get web app {0}'.format(self.name)) + item = None + result = [] + + try: + item = self.web_client.web_apps.get(self.resource_group, self.name) + except CloudError: + pass + + if item and self.has_tags(item.tags, self.tags): + curated_result = self.get_curated_webapp(self.resource_group, self.name, item) + result = [curated_result] + + return result + + def list_by_resource_group(self): + self.log('List web apps in resource groups {0}'.format(self.resource_group)) + try: + response = list(self.web_client.web_apps.list_by_resource_group(self.resource_group)) + except CloudError as exc: + request_id = exc.request_id if exc.request_id else '' + self.fail("Error listing web apps in resource groups {0}, request id: {1} - {2}".format(self.resource_group, request_id, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + curated_output = self.get_curated_webapp(self.resource_group, item.name, item) + results.append(curated_output) + return results + + def list_all(self): + self.log('List web apps in current subscription') + try: + response = list(self.web_client.web_apps.list()) + except CloudError as exc: + request_id = exc.request_id if exc.request_id else '' + self.fail("Error listing web apps, request id {0} - {1}".format(request_id, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + curated_output = self.get_curated_webapp(item.resource_group, item.name, item) + results.append(curated_output) + return results + + def list_webapp_configuration(self, resource_group, name): + self.log('Get web app {0} configuration'.format(name)) + + response = [] + + try: + response = self.web_client.web_apps.get_configuration(resource_group_name=resource_group, name=name) + except CloudError as ex: + request_id = ex.request_id if ex.request_id else '' + self.fail('Error getting web app {0} configuration, request id {1} - {2}'.format(name, request_id, str(ex))) + + return response.as_dict() + + def list_webapp_appsettings(self, resource_group, name): + self.log('Get web app {0} app settings'.format(name)) + + response = [] + + try: + response = self.web_client.web_apps.list_application_settings(resource_group_name=resource_group, name=name) + except CloudError as ex: + request_id = ex.request_id if ex.request_id else '' + self.fail('Error getting web app {0} app settings, request id {1} - {2}'.format(name, request_id, str(ex))) + + return response.as_dict() + + def get_publish_credentials(self, resource_group, name): + self.log('Get web app {0} publish credentials'.format(name)) + try: + poller = self.web_client.web_apps.list_publishing_credentials(resource_group, name) + if isinstance(poller, LROPoller): + response = self.get_poller_result(poller) + except CloudError as ex: + request_id = ex.request_id if ex.request_id else '' + self.fail('Error getting web app {0} publishing credentials - {1}'.format(request_id, str(ex))) + return response + + def get_webapp_ftp_publish_url(self, resource_group, name): + import xmltodict + + self.log('Get web app {0} app publish profile'.format(name)) + + url = None + try: + content = self.web_client.web_apps.list_publishing_profile_xml_with_secrets(resource_group_name=resource_group, name=name) + if not content: + return url + + full_xml = '' + for f in content: + full_xml += f.decode() + profiles = xmltodict.parse(full_xml, xml_attribs=True)['publishData']['publishProfile'] + + if not profiles: + return url + + for profile in profiles: + if profile['@publishMethod'] == 'FTP': + url = profile['@publishUrl'] + + except CloudError as ex: + self.fail('Error getting web app {0} app settings'.format(name)) + + return url + + def get_curated_webapp(self, resource_group, name, webapp): + pip = self.serialize_obj(webapp, AZURE_OBJECT_CLASS) + + try: + site_config = self.list_webapp_configuration(resource_group, name) + app_settings = self.list_webapp_appsettings(resource_group, name) + publish_cred = self.get_publish_credentials(resource_group, name) + ftp_publish_url = self.get_webapp_ftp_publish_url(resource_group, name) + except CloudError as ex: + pass + return self.construct_curated_webapp(webapp=pip, + configuration=site_config, + app_settings=app_settings, + deployment_slot=None, + ftp_publish_url=ftp_publish_url, + publish_credentials=publish_cred) + + def construct_curated_webapp(self, + webapp, + configuration=None, + app_settings=None, + deployment_slot=None, + ftp_publish_url=None, + publish_credentials=None): + curated_output = dict() + curated_output['id'] = webapp['id'] + curated_output['name'] = webapp['name'] + curated_output['resource_group'] = webapp['properties']['resourceGroup'] + curated_output['location'] = webapp['location'] + curated_output['plan'] = webapp['properties']['serverFarmId'] + curated_output['tags'] = webapp.get('tags', None) + + # important properties from output. not match input arguments. + curated_output['app_state'] = webapp['properties']['state'] + curated_output['availability_state'] = webapp['properties']['availabilityState'] + curated_output['default_host_name'] = webapp['properties']['defaultHostName'] + curated_output['host_names'] = webapp['properties']['hostNames'] + curated_output['enabled'] = webapp['properties']['enabled'] + curated_output['enabled_host_names'] = webapp['properties']['enabledHostNames'] + curated_output['host_name_ssl_states'] = webapp['properties']['hostNameSslStates'] + curated_output['outbound_ip_addresses'] = webapp['properties']['outboundIpAddresses'] + + # curated site_config + if configuration: + curated_output['frameworks'] = [] + for fx_name in self.framework_names: + fx_version = configuration.get(fx_name + '_version', None) + if fx_version: + fx = { + 'name': fx_name, + 'version': fx_version + } + # java container setting + if fx_name == 'java': + if configuration['java_container'] and configuration['java_container_version']: + settings = { + 'java_container': configuration['java_container'].lower(), + 'java_container_version': configuration['java_container_version'] + } + fx['settings'] = settings + + curated_output['frameworks'].append(fx) + + # linux_fx_version + if configuration.get('linux_fx_version', None): + tmp = configuration.get('linux_fx_version').split("|") + if len(tmp) == 2: + curated_output['frameworks'].append({'name': tmp[0].lower(), 'version': tmp[1]}) + + # curated app_settings + if app_settings and app_settings.get('properties', None): + curated_output['app_settings'] = dict() + for item in app_settings['properties']: + curated_output['app_settings'][item] = app_settings['properties'][item] + + # curated deploymenet_slot + if deployment_slot: + curated_output['deployment_slot'] = deployment_slot + + # ftp_publish_url + if ftp_publish_url: + curated_output['ftp_publish_url'] = ftp_publish_url + + # curated publish credentials + if publish_credentials and self.return_publish_profile: + curated_output['publishing_username'] = publish_credentials.publishing_user_name + curated_output['publishing_password'] = publish_credentials.publishing_password + return curated_output + + +def main(): + AzureRMWebAppInfo() + + +if __name__ == '__main__': + main() diff --git a/module_utils/azure_rm_common.py b/module_utils/azure_rm_common.py index c51ff09..af9908b 100644 --- a/module_utils/azure_rm_common.py +++ b/module_utils/azure_rm_common.py @@ -356,7 +356,7 @@ class AzureRMModuleBase(object): try: client_module = importlib.import_module(client_type.__module__) client_version = client_module.VERSION - except RuntimeError: + except (RuntimeError, AttributeError): # can't get at the module version for some reason, just fail silently... return expected_version = package_version.get('expected_version') diff --git a/tests/integration/targets/azure_rm_availabilityset/tasks/main.yml b/tests/integration/targets/azure_rm_availabilityset/tasks/main.yml index c305047..8127d3c 100644 --- a/tests/integration/targets/azure_rm_availabilityset/tasks/main.yml +++ b/tests/integration/targets/azure_rm_availabilityset/tasks/main.yml @@ -112,9 +112,9 @@ that: - not results.changed - not results.failed - - results.ansible_facts.azure_availabilitysets[0].properties.platformFaultDomainCount == 2 - - results.ansible_facts.azure_availabilitysets[0].properties.platformUpdateDomainCount == 5 - - results.ansible_facts.azure_availabilitysets[0].sku == 'Aligned' + - results.ansible_info.azure_availabilitysets[0].properties.platformFaultDomainCount == 2 + - results.ansible_info.azure_availabilitysets[0].properties.platformUpdateDomainCount == 5 + - results.ansible_info.azure_availabilitysets[0].sku == 'Aligned' - name: Delete an availability set diff --git a/tests/integration/targets/azure_rm_cdnprofile/aliases b/tests/integration/targets/azure_rm_cdnprofile/aliases index f5c7265..ea347fa 100644 --- a/tests/integration/targets/azure_rm_cdnprofile/aliases +++ b/tests/integration/targets/azure_rm_cdnprofile/aliases @@ -1,5 +1,5 @@ cloud/azure shippable/azure/group2 destructive -azure_rm_cdnprofile_facts +azure_rm_cdnprofile_info azure_rm_cdnendpoint diff --git a/tests/integration/targets/azure_rm_cdnprofile/tasks/main.yml b/tests/integration/targets/azure_rm_cdnprofile/tasks/main.yml index 69550d9..657881a 100644 --- a/tests/integration/targets/azure_rm_cdnprofile/tasks/main.yml +++ b/tests/integration/targets/azure_rm_cdnprofile/tasks/main.yml @@ -17,7 +17,7 @@ check_mode: yes - name: Check there is no CDN profile created - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: resource_group: "{{ resource_group }}" name: "{{ cdnprofilename }}" register: fact @@ -43,7 +43,7 @@ - output.id != '' - name: Gather CDN profile facts - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: resource_group: "{{ resource_group }}" name: "{{ cdnprofilename }}" register: fact @@ -96,7 +96,7 @@ check_mode: yes - name: Gather CDN profile facts - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: resource_group: "{{ resource_group }}" name: "{{ cdnprofilename }}" register: fact @@ -144,7 +144,7 @@ - output.id - name: Get facts of a Azure CDN endpoint - azure_rm_cdnendpoint_facts: + azure_rm_cdnendpoint_info: resource_group: "{{ resource_group }}" name: "{{ endpointname }}" profile_name: "{{ cdnprofilename }}" @@ -265,7 +265,7 @@ - output.changed - name: Get CDN profile fact - azure_rm_cdnprofile_facts: + azure_rm_cdnprofile_info: resource_group: "{{ resource_group }}" name: "{{ cdnprofilename }}" register: fact diff --git a/tests/integration/targets/azure_rm_containerinstance/aliases b/tests/integration/targets/azure_rm_containerinstance/aliases index 11625e8..93066dc 100644 --- a/tests/integration/targets/azure_rm_containerinstance/aliases +++ b/tests/integration/targets/azure_rm_containerinstance/aliases @@ -1,4 +1,4 @@ cloud/azure destructive shippable/azure/group2 -azure_rm_containerinstance_facts +azure_rm_containerinstance_info diff --git a/tests/integration/targets/azure_rm_containerinstance/tasks/main.yml b/tests/integration/targets/azure_rm_containerinstance/tasks/main.yml index 13ce1a7..a76e387 100644 --- a/tests/integration/targets/azure_rm_containerinstance/tasks/main.yml +++ b/tests/integration/targets/azure_rm_containerinstance/tasks/main.yml @@ -100,7 +100,7 @@ register: output - name: Gather facts for single Container Instance - azure_rm_containerinstance_facts: + azure_rm_containerinstance_info: resource_group: "{{ resource_group }}" name: "aci{{ resource_group | hash('md5') | truncate(7, True, '') }}sec" register: output @@ -124,7 +124,7 @@ - output.containerinstances[0]['restart_policy'] == 'on_failure' - name: Gather facts for all Container Instances in the resource group - azure_rm_containerinstance_facts: + azure_rm_containerinstance_info: resource_group: "{{ resource_group }}" register: output diff --git a/tests/integration/targets/azure_rm_containerregistry/aliases b/tests/integration/targets/azure_rm_containerregistry/aliases index 394d641..2615d3f 100644 --- a/tests/integration/targets/azure_rm_containerregistry/aliases +++ b/tests/integration/targets/azure_rm_containerregistry/aliases @@ -1,4 +1,4 @@ cloud/azure shippable/azure/group2 destructive -azure_rm_containerregistry_facts +azure_rm_containerregistry_info diff --git a/tests/integration/targets/azure_rm_containerregistry/tasks/main.yml b/tests/integration/targets/azure_rm_containerregistry/tasks/main.yml index 92a5fcc..7c83c5c 100644 --- a/tests/integration/targets/azure_rm_containerregistry/tasks/main.yml +++ b/tests/integration/targets/azure_rm_containerregistry/tasks/main.yml @@ -59,7 +59,7 @@ - output.credentials['password2'] is not defined - name: Gather facts for single Container Registry - azure_rm_containerregistry_facts: + azure_rm_containerregistry_info: resource_group: "{{ resource_group }}" name: "acr{{ resource_group | hash('md5') | truncate(7, True, '') }}" register: output @@ -78,7 +78,7 @@ - output.registries[0]['credentials'] != None - name: Gather facts for all Container Registries in the resource group - azure_rm_containerregistry_facts: + azure_rm_containerregistry_info: resource_group: "{{ resource_group }}" register: output diff --git a/tests/integration/targets/azure_rm_cosmosdbaccount/aliases b/tests/integration/targets/azure_rm_cosmosdbaccount/aliases index 4d64b78..8a081bd 100644 --- a/tests/integration/targets/azure_rm_cosmosdbaccount/aliases +++ b/tests/integration/targets/azure_rm_cosmosdbaccount/aliases @@ -1,4 +1,4 @@ cloud/azure destructive shippable/azure/group1 -azure_rm_cosmosdbaccount_facts +azure_rm_cosmosdbaccount_info diff --git a/tests/integration/targets/azure_rm_cosmosdbaccount/tasks/main.yml b/tests/integration/targets/azure_rm_cosmosdbaccount/tasks/main.yml index cebf4e8..f50aa47 100644 --- a/tests/integration/targets/azure_rm_cosmosdbaccount/tasks/main.yml +++ b/tests/integration/targets/azure_rm_cosmosdbaccount/tasks/main.yml @@ -116,7 +116,7 @@ - output.changed - name: Get facts of single account - azure_rm_cosmosdbaccount_facts: + azure_rm_cosmosdbaccount_info: resource_group: "{{ resource_group }}" name: "{{ dbname }}" register: output @@ -148,7 +148,7 @@ - output.accounts[0]['tags'] != None - name: Get facts with keys - azure_rm_cosmosdbaccount_facts: + azure_rm_cosmosdbaccount_info: resource_group: "{{ resource_group }}" name: "{{ dbname }}" retrieve_keys: all @@ -164,7 +164,7 @@ - output.accounts[0]['secondary_readonly_master_key'] != None - name: Get facts with readonly keys - azure_rm_cosmosdbaccount_facts: + azure_rm_cosmosdbaccount_info: resource_group: "{{ resource_group }}" name: "{{ dbname }}" retrieve_keys: readonly @@ -182,7 +182,7 @@ - output.accounts[0]['connection_strings'] | length > 0 - name: List acounts by resource group - azure_rm_cosmosdbaccount_facts: + azure_rm_cosmosdbaccount_info: resource_group: "{{ resource_group }}" name: "{{ dbname }}" register: output diff --git a/tests/integration/targets/azure_rm_deployment/tasks/main.yml b/tests/integration/targets/azure_rm_deployment/tasks/main.yml index e24b147..fb3d195 100644 --- a/tests/integration/targets/azure_rm_deployment/tasks/main.yml +++ b/tests/integration/targets/azure_rm_deployment/tasks/main.yml @@ -29,7 +29,7 @@ with_items: "{{ output.deployment.instances }}" - name: Get Deployment Facts - azure_rm_deployment_facts: + azure_rm_deployment_info: resource_group: "{{ resource_group }}" name: "{{ dns_label }}" register: output diff --git a/tests/integration/targets/azure_rm_dnszone/aliases b/tests/integration/targets/azure_rm_dnszone/aliases index 7dfa9cf..b048b01 100644 --- a/tests/integration/targets/azure_rm_dnszone/aliases +++ b/tests/integration/targets/azure_rm_dnszone/aliases @@ -1,6 +1,6 @@ cloud/azure shippable/azure/group2 destructive -azure_rm_dnszone_facts +azure_rm_dnszone_info azure_rm_dnsrecordset -azure_rm_dnsrecordset_facts +azure_rm_dnsrecordset_info diff --git a/tests/integration/targets/azure_rm_dnszone/tasks/main.yml b/tests/integration/targets/azure_rm_dnszone/tasks/main.yml index d00b41d..03c7639 100644 --- a/tests/integration/targets/azure_rm_dnszone/tasks/main.yml +++ b/tests/integration/targets/azure_rm_dnszone/tasks/main.yml @@ -35,7 +35,7 @@ - results.state.tags.test == 'modified' - name: Retrieve DNS Zone Facts - azure_rm_dnszone_facts: + azure_rm_dnszone_info: resource_group: "{{ resource_group }}" name: "{{ domain_name }}.com" register: zones @@ -43,7 +43,7 @@ - name: Assert that facts module returned result assert: that: - - azure_dnszones[0].tags.test == 'modified' + - zones.dnszones[0].tags.test == 'modified' - zones.dnszones[0].type == 'public' - name: Create virtual network @@ -254,11 +254,11 @@ - results.changed # -# azure_rm_dnsrecordset_facts +# azure_rm_dnsrecordset_info # - name: Retrieve DNS Record Set Facts for single Record Set - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: "{{ resource_group }}" zone_name: "{{ domain_name }}.com" relative_name: www @@ -269,13 +269,13 @@ assert: that: - not results.changed - - azure_dnsrecordset[0].name == 'www' +# - azure_dnsrecordset[0].name == 'www' - results.dnsrecordsets[0].relative_name == 'www' - 'results.dnsrecordsets[0].records | length == 3' - results.dnsrecordsets[0].record_type == 'A' - name: Retrieve DNS Record Set Facts for all Record Sets - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: "{{ resource_group }}" zone_name: "{{ domain_name }}.com" register: facts @@ -284,9 +284,9 @@ assert: that: - not facts.changed - - facts.ansible_facts.azure_dnsrecordset[0].name == '@' - - facts.ansible_facts.azure_dnsrecordset[1].name == '@' - - facts.ansible_facts.azure_dnsrecordset[4].name == 'www' +# - facts.ansible_facts.azure_dnsrecordset[0].name == '@' +# - facts.ansible_facts.azure_dnsrecordset[1].name == '@' +# - facts.ansible_facts.azure_dnsrecordset[4].name == 'www' # # azure_rm_dnsrecordset cleanup @@ -308,7 +308,7 @@ that: results.changed - name: Retrieve DNS Record Set Facts for all Record Sets - azure_rm_dnsrecordset_facts: + azure_rm_dnsrecordset_info: resource_group: "{{ resource_group }}" zone_name: "{{ domain_name }}.com" register: facts diff --git a/tests/integration/targets/azure_rm_functionapp/tasks/main.yml b/tests/integration/targets/azure_rm_functionapp/tasks/main.yml index 5a42f09..cf200fb 100644 --- a/tests/integration/targets/azure_rm_functionapp/tasks/main.yml +++ b/tests/integration/targets/azure_rm_functionapp/tasks/main.yml @@ -28,7 +28,7 @@ that: output.changed - name: list facts for function - azure_rm_functionapp_facts: + azure_rm_functionapp_info: resource_group: '{{ resource_group }}' name: "{{ funcapp_name_basic }}" register: results @@ -36,8 +36,8 @@ - name: assert the facts were retrieved assert: that: - - results.ansible_facts.azure_functionapps|length == 1 - - results.ansible_facts.azure_functionapps[0].name == "{{ funcapp_name_basic }}" + - results.ansible_info.azure_functionapps|length == 1 + - results.ansible_info.azure_functionapps[0].name == "{{ funcapp_name_basic }}" - name: delete basic function app azure_rm_functionapp: diff --git a/tests/integration/targets/azure_rm_hdinsightcluster/aliases b/tests/integration/targets/azure_rm_hdinsightcluster/aliases index cb8cb9a..ef98a7b 100644 --- a/tests/integration/targets/azure_rm_hdinsightcluster/aliases +++ b/tests/integration/targets/azure_rm_hdinsightcluster/aliases @@ -2,4 +2,5 @@ cloud/azure destructive shippable/azure/group1 unstable # test is slow (~30 minute run time), not unstable, but this is better than unsupported -azure_rm_hdinsightcluster_facts +azure_rm_hdinsightcluster_info +disabled diff --git a/tests/integration/targets/azure_rm_hdinsightcluster/tasks/main.yml b/tests/integration/targets/azure_rm_hdinsightcluster/tasks/main.yml index 62c586b..2bf0a98 100644 --- a/tests/integration/targets/azure_rm_hdinsightcluster/tasks/main.yml +++ b/tests/integration/targets/azure_rm_hdinsightcluster/tasks/main.yml @@ -200,7 +200,7 @@ - output.changed - name: Get facts of Cluster - azure_rm_hdinsightcluster_facts: + azure_rm_hdinsightcluster_info: resource_group: "{{ resource_group }}" name: "cluster{{ rpfx }}" register: output diff --git a/tests/integration/targets/azure_rm_image/aliases b/tests/integration/targets/azure_rm_image/aliases index f12022f..2d7dea2 100644 --- a/tests/integration/targets/azure_rm_image/aliases +++ b/tests/integration/targets/azure_rm_image/aliases @@ -1,4 +1,4 @@ cloud/azure shippable/azure/group3 destructive -azure_rm_image_facts +azure_rm_image_info diff --git a/tests/integration/targets/azure_rm_image/tasks/main.yml b/tests/integration/targets/azure_rm_image/tasks/main.yml index 8b87adf..9b68a92 100644 --- a/tests/integration/targets/azure_rm_image/tasks/main.yml +++ b/tests/integration/targets/azure_rm_image/tasks/main.yml @@ -106,7 +106,7 @@ - output.id - name: Gather information about image created - azure_rm_image_facts: + azure_rm_image_info: resource_group: "{{ resource_group }}" name: testimage001 register: output diff --git a/tests/integration/targets/azure_rm_lock/aliases b/tests/integration/targets/azure_rm_lock/aliases index b13b9e8..68bf9dd 100644 --- a/tests/integration/targets/azure_rm_lock/aliases +++ b/tests/integration/targets/azure_rm_lock/aliases @@ -1,4 +1,4 @@ cloud/azure destructive unsupported -azure_rm_lock_facts +azure_rm_lock_info diff --git a/tests/integration/targets/azure_rm_lock/tasks/main.yml b/tests/integration/targets/azure_rm_lock/tasks/main.yml index 9deb7d2..371e24c 100644 --- a/tests/integration/targets/azure_rm_lock/tasks/main.yml +++ b/tests/integration/targets/azure_rm_lock/tasks/main.yml @@ -19,7 +19,7 @@ - lock.changed - name: Query lock - azure_rm_lock_facts: + azure_rm_lock_info: managed_resource_id: "{{ vn.state.id }}" register: locks @@ -40,7 +40,7 @@ - lock.id - name: Query lock - azure_rm_lock_facts: + azure_rm_lock_info: name: keep managed_resource_id: "{{ vn.state.id }}" register: locks @@ -84,7 +84,7 @@ - lock.changed - name: Query lock - azure_rm_lock_facts: + azure_rm_lock_info: managed_resource_id: "{{ vn.state.id }}" register: locks diff --git a/tests/integration/targets/azure_rm_manageddisk/aliases b/tests/integration/targets/azure_rm_manageddisk/aliases index 371e749..8052bd2 100644 --- a/tests/integration/targets/azure_rm_manageddisk/aliases +++ b/tests/integration/targets/azure_rm_manageddisk/aliases @@ -1,4 +1,4 @@ cloud/azure shippable/azure/group3 destructive -azure_rm_manageddisk_facts +azure_rm_manageddisk_info diff --git a/tests/integration/targets/azure_rm_manageddisk/tasks/main.yml b/tests/integration/targets/azure_rm_manageddisk/tasks/main.yml index 89d7ac9..3abaaef 100644 --- a/tests/integration/targets/azure_rm_manageddisk/tasks/main.yml +++ b/tests/integration/targets/azure_rm_manageddisk/tasks/main.yml @@ -132,21 +132,22 @@ - output.state.os_type == 'linux' - name: Gather facts to one specific disk - azure_rm_manageddisk_facts: + azure_rm_manageddisk_info: resource_group: "{{ resource_group }}" name: "md{{ rpfx }}1" + register: output - assert: that: - - "azure_managed_disk | length == 1" - - azure_managed_disk[0].storage_account_type == "StandardSSD_LRS" - - azure_managed_disk[0].disk_size_gb == 2 - - "azure_managed_disk[0].os_type == 'linux'" + - "output.ansible_info.azure_managed_disk | length == 1" + - output.ansible_info.azure_managed_disk[0].storage_account_type == "StandardSSD_LRS" + - output.ansible_info.azure_managed_disk[0].disk_size_gb == 2 + - "output.ansible_info.azure_managed_disk[0].os_type == 'linux'" - set_fact: parameter: "{{parameter |combine({item.key: item.value})}}" when: "{{item.key not in ['id', 'changed'] and item.value != None}}" - with_dict: "{{ azure_managed_disk[0] }}" + with_dict: "{{ output.ansible_info.azure_managed_disk[0] }}" - name: Create disk with facts return value azure_rm_manageddisk: diff --git a/tests/integration/targets/azure_rm_networkinterface/tasks/main.yml b/tests/integration/targets/azure_rm_networkinterface/tasks/main.yml index 2dbb338..bd7df0a 100644 --- a/tests/integration/targets/azure_rm_networkinterface/tasks/main.yml +++ b/tests/integration/targets/azure_rm_networkinterface/tasks/main.yml @@ -87,7 +87,7 @@ - output.state.id - name: Get fact of the new created NIC - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: "{{ resource_group }}" name: "tn{{ rpfx }}" register: facts @@ -277,7 +277,7 @@ - not output.changed - name: Get fact of the new created NIC - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: "{{ resource_group }}" name: "tn{{ rpfx }}" register: facts @@ -351,7 +351,7 @@ - output.id != '' - name: Get Application security group - azure_rm_applicationsecuritygroup_facts: + azure_rm_applicationsecuritygroup_info: resource_group: "{{ resource_group }}" name: "{{ applicationsecuritygroup_name1 }}" register: facts @@ -460,7 +460,7 @@ - output.changed - name: Get fact of the new created NIC - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: "{{ resource_group }}" name: "{{ nic_name1 }}" register: facts diff --git a/tests/integration/targets/azure_rm_securitygroup/tasks/main.yml b/tests/integration/targets/azure_rm_securitygroup/tasks/main.yml index cbe0740..658c1c9 100644 --- a/tests/integration/targets/azure_rm_securitygroup/tasks/main.yml +++ b/tests/integration/targets/azure_rm_securitygroup/tasks/main.yml @@ -35,7 +35,7 @@ - assert: { that: "{{ output.state.rules | length }} == 2" } - name: Gather facts by tags - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: "{{ resource_group }}" tags: - testing @@ -43,7 +43,7 @@ register: output - assert: - that: azure_securitygroups | length == 1 + that: output.securitygroups | length == 1 - name: Add/Update rules on existing security group azure_rm_securitygroup: @@ -121,23 +121,23 @@ - output.state.tags.delete == 'on-exit' - name: Gather facts for one accounts - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: "{{ resource_group }}" name: "{{ secgroupname }}" register: output - assert: that: - - azure_securitygroups | length == 1 + - output.securitygroups | length == 1 - name: Gather facts for all accounts - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: "{{ resource_group }}" - register: output + register: output_groups - assert: that: - - azure_securitygroups | length > 0 + - output_groups.securitygroups | length > 0 - name: Create security group with source_address_prefixes azure_rm_securitygroup: @@ -290,13 +290,13 @@ resource_group: "{{ resource_group }}" name: "{{ item.name }}" state: absent - with_items: "{{ azure_securitygroups }}" + with_items: "{{ output_groups.securitygroups }}" - name: Should have no security groups remaining - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: "{{ resource_group }}" register: output - assert: that: - - azure_securitygroups | length == 0 + - output.securitygroups | length == 0 diff --git a/tests/integration/targets/azure_rm_virtualmachine/tasks/azure_test_minimal.yml b/tests/integration/targets/azure_rm_virtualmachine/tasks/azure_test_minimal.yml index d2a7908..8f2767f 100644 --- a/tests/integration/targets/azure_rm_virtualmachine/tasks/azure_test_minimal.yml +++ b/tests/integration/targets/azure_rm_virtualmachine/tasks/azure_test_minimal.yml @@ -66,19 +66,19 @@ state: absent - name: Query auto created NIC - azure_rm_networkinterface_facts: + azure_rm_networkinterface_info: resource_group: "{{ resource_group }}" name: "{{ vm_name }}01" register: nic_result - name: Query auto created security group - azure_rm_securitygroup_facts: + azure_rm_securitygroup_info: resource_group: "{{ resource_group }}" name: "{{ vm_name }}01" register: nsg_result - name: Query auto created public IP - azure_rm_publicipaddress_facts: + azure_rm_publicipaddress_info: resource_group: "{{ resource_group }}" name: "{{ vm_name }}01" register: pip_result @@ -87,9 +87,9 @@ assert: that: # what about the default storage group? - - nic_result.ansible_facts.azure_networkinterfaces | length == 0 - - nsg_result.ansible_facts.azure_securitygroups | length == 0 - - pip_result.ansible_facts.azure_publicipaddresses | length == 0 + - nic_result.networkinterfaces | length == 0 + - nsg_result.securitygroups | length == 0 + - pip_result.publicipaddresses | length == 0 - name: Destroy subnet azure_rm_subnet: