def get_at_management_group( self, policy_definition_name, credentials=None, management_group_id=None, subscription_id=None, raw=False, ): if credentials is None: credentials = AzureIdentityCredentialAdapter() if subscription_id is None: subscription_id = self.subscription_id # Defaults to the root management group unless specified in the parameter list if management_group_id is None: management_group_id = self.tenant_id policy_client = PolicyClient( credentials=credentials, subscription_id=subscription_id ) policy_definition = policy_client.policy_definitions.get_at_management_group( policy_definition_name=policy_definition_name, management_group_id=management_group_id, raw=raw, ) return policy_definition
def test_list_at_subscription_level(self): credentials = AzureIdentityCredentialAdapter() policy_client = PolicyClient(credentials=credentials, subscription_id=self.subscription_id) policy_definitions = list(policy_client.policy_definitions.list()) self.assertGreater(len(policy_definitions), 0) logging.debug("Subscription policy definition list count {}".format( len(policy_definitions)))
def test_get_subscription_level_raw(self): credentials = AzureIdentityCredentialAdapter() policy_client = PolicyClient(credentials=credentials, subscription_id=self.subscription_id) policy_definition_name = self.test_data_config['AZURE_POLICY'][ "policy_name_04"] policy_definition = policy_client.policy_definitions.get( policy_definition_name=policy_definition_name, raw=True) self.assertIsNotNone(policy_definition)
def test_get_subscription_level(self): credentials = AzureIdentityCredentialAdapter() policy_client = PolicyClient(credentials=credentials, subscription_id=self.subscription_id) policy_definition = policy_client.policy_definitions.get( policy_definition_name=self.test_data_config['AZURE_POLICY'] ["policy_name_03"]) self.assertIsNotNone(policy_definition) self.assertTrue("PolicyDefinition" in str(type(policy_definition)))
def create_manage_group_assignment( self, policy_defintion_name, policy_assignment_name, credentials=None, management_group_id=None, subscription_id=None, ): """ Create a policy assignment at the specified management group level :param policy_assignment_name: :param credentials: :param management_group_id: :param subscription_id: :return: """ if credentials is None: credentials = AzureIdentityCredentialAdapter() if subscription_id is None: subscription_id = self.subscription_id # Defaults to the root management group unless specified in the parameter list if management_group_id is None: management_group_id = self.management_group_id policy_defintion_client = MopPolicyDefinition( operations_path=self.operations_path, config_variables=self.config_variables) policy_definition = policy_defintion_client.get_at_management_group( policy_definition_name=policy_defintion_name, raw=True) # Cannot assignment a policy for a policy that doesn't exist yet if not policy_definition: raise KeyError assignment_scope = self.config["AZURESDK"][ "management_group_scope_policy_assignment"] assignment_scope = assignment_scope.format( managementGroup=management_group_id) parameters = self.create_assignment_body(policy_definition) policy_client = PolicyClient(credentials=credentials, subscription_id=subscription_id) mgmnt_group_policy_assingment = policy_client.policy_assignments.create( scope=assignment_scope, policy_assignment_name=policy_assignment_name, parameters=parameters, ) print(mgmnt_group_policy_assingment)
def get_policies_for_subscription(subscription_id): """ Gets all the policy details associated with the subscription. Returns a dictionary of policies with the id of the policy as the key """ policy_client = PolicyClient(credentials, subscription_id) policies = policy_client.policy_definitions.list() policies_by_id = {} for policy in policies: policy_dict = policy.as_dict() policies_by_id[policy_dict['name']] = policy_dict return policies_by_id
def create_at_management_group_scope(self, policy_definition_name, policy_definition_body, credentials=None, management_group_id=None, subscription_id=None, ): """ This method has the benefit of specifying the the internal name of the policy. The policy_definition_name given in this method will set the unique name for the Azure Tenant. Creating a policy this way offers more control, but can also yield name collisions. If a policy with the same internal name is found, this method WILL OVERWRITE that policy. :param policy_definition_name: :param policy_definition_body: :param credentials: :param management_group_id: :param subscription_id: :return: """ if credentials is None: credentials = AzureIdentityCredentialAdapter() if subscription_id is None: subscription_id = self.subscription_id # Defaults to the root management group unless specified in the parameter list if management_group_id is None: management_group_id = self.tenant_id policy_client = PolicyClient( credentials=credentials, subscription_id=subscription_id ) policy_definition = policy_client.policy_definitions.create_or_update_at_management_group( policy_definition_name=policy_definition_name, parameters=policy_definition_body, management_group_id=management_group_id) return policy_definition
def list_for_management_group( self, management_group_id, credentials=None, subscription_id=None ): if credentials is None: credentials = AzureIdentityCredentialAdapter() if subscription_id is None: subscription_id = self.subscription_id # Defaults to the root management group unless specified in the parameter list if management_group_id is None: management_group_id = self.tenant_id policy_client = PolicyClient( credentials=credentials, subscription_id=subscription_id ) policy_definition_list = policy_client.policy_definitions.list_by_management_group( management_group_id=management_group_id ) return policy_definition_list
def list_for_management_group( self, credentials=None, management_group_id=None, subscription_id=None, filter="atScope()", ): if credentials is None: credentials = AzureIdentityCredentialAdapter() if subscription_id is None: subscription_id = self.subscription_id # Defaults to the root management group unless specified in the parameter list if management_group_id is None: management_group_id = self.management_group_id policy_client = PolicyClient(credentials=credentials, subscription_id=subscription_id) policy_assignments = list( policy_client.policy_assignments.list_for_management_group( management_group_id=management_group_id, filter=filter)) return policy_assignments
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" REMEDIATION = "remediationxxyyzz" POLICY_NAME = "policyxyz" POLICY_ASSIGNMENT_NAME = "assignmentx" # Create client # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID) policyinsights_client = PolicyInsightsClient( credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID) # - init depended client - policy_client = PolicyClient(credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID) # - end - # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # - init depended resources - # Create policy definition definition = policy_client.policy_definitions.create_or_update( POLICY_NAME, { 'policy_type': 'Custom', 'description': 'Don\'t create a VM anywhere', 'policy_rule': { 'if': { 'allOf': [{ 'source': 'action', 'equals': 'Microsoft.Compute/virtualMachines/read' }, { 'field': 'location', 'in': ['eastus', 'eastus2', 'centralus'] }] }, 'then': { 'effect': 'deny' } } }) print("Create policy definition: {}".format(definition)) # Policy Assignment - By Name scope = '/subscriptions/{}/resourceGroups/{}'.format( SUBSCRIPTION_ID, GROUP_NAME) # Create policy assignment assignment = policy_client.policy_assignments.create( scope, POLICY_ASSIGNMENT_NAME, { 'policy_definition_id': definition.id, }) print("Create policy assignment: {}".format(assignment)) # - end - # Create remediation remediation = policyinsights_client.remediations.create_or_update_at_resource_group( GROUP_NAME, REMEDIATION, {"policy_assignment_id": assignment.id}) print("Create remediation:\n{}".format(remediation)) # Get remediation remediation = policyinsights_client.remediations.get_at_resource_group( GROUP_NAME, REMEDIATION) print("Get remediation:\n{}".format(remediation)) # Delete remediation remediation = policyinsights_client.remediations.delete_at_resource_group( GROUP_NAME, REMEDIATION) print("Delete remediation.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" POLICY_NAME = "policyxyz" POLICY_ASSIGNMENT_NAME = "assignmentx" POLICY_SET_NAME = "policysetdefinition" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ policy_client = PolicyClient( credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID ) resource_client = ResourceManagementClient( credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create policy definition definition = policy_client.policy_definitions.create_or_update( POLICY_NAME, { 'policy_type': 'Custom', 'description': 'Don\'t create a VM anywhere', 'policy_rule': { 'if': { 'allOf': [ { 'source': 'action', 'equals': 'Microsoft.Compute/virtualMachines/read' }, { 'field': 'location', 'in': [ 'eastus', 'eastus2', 'centralus' ] } ] }, 'then': { 'effect': 'deny' } } } ) print("Create policy definition: {}".format(definition)) # Get policy definition definition = policy_client.policy_definitions.get( POLICY_NAME ) print("Get policy definition: {}".format(definition)) # Policy Assignment - By Name scope = '/subscriptions/{}/resourceGroups/{}'.format( SUBSCRIPTION_ID, GROUP_NAME ) # Create policy assignment assignment = policy_client.policy_assignments.create( scope, POLICY_ASSIGNMENT_NAME, { 'policy_definition_id': definition.id, } ) print("Create policy assignment: {}".format(assignment)) # Get policy assignment assignment = policy_client.policy_assignments.get( assignment.scope, assignment.name ) print("Get policy assignment: {}".format(assignment)) # Create policy set definition policy_set = policy_client.policy_set_definitions.create_or_update( POLICY_SET_NAME, { "properties": { "displayName": "Cost Management", "description": "Policies to enforce low cost storage SKUs", "metadata": { "category": "Cost Management" }, "policyDefinitions": [ { "policyDefinitionId": definition.id, "parameters": { } } ] } } ) print("Create policy set definition: {}".format(policy_set)) # Get policy set definition policy_set = policy_client.policy_set_definitions.get( POLICY_SET_NAME ) print("Get policy set definition: {}".format(policy_set)) # Delete policy set definition policy_client.policy_set_definitions.delete( POLICY_SET_NAME ) print("Delete policy set definition.") # Delete policy assignment policy_client.policy_assignments.delete( assignment.scope, assignment.name ) print("Delete policy assignment.") # Delete policy definition policy_client.policy_definitions.delete( POLICY_NAME ) print("Delete policy definition.") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
'/home/yahav/Downloads/rgs-click.csv', mode='r', ) as file: csv_reader = csv.DictReader(file) all_rows = [row for row in csv_reader] for sub in subscription_ids: # policy = PolicyInsightsClient(credential=credential, subscription_id=sub.subscription_id) with open( '/home/yahav/Downloads/deny_policy_data_30-09-2021_09 57 23.csv', mode='r', ) as file_click: policy_reader = csv.DictReader(file_click) row_data = [id for id in policy_reader] print(row_data) policy_client = PolicyClient(credential=credential, subscription_id=sub.subscription_id) # Validate sub names within the CSV. sub_exist = [] for row in all_rows: if sub.display_name == row['SUBSCRIPTION']: sub_exist.append(row) #Initiate rg client resource_group_client = ResourceManagementClient( credential, subscription_id=sub.subscription_id) rg_list = resource_group_client.resource_groups.list() rg_names = [rg.name for rg in rg_list] # Validate rg names within the CSV.