azure_service_principal_attribute_1.py 1.7 KB

1234567891011121314151617181920212223242526272829303132
  1. def run(self, terms, variables, **kwargs):
  2. self.set_options(direct=kwargs)
  3. credentials = {}
  4. credentials['azure_client_id'] = self.get_option('azure_client_id', None)
  5. credentials['azure_secret'] = self.get_option('azure_secret', None)
  6. credentials['azure_tenant'] = self.get_option('azure_tenant', 'common')
  7. if credentials['azure_client_id'] is None or credentials['azure_secret'] is None:
  8. raise AnsibleError("Must specify azure_client_id and azure_secret")
  9. _cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD
  10. if self.get_option('azure_cloud_environment', None) is not None:
  11. cloud_environment = azure_cloud.get_cloud_from_metadata_endpoint(credentials['azure_cloud_environment'])
  12. try:
  13. azure_credentials = ServicePrincipalCredentials(client_id=credentials['azure_client_id'],
  14. secret=credentials['azure_secret'],
  15. tenant=credentials['azure_tenant'],
  16. resource=_cloud_environment.endpoints.active_directory_graph_resource_id)
  17. client = GraphRbacManagementClient(azure_credentials, credentials['azure_tenant'],
  18. base_url=_cloud_environment.endpoints.active_directory_graph_resource_id)
  19. response = list(client.service_principals.list(filter="appId eq '{0}'".format(credentials['azure_client_id'])))
  20. sp = response[0]
  21. return sp.object_id.split(',')
  22. except CloudError as ex:
  23. raise AnsibleError("Failed to get service principal object id: %s" % to_native(ex))
  24. return False