### Configuration Setup for Acronis Cyber Platform API Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Initialize API configuration with base URL, tenant information, and application settings. This configuration is loaded from cyber.platform.cfg.json file and used for all subsequent API requests to the Acronis Cyber Platform. ```json { "base_url": "https://dev-cloud.acronis.com/", "partner_tenant": "partner", "customer_tenant": "customer", "edition": "pck_per_gigabyte", "switch_edition": "pck_per_workload", "cyber_protection_application_id": "6e6d758d-8e74-3ae3-ac84-50eb0dff12eb" } ``` -------------------------------- ### Start Plan Execution - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Initiate execution of the first available protection plan for the first resource in the Acronis Cyber Platform. Triggers immediate backup or protection job execution. ```python # start_plan_execution.py # Start the first plan for the first resource execution ``` -------------------------------- ### Get All Protection Plans Information - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve detailed information about all protection plans available within the authorization scope. Lists all backup and protection plans with their configurations. ```python # get_all_plans_info.py # Get the list of all protection plans available in authorization scope ``` -------------------------------- ### Create Partner Tenant with Offering Items using Python Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Creates a new partner tenant and enables all available offering items for a specified edition. This script depends on a configuration object and requires the Acronis client to be initialized. ```python import json import random import string from common.base_operations import Acronis, Config, Tenant def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) cfg = Config(full=True) acronis = Acronis(cfg) partner = { "name": f"Python Partner {id_generator()} v3.0", "parent_id": f"{cfg.tenant_id}", "kind": "partner" } response = acronis.post('api/2/tenants', data=json.dumps(partner)) if response.ok: with open('partner.json', 'w') as outfile: json.dump(response.json(), outfile) new_partner = Tenant('partner.json') # Get available offering items response = acronis.get( f'api/2/tenants/{cfg.tenant_id}/offering_items/available_for_child' f'?kind=partner&edition=pck_per_gigabyte' ) if response.ok: offering_items = {"offering_items": response.json()["items"]} # Enable offering items for partner response = acronis.put( f'api/2/tenants/{new_partner.tenant_id}/offering_items', data=json.dumps(offering_items) ) if response.ok: print(f"Partner {new_partner.tenant_id} created with offerings enabled") else: print(f"Error enabling offerings: {response.json()}") else: print(f"Error creating partner: {response.json()}") ``` -------------------------------- ### GET /tenants/{customerTenantId}/pricing Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieves the current pricing configuration for a given customer tenant. This is the first step in switching a customer's account from trial to production mode. ```APIDOC ## GET /tenants/{customerTenantId}/pricing ### Description Retrieves the current pricing for a customer tenant. ### Method GET ### Endpoint /tenants/{customerTenantId}/pricing #### Parameters ##### Path Parameters - **customerTenantId** (string) - Required - The ID of the customer tenant. ### Response #### Success Response (200) - **mode** (string) - The current pricing mode (e.g., 'trial', 'production'). - Other pricing related fields. #### Response Example ```json { "mode": "trial", "currency": "USD", "items": [] } ``` ``` -------------------------------- ### Get All Resources Information - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve comprehensive information about all resources available within the authorization scope of the Acronis Cyber Platform. Returns detailed metadata for each resource. ```python # get_all_resources_info.py # Get the list of all resources available in authorization scope ``` -------------------------------- ### Get All Resources with Attributes Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Retrieves all resources within the authorization scope, including their attributes, using the Acronis Cyber Platform API. The results are saved to a JSON file, and the total count and types of the first few resources are printed. ```python import json from common.base_operations import Acronis, Config cfg = Config(full=True) acronis = Acronis(cfg) response = acronis.get('api/resource_management/v4/resources?include_attributes=true') if response.ok: resources = response.json() with open('all_resources_with_attributes.json', 'w') as outfile: json.dump(resources, outfile) print(f"Total resources: {len(resources.get('items', []))}") # Display resource types for resource in resources.get('items', [])[:5]: print(f"Resource: {resource.get('name')} - Type: {resource.get('type')}") else: print(f"Error: {response.json()}") ``` -------------------------------- ### Create Customer Tenant with Offering Items Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Creates a new customer tenant under a specified partner and enables specific offering items for it. It requires a configuration object, Acronis API client, and partner tenant information. The output is the creation of a customer tenant JSON file and enabling of offering items. ```python import json from common.base_operations import Acronis, Config, Tenant cfg = Config(full=True) acronis = Acronis(cfg) partner = Tenant('partner.json') customer = { "name": f"Python Customer {id_generator()} v3.0", "parent_id": f"{partner.tenant_id}", "kind": "customer" } response = acronis.post('api/2/tenants', data=json.dumps(customer)) if response.ok: with open('customer.json', 'w') as outfile: json.dump(response.json(), outfile) new_customer = Tenant('customer.json') # Get and enable offering items for customer response = acronis.get( f'api/2/tenants/{partner.tenant_id}/offering_items/available_for_child' f'?kind=customer&edition=pck_per_gigabyte' ) if response.ok: offering_items = {"offering_items": response.json()["items"]} response = acronis.put( f'api/2/tenants/{new_customer.tenant_id}/offering_items', data=json.dumps(offering_items) ) if response.ok: print(f"Customer {new_customer.tenant_id} created successfully") ``` -------------------------------- ### Get Tenant Usage Statistics Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Retrieves current usage statistics for a specific tenant from the Acronis Cyber Platform API. The usage data is saved to a JSON file, and the first few usage items (name, value, unit) are printed. ```python import json from common.base_operations import Acronis, Config cfg = Config(full=True) acronis = Acronis(cfg) response = acronis.get(f'api/2/tenants/{cfg.tenant_id}/usages') if response.ok: usage = response.json() with open(f'tenant_usage_{cfg.tenant_id}.json', 'w') as outfile: json.dump(usage, outfile) print(f"Usage data for tenant {cfg.tenant_id}:") for item in usage.get('items', [])[:5]: print(f" {item.get('name')}: {item.get('value')} {item.get('measurement_unit')}") else: print(f"Error: {response.json()}") ``` -------------------------------- ### Create API Client using Python Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Generates OAuth2 API client credentials for secure platform access using basic authentication. It requires username and password inputs and saves the client details to 'api_client.json'. ```python import requests import json import getpass base_url = "https://dev-cloud.acronis.com/" username = input("Username: ") password = getpass.getpass(prompt="Password: ") # Get user tenant ID response = requests.get( f'{base_url}api/2/users/me', auth=(username, password) ) if response.ok: my_tenant_id = response.json()["tenant_id"] client = { "type": "api_client", "tenant_id": f"{my_tenant_id}", "token_endpoint_auth_method": "client_secret_basic", "data": { "client_name": "Python.Client" } } response = requests.post( f'{base_url}api/2/clients', headers={'Content-Type': 'application/json'}, auth=(username, password), data=json.dumps(client) ) if response.ok: with open('api_client.json', 'w') as outfile: json.dump(response.json(), outfile) print(f"Client ID: {response.json()['client_id']}") else: print(f"Error: {response.json()}") ``` -------------------------------- ### Create User with Role Assignment Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Creates a new user within a customer tenant, sends an activation email, and assigns the 'backup_user' role. It first checks if the login is available, then creates the user, sends the activation email, and finally updates access policies to assign the role. Requires user login, email, and customer tenant information. ```python import json from common.base_operations import Acronis, Config, Tenant, User cfg = Config(full=True) acronis = Acronis(cfg) login = "john.doe@example.com" email = "john.doe@example.com" # Check if login is available response = acronis.get(f"api/2/users/check_login?username={login}") if response.ok and response.status_code == 204: customer = Tenant("customer.json") user = { "tenant_id": f"{customer.tenant_id}", "login": f"{login}", "contact": { "email": f"{email}", "firstname": "John", "lastname": "Doe" } } response = acronis.post('api/2/users', data=json.dumps(user)) if response.ok: with open('user.json', 'w') as outfile: json.dump(response.json(), outfile) new_user = User('user.json') # Send activation email response = acronis.post(f'api/2/users/{new_user.id}/send-activation-email') if response.ok: print(f"User {login} activated via email") # Assign backup user role user_role = { "items": [{ "id": "00000000-0000-0000-0000-000000000000", "issuer_id": "00000000-0000-0000-0000-000000000000", "role_id": "backup_user", "tenant_id": f"{customer.tenant_id}", "trustee_id": f"{new_user.id}", "trustee_type": "user", "version": 0 }] } response = acronis.put( f'api/2/users/{new_user.id}/access_policies', data=json.dumps(user_role) ) if response.ok: print(f"Backup user role assigned to {login}") ``` -------------------------------- ### HTTP Operations Wrapper with Bearer Token Authentication - Python Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Provides a reusable Acronis class that wraps HTTP requests with OAuth2 bearer token authentication and a BearerAuth custom authentication handler. Supports GET, POST, PUT, and DELETE methods with automatic header and authentication injection. Requires requests library and Config object with base_url and access_token. ```python import requests import json import os from time import time class BearerAuth(requests.auth.AuthBase): def __init__(self, token): self.token = token def __call__(self, r): r.headers["Authorization"] = "Bearer " + self.token return r class Acronis: def __init__(self, cfg): self.__cfg = cfg self.__auth = BearerAuth(cfg.access_token) def get(self, uri, data=None): return requests.get( f'{self.__cfg.base_url}{uri}', params=data, headers=self.__cfg.header, auth=self.__auth ) def post(self, uri, data=None): return requests.post( f'{self.__cfg.base_url}{uri}', headers={**self.__cfg.header, **{'Content-Type': 'application/json'}}, auth=self.__auth, data=data ) def put(self, uri, data=None): return requests.put( f'{self.__cfg.base_url}{uri}', headers={**self.__cfg.header, **{'Content-Type': 'application/json'}}, auth=self.__auth, data=data ) def delete(self, uri, data=None): return requests.delete( f'{self.__cfg.base_url}{uri}', params=data, headers=self.__cfg.header, auth=self.__auth ) # Usage example cfg = Config(full=True) acronis = Acronis(cfg) response = acronis.get('api/2/users/me') print(response.json()) ``` -------------------------------- ### Get Alerts with Filtering by Date Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Fetches alerts from the Acronis Cyber Platform API that were updated within the last 7 days and orders them by creation date. It categorizes alerts by severity (critical, error, warning) and saves the raw alert data to a JSON file. ```python import json from datetime import datetime, timedelta, timezone from common.base_operations import Config, Acronis cfg = Config(full=True) acronis = Acronis(cfg) # Calculate timestamp for 7 days ago in nanoseconds last_week = (datetime.today() - timedelta(days=7)).replace( hour=0, minute=0, second=0, microsecond=0 ) last_week_ns = int(last_week.replace(tzinfo=timezone.utc).timestamp() * 1000000000) filters = { 'updated_at': f'gt({last_week_ns})', 'order': 'desc(created_at)' } response = acronis.get('api/alert_manager/v1/alerts', data=filters) if response.ok: alerts = response.json() # Categorize by severity warning_alerts = [a for a in alerts["items"] if a["severity"] == "warning"] error_alerts = [a for a in alerts["items"] if a["severity"] == "error"] critical_alerts = [a for a in alerts["items"] if a["severity"] == "critical"] with open(f'alerts_{last_week_ns}.json', 'w') as outfile: json.dump(alerts, outfile) print(f'Critical: {len(critical_alerts)}') print(f'Errors: {len(error_alerts)}') print(f'Warnings: {len(warning_alerts)}') else: print(f"Error: {response.json()}") ``` -------------------------------- ### GET /api/2/tenants/{tenant_id}/offering_items/available_for_child Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieves a list of available offering items for a child tenant, filtered by kind and edition. This is used to determine which services can be provisioned for a customer. ```APIDOC ## GET /api/2/tenants/{tenant_id}/offering_items/available_for_child ### Description Retrieves available offering items for a child tenant. ### Method GET ### Endpoint /api/2/tenants/{tenant_id}/offering_items/available_for_child #### Query Parameters - **kind** (string) - Required - The kind of tenant. - **edition** (string) - Required - The edition of the offering items. ### Response #### Success Response (200) - **items** (array) - A list of available offering items. - **type** (string) - The type of the offering item. - **infra_id** (string) - The infrastructure ID. - **usage_name** (string) - The usage name of the offering item. #### Response Example ```json { "items": [ { "type": "infra", "infra_id": "some_infra_id", "usage_name": "some_usage_name" } ] } ``` ``` -------------------------------- ### Customize Retention Settings and Create Backup Plan Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Configures retention rules for backup plans (daily, weekly, monthly) and creates a new backup plan using the Acronis Cyber Platform API. It saves the response to a JSON file and prints the status. ```python import json # Assume base_plan is a pre-defined dictionary with policy structure base_plan["subject"]["policy"][1]["settings"]["retention"]["rules"] = [ { "backup_set": ["daily"], "max_age": {"type": "days", "count": 7} }, { "backup_set": ["weekly"], "max_age": {"type": "weeks", "count": 4} }, { "backup_set": ["monthly"], "max_age": {"type": "months", "count": 6} } ] response = acronis.post( 'api/policy_management/v4/policies', data=json.dumps(base_plan) ) if response.ok: with open('plan_creation_response.json', 'w') as outfile: json.dump(response.json(), outfile) print(f"Backup plan created: {backup_plan_uuid}") else: print(f"Error: {response.json()}") ``` -------------------------------- ### Initialize Acronis API Configuration Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Initializes the Acronis Cyber Platform API client configuration and reads required values from a JSON configuration file. This setup is a prerequisite for making API requests to create and manage tenants and users. ```Python # Initialize config and read all required values form JSON config ``` -------------------------------- ### Switch Customer Tenant to Production Mode Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Converts an existing customer tenant from trial mode to production mode. This operation requires the customer tenant's details. It retrieves the current pricing configuration, updates the mode to 'production', and then applies the changes via a PUT request. ```python import json from common.base_operations import Acronis, Config, Tenant cfg = Config(full=True) acronis = Acronis(cfg) customer = Tenant('customer.json') response = acronis.get(f'api/2/tenants/{customer.tenant_id}/pricing') if response.ok: pricing = response.json() pricing["mode"] = "production" response = acronis.put( f'api/2/tenants/{customer.tenant_id}/pricing', data=json.dumps(pricing) ) if response.ok: print(f"Customer {customer.tenant_id} switched to production mode") else: print(f"Error: {response.json()}") else: print(f"Error getting pricing: {response.json()}") ``` -------------------------------- ### Get All Resources Protection Statuses - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Fetch the protection status for all resources available in the authorization scope. Provides visibility into which resources are protected and their current protection state. ```python # get_all_resources_protection_statuses.py # Get the list of all resources available in authorization scope with their protection statuses ``` -------------------------------- ### Create Machine Backup Plan Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Defines a machine backup plan, including retention policies and scheduling, based on a provided JSON template. This script loads a base plan, generates unique UUIDs for plan components, and sets these IDs within the plan structure. It requires a base plan JSON file. ```python import json import uuid from common.base_operations import Acronis, Config cfg = Config(full=True) acronis = Acronis(cfg) # Load base plan template with open('plans/base_plan.json') as base_plan_file: base_plan = json.load(base_plan_file) backup_plan_uuid = str(uuid.uuid4()) total_protection_plan_uuid = str(uuid.uuid4()) # Set plan UUIDs base_plan["subject"]["policy"][0]["id"] = total_protection_plan_uuid base_plan["subject"]["policy"][1]["parent_ids"][0] = total_protection_plan_uuid base_plan["subject"]["policy"][1]["id"] = backup_plan_uuid ``` -------------------------------- ### Get Tenant Usage Information - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve usage statistics and metrics for the root tenant in the Acronis Cyber Platform. Provides data on resource consumption, protected items, and storage utilization. ```python # get_tenant_usage.py # Gets usage for the root tenant ``` -------------------------------- ### Get Tasks with Pagination - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve the complete list of all tasks from the Acronis Cyber Platform using pagination. This script handles paginated task results for monitoring background operations. ```python # tasks_pagination.py # Get the list of all tasks with pagination ``` -------------------------------- ### Retrieve User Information with Basic Authentication - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Makes an HTTP GET request to the /api/2/users/me endpoint using Basic Authentication with the provided username and password. Extracts the tenant_id from the JSON response for subsequent API client creation. Returns error details if the request fails. ```Python # Request information about a user which is authenticated by # username and password - Basic Authentication response = requests.get( f'{cfg.base_url}api/2/users/me', auth=(username, password) ) if response.ok: # Read tenant_id from received JSON my_tenant_id = response.json()["tenant_id"] # Build an object represents an API Client creation request JSON body client = { "type": "api_client", "tenant_id": f"{my_tenant_id}", "token_endpoint_auth_method": "client_secret_basic", "data": { "client_name": "Python.Client" } } ... else: pprint.pprint(response.json()) ``` -------------------------------- ### Get Activities Completed Last Week - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve all activities that were completed during the previous week from the Acronis Cyber Platform. Provides audit trail and activity monitoring capabilities. ```python # get_activities.py # Get the list of all activities competed during the last week ``` -------------------------------- ### Issue Access Token using Python Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Obtains a JWT bearer token using API client credentials. The token has a 2-hour expiration and is saved to 'api_token.json'. This requires the 'api_client.json' file to exist. ```python import requests import json base_url = "https://dev-cloud.acronis.com/" with open('api_client.json') as api_client_file: api_client_json = json.load(api_client_file) client_id = api_client_json["client_id"] client_secret = api_client_json["client_secret"] response = requests.post( f'{base_url}api/2/idp/token', headers={'Content-Type': 'application/x-www-form-urlencoded'}, auth=(client_id, client_secret), data={'grant_type': 'client_credentials'} ) if response.ok: token_data = response.json() with open('api_token.json', 'w') as outfile: json.dump(token_data, outfile) print(f"Access Token: {token_data['access_token']}") print(f"Expires in: {token_data['expires_in']} seconds") else: print(f"Error: {response.json()}") ``` -------------------------------- ### Get Alerts with Pagination - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieve the complete list of all alerts from the Acronis Cyber Platform using pagination to handle large result sets efficiently. This script iterates through paginated alert results. ```python # alerts_pagination.py # Get the list of all alerts with pagination ``` -------------------------------- ### Create and Download CSV Report with Polling - Python Source: https://context7.com/acronis/acronis-cyber-platform-python-examples/llms.txt Generates a one-time usage report for a tenant and downloads it as a CSV file. The code creates a report request, polls the API until the report is ready (status = 'saved'), and downloads the generated file. Requires Acronis API credentials and base_operations module for authentication. ```python import json import time from common.base_operations import Acronis, Config cfg = Config(full=True) acronis = Acronis(cfg) report = { "parameters": { "kind": "usage_current", "tenant_id": f"{cfg.tenant_id}", "level": "accounts", "formats": ["csv_v2_0"] }, "schedule": { "type": "once" }, "result_action": "save" } response = acronis.post('api/2/reports', data=json.dumps(report)) if response.ok: report_id = response.json()["id"] report_status = "non saved" stored_report_id = None # Poll until report is ready while report_status != "saved": response = acronis.get(f'api/2/reports/{report_id}/stored') if response.ok: items = response.json().get("items", []) if items: report_status = items[0]["status"] if report_status == "saved": stored_report_id = items[0]["id"] time.sleep(2) # Download report response = acronis.get(f'api/2/reports/{report_id}/stored/{stored_report_id}') if response.ok: with open(f'report_for_tenant_{cfg.tenant_id}.csv', 'w') as outfile: outfile.write(response.text) print(f"Report downloaded: report_for_tenant_{cfg.tenant_id}.csv") else: print(f"Error downloading report: {response.json()}") else: print(f"Error creating report: {response.json()}") ``` -------------------------------- ### Create Partner Tenant and Set Offering Items (Python) Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md This script initializes configuration, creates a new partner tenant, and then sets the available offering items for that tenant. It reads configuration from a JSON file and uses the Acronis client to interact with the API. Dependencies include the 'acronis' library, 'json', 'os', and 'pprint'. It takes configuration values as input and outputs tenant information and API responses. ```python import json import os import pprint from acronis.api.client import Acronis from acronis.api.config import Config from acronis.api.models.tenant import Tenant # Helper function to generate unique IDs def id_generator(): import random return random.randint(1000, 9999) base_path = os.path.dirname(os.path.abspath(__file__)) # Initialize config and read all required values form JSON config # an API client and a token files cfg = Config(full=True) acronis = Acronis(cfg) partner = { "name": f"Python Partner {id_generator()} v3.0", "parent_id": f"{cfg.tenant_id}", "kind": f"{cfg.partner_tenant}" } response = acronis.post( 'api/2/tenants', data=json.dumps(partner) ) if response.ok: with open(os.path.join(base_path, 'partner.json'), 'w') as outfile: json.dump(response.json(), outfile) new_partner = Tenant(os.path.join(base_path, 'partner.json')) response = acronis.get( f'api/2/tenants/{cfg.tenant_id}/offering_items/available_for_child?kind={cfg.partner_tenant}&edition={cfg.edition}' ) if response.ok: offering_items = json.loads('{"offering_items":[]}') offering_items["offering_items"] = response.json()["items"] response = acronis.put( f'api/2/tenants/{new_partner.tenant_id}/offering_items', data=json.dumps(offering_items) ) if response.ok: print(f"Offering items were set for tenant {new_partner.tenant_id}") else: pprint.pprint(response.json()) else: pprint.pprint(response.json()) else: pprint.pprint(response.json()) ``` -------------------------------- ### GET /users/check_login Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Checks if a desired username (login) is available for a new user. This endpoint is used before creating a user to ensure the chosen login is unique. ```APIDOC ## GET /users/check_login ### Description Checks the availability of a username for a new user. ### Method GET ### Endpoint /users/check_login #### Query Parameters - **username** (string) - Required - The username to check for availability. ### Response #### Success Response (200) - **available** (boolean) - True if the username is available, false otherwise. #### Response Example ```json { "available": true } ``` ``` -------------------------------- ### Create Customer User with Backup Role - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Create a new user account for a customer tenant, activate it via email notification, and assign the backup_user role. Script prompts for username and email address. ```python # create_user_for_customer_activate_assign_backup_user_role.py # Creates a user for Customer.Bash.Examples.v3 and activate them by sending an e-mail # and assign the backup_user role. The script asks for a username and an e-mail to create ``` -------------------------------- ### Create Partner User with Admin Role - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Create a new user account for a partner tenant, activate it via email notification, and assign the partner_admin role. Script prompts for username and email address. ```python # create_user_for_partner_activate_assign_admin_role.py # Creates a user for Partner.Bash.Examples.v3 and activate them by sending an e-mail # and assign the partner_admin role. The script asks for a username and an e-mail to create ``` -------------------------------- ### Create SKU Report with Partner Information - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Generate a one-time SKU and partner usage report for the root tenant in the Acronis Cyber Platform, including direct partner and SKU information, then download it. ```python # create_sku_report_retrieve.py # Create an one time report for direct partners and SKU information included to save for the root tenant, wait till its creation and download ``` -------------------------------- ### Create Backup Plan from Template - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Create a new backup protection plan in the Acronis Cyber Platform based on the base_plan.json template. Configures backup schedules, retention policies, and other protection parameters. ```python # create_a_backup_plan.py # Create a backup plan based on base_plan.json template ``` -------------------------------- ### Create Customer Tenant in Acronis Cyber Platform Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Creates a new customer tenant using the Acronis API client with configuration from a partner tenant JSON file. The code initializes the API client, defines customer details with a unique name, posts the tenant creation request, and saves the response to a JSON file for future reference. ```Python cfg = Config(full=True) acronis = Acronis(cfg) partner = Tenant(os.path.join(base_path, 'partner.json')) customer = { "name": f"Python Customer {id_generator()} v3.0", "parent_id": f"{partner.tenant_id}", "kind": f"{cfg.customer_tenant}" } response = acronis.post( 'api/2/tenants', data=json.dumps(customer) ) if response.ok: with open(os.path.join(base_path, 'customer.json'), 'w') as outfile: json.dump(response.json(), outfile) new_customer = Tenant(os.path.join(base_path, 'customer.json')) ``` -------------------------------- ### Get Tasks Completed Last Week - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Fetch and display all tasks that were completed during the previous week from the Acronis Cyber Platform. Useful for tracking recent backup and protection operations. ```python # get_tasks.py # Get the list of all tasks competed during the last week ``` -------------------------------- ### Tenant Management API Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md APIs for creating and managing tenants, including partners, customers, and users, and configuring their offering items. ```APIDOC ## Tenant Management API ### Description This section covers the creation of partner and customer tenants, enabling offering items, and creating/activating users within those tenants. ### Prerequisites Ensure a valid authorization token is obtained using the `/idp/token` endpoint. ### 1. Retrieve API Client Tenant Information #### Method GET #### Endpoint `/clients/{clientId}` #### Parameters ##### Path Parameters - **clientId** (string) - Required - The ID of the API client. ### 2. Create Tenant (Partner/Customer) #### Method POST #### Endpoint `/tenants` #### Parameters ##### Request Body - **tenant_id** (string) - Required - The `tenant_id` obtained from retrieving client information. - **kind** (string) - Required - The type of tenant to create (`partner`, `folder`, `customer`, `unit`). - **name** (string) - Required - The name of the tenant. ### 3. Get Available Offering Items #### Method GET #### Endpoint `/tenants/{tenantId}/offering_items/available_for_child` #### Parameters ##### Path Parameters - **tenantId** (string) - Required - The ID of the parent tenant. ##### Query Parameters - **edition** (string) - Required - The edition of the tenant. - **kind** (string) - Required - The kind of the tenant (`partner`, `customer`, etc.). ### 4. Enable Offering Items for Tenant #### Method PUT #### Endpoint `/tenants/{tenantId}/offering_items` #### Parameters ##### Path Parameters - **tenantId** (string) - Required - The ID of the tenant for which to enable offering items. ##### Request Body - **offering_items** (array) - Required - A list of offering item configurations. - **id** (string) - Required - The ID of the offering item. - **enabled** (boolean) - Required - Whether the offering item is enabled. - **quantity** (integer) - Optional - The quantity for the offering item. ### 5. Create User *(Specific endpoint and details for user creation are not detailed in the provided text, but would typically follow tenant creation.)* ### Error Handling - **400 Bad Request**: Invalid input data or parameters. - **401 Unauthorized**: Authentication token is missing or invalid. - **403 Forbidden**: Insufficient permissions to perform the action. - **404 Not Found**: Tenant or related resource not found. ``` -------------------------------- ### Get Alerts Completed Last Week - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Fetch all alerts that were completed or resolved during the previous week from the Acronis Cyber Platform. Helps track alert resolution and system health history. ```python # get_alerts.py # Get the list of all alerts competed during the last week ``` -------------------------------- ### Apply Protection Plan to Resource - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Apply the first applicable protection plan to the first available resource in the Acronis Cyber Platform. Demonstrates plan assignment workflow for resource protection. ```python # apply_plan.py # Apply the first applicable plan for the first resource ``` -------------------------------- ### Impersonate User and Verify Identity - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Impersonate a customer user account created earlier and call the /users/me endpoint to verify the impersonation. Demonstrates user impersonation for testing and delegation. ```python # impersonate_user_call_me.py # Impersonate the user created for the customer and call /users/me to check ``` -------------------------------- ### POST /users Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Creates a new user within the Acronis Cyber Platform. Requires a JSON body containing user details. ```APIDOC ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users #### Request Body - **username** (string) - Required - The desired login name for the user. - **email** (string) - Required - The user's email address. - **first_name** (string) - Required - The user's first name. - **last_name** (string) - Required - The user's last name. - **tenant_id** (string) - Required - The ID of the tenant the user belongs to. - **roles** (array) - Optional - A list of roles assigned to the user. ### Request Example ```json { "username": "newuser", "email": "user@example.com", "first_name": "New", "last_name": "User", "tenant_id": "", "roles": ["administrator"] } ``` ### Response #### Success Response (200) - **user_id** (string) - The ID of the newly created user. - **username** (string) - The username of the created user. #### Response Example ```json { "user_id": "", "username": "newuser" } ``` ``` -------------------------------- ### Create and validate user account with Acronis API Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Creates a new user by validating login availability, constructing user object with contact information, and posting to the Acronis API. Includes login uniqueness check, email validation, and saves the created user response to a JSON file for later reference. ```Python cfg = Config(full=True) acronis = Acronis(cfg) login = input("New login: ") email = input("Please enter a valid email, it will be used for account activation: ") response = acronis.get( f"api/2/users/check_login?username={login}" ) if response.ok and response.status_code == 204: customer = Tenant(os.path.join(base_path, "customer.json")) user = { "tenant_id": f"{customer.tenant_id}", "login": f"{login}", "contact": { "email": f"{email}", "firstname": f"First {login}", "lastname": f"Last {login}" } } response = acronis.post( 'api/2/users', data=json.dumps(user) ) if response.ok: with open(os.path.join(base_path, 'user.json'), 'w') as outfile: json.dump(response.json(), outfile) else: pprint.pprint(response.json()) else: pprint.pprint(response.json()) ``` -------------------------------- ### Generate and Download Usage Report using Acronis API Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md This Python code demonstrates how to generate a usage report for a tenant using the Acronis Cyber Platform API. It initializes an API client, defines report parameters, posts a report generation request, and then polls for the report status until it's saved. Finally, it downloads the report and saves it to a local file. Dependencies include 'acronis', 'json', 'pprint', 'time', and 'os'. ```python from acronis import Acronis from acronis.config import Config import json import pprint import time import os # Assuming base_path is defined elsewhere # base_path = "/path/to/save/reports" cfg = Config(full=True) acronis = Acronis(cfg) report = { "parameters": { "kind": "usage_current", "tenant_id": f"{cfg.tenant_id}", "level": "accounts", "formats": [ "csv_v2_0" ] }, "schedule": { "type": "once" }, "result_action": "save" } response = acronis.post( 'api/2/reports', data=json.dumps(report) ) if response.ok: report_status = "non saved" report_id = response.json()["id"] stored_report_id = None while report_status != "saved": response = acronis.get( f'api/2/reports/{report_id}/stored' ) if response.ok: report_status = response.json()["items"][0]["status"] else: pprint.pprint(response.json()) time.sleep(2) stored_report_id = response.json()["items"][0]["id"] response = acronis.get( f'api/2/reports/{report_id}/stored/{stored_report_id}', ) if response.ok: with open(os.path.join(base_path, f'report_for_tenant_{cfg.tenant_id}.csv'), 'w') as outfile: outfile.write(response.text) else: pprint.pprint(response.json()) else: pprint.pprint(response.json()) ``` -------------------------------- ### Update Customer Tenant Pricing Mode to Production Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Retrieves the current pricing configuration for a customer tenant, changes the pricing mode from trial to production, and updates the tenant with the new pricing settings. This operation is irreversible and requires careful consideration before execution. ```Python response = acronis.get( f'api/2/tenants/{new_customer.tenant_id}/pricing' ) if response.ok: pricing = response.json() pricing["mode"] = "production" response = acronis.put( f'api/2/tenants/{new_customer.tenant_id}/pricing', data=json.dumps(pricing) ) if response.ok: print(f"Customer tenant {new_customer.tenant_id} pricing set to production mode.") else: pprint.pprint(response.json()) else: pprint.pprint(response.json()) ``` -------------------------------- ### POST /api/2/tenants Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Creates a new customer tenant within the Acronis Cyber Platform. The request body should contain the customer's details including name, parent ID, and kind. ```APIDOC ## POST /api/2/tenants ### Description Creates a new customer tenant. ### Method POST ### Endpoint /api/2/tenants #### Request Body - **name** (string) - Required - The name of the customer tenant. - **parent_id** (string) - Required - The ID of the parent tenant. - **kind** (string) - Required - The kind of tenant to create. ### Request Example ```json { "name": "Python Customer v3.0", "parent_id": "", "kind": "" } ``` ### Response #### Success Response (200) - **tenant_id** (string) - The ID of the newly created tenant. #### Response Example ```json { "tenant_id": "" } ``` ``` -------------------------------- ### Backup Plan Template - JSON Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md JSON template defining the structure and configuration options for creating backup protection plans in the Acronis Cyber Platform. Serves as a base configuration for plan creation. ```json # base_plan.json # A backup plan template ``` -------------------------------- ### Create API Client via POST Request with Basic Authentication - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Sends an HTTP POST request to the /api/2/clients endpoint with Basic Authentication to create a new API client. The client configuration object is sent as JSON in the request body. On success, the API client credentials are saved to an api_client.json file; otherwise, error details are displayed. ```Python # Create an API Client with Basic Authentication response = requests.post( f'{cfg.base_url}api/2/clients', headers={**cfg.header, **{'Content-Type': 'application/json'}}, auth=(username, password), data=json.dumps(client) ) if response.ok: # Save the created API Client info to api_client.json file with open(os.path.join(base_path, 'api_client.json'), 'w') as outfile: json.dump(response.json(), outfile) else: pprint.pprint(response.json()) ``` -------------------------------- ### Add Custom User-Agent Header to Acronis API Requests (Python) Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md This Python snippet illustrates how to add a custom User-Agent header to API requests made to the Acronis Cyber Platform. This is useful for identifying your integration in audit logs. The example shows how to define the header dictionary and assign it to the API client's header attribute. Ensure you use a unique integration name, version, and relevant comments for real-world applications. ```python class AcronisAPIClient: def __init__(self, config): # ... other initializations ... self.header = {"User-Agent": "ACP 3.0/Acronis Cyber Platform Python Examples"} # ... rest of the class ... # For a real integration, use: # self.header = {"User-Agent": "/ "} ``` -------------------------------- ### Create and Retrieve Report - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Generate a one-time report for the root tenant in the Acronis Cyber Platform, wait for its completion, and download the generated report. Useful for compliance and auditing. ```python # create_report_retrieve.py # Create an one time report to save for the root tenant, wait till its creation and download ``` -------------------------------- ### Search for Tenant or User - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Search the Acronis Cyber Platform for specific tenant or user accounts. Enables finding users and tenants by name or other criteria. ```python # search_for_tenant_or_user.py # Search for a tenant or user ``` -------------------------------- ### PUT /tenants/{customerTenantId}/pricing Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Updates the pricing configuration for a customer tenant. This is used to switch the customer's account to production mode by modifying the 'mode' field in the pricing JSON. ```APIDOC ## PUT /tenants/{customerTenantId}/pricing ### Description Updates the pricing for a customer tenant, used to switch to production mode. ### Method PUT ### Endpoint /tenants/{customerTenantId}/pricing #### Parameters ##### Path Parameters - **customerTenantId** (string) - Required - The ID of the customer tenant. #### Request Body - **mode** (string) - Required - Set to 'production' to switch to production mode. - Other pricing related fields. ### Request Example ```json { "mode": "production", "currency": "USD", "items": [] } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the pricing update was successful. #### Response Example ```json { "message": "Customer tenant pricing set to production mode." } ``` ``` -------------------------------- ### Create Dynamic Group for Resources - Python Source: https://github.com/acronis/acronis-cyber-platform-python-examples/blob/master/README.md Create a dynamic group in the Acronis Cyber Platform that automatically groups resources based on specified criteria. Dynamic groups allow for flexible resource organization and policy application. ```python # create_dynamic_group.py # Create a dynamic group for resources ```