Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ $ pyaxm-cli [OPTIONS] COMMAND [ARGS]...
* `mdm-server-assigned`: Get the server assignment for a device.
* `assign-device`: Assign one or more devices to an MDM server.
* `unassign-device`: Unassign one or more devices from an MDM...
* `update-mdm-migration-deadline`: Update the MDM migration deadline for one...
* `cancel-mdm-migration`: Cancel an in-progress MDM migration for...
* `audit-events`: Get a list of audit events.
* `users`: List all users in the organization.
* `user`: Get a user by ID.
Expand Down Expand Up @@ -149,6 +151,7 @@ $ pyaxm-cli assign-device [OPTIONS] {device_ids}... {server_id}

**Options**:

* `--deadline <str>`: Migration deadline: YYYY-MM-DD or ISO 8601 (e.g. 2026-03-15 or 2026-03-15T17:00:00.000Z), max 90 days in the future. When set, devices are assigned with an MDM migration deadline.
* `--format <str>`: Output format [default: yaml]
* `--help`: Show this message and exit.

Expand All @@ -172,6 +175,45 @@ $ pyaxm-cli unassign-device [OPTIONS] {device_ids}... {server_id}
* `--format <str>`: Output format [default: yaml]
* `--help`: Show this message and exit.

## `pyaxm-cli update-mdm-migration-deadline`

Update the MDM migration deadline for one or more devices.

**Usage**:

```console
$ pyaxm-cli update-mdm-migration-deadline [OPTIONS] {device_ids}... {deadline}
```

**Arguments**:

* `device_ids...`: [required]
* `deadline`: Migration deadline: YYYY-MM-DD or ISO 8601 (e.g. 2026-03-15 or 2026-03-15T17:00:00.000Z), max 90 days in the future. [required]

**Options**:

* `--format <str>`: Output format [default: yaml]
* `--help`: Show this message and exit.

## `pyaxm-cli cancel-mdm-migration`

Cancel an in-progress MDM migration for one or more devices.

**Usage**:

```console
$ pyaxm-cli cancel-mdm-migration [OPTIONS] {device_ids}...
```

**Arguments**:

* `device_ids...`: [required]

**Options**:

* `--format <str>`: Output format [default: yaml]
* `--help`: Show this message and exit.

## `pyaxm-cli audit-events`

Get a list of audit events.
Expand Down
60 changes: 42 additions & 18 deletions pyaxm/abm_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
OrgDeviceAssignedServerLinkageResponse,
OrgDeviceActivityCreateRequest,
OrgDeviceActivityResponse,
OrgDeviceActivityType,
AppleCareCoverageResponse,
AuditEventsResponse,
UsersResponse,
Expand Down Expand Up @@ -232,18 +233,28 @@ def get_device_server_assignment(self, device_id, access_token) -> OrgDeviceAssi

@exponential_backoff(retries=5, backoff_factor=2)
def assign_unassign_device_to_mdm_server(
self, device_ids: List[str], server_id: str, action: str, access_token: str
self,
device_ids: List[str],
server_id: Optional[str],
action: OrgDeviceActivityType,
access_token: str,
mdm_migration_deadline_date_time: Optional[str] = None,
) -> OrgDeviceActivityResponse:
"""
Assign or unassign one or more devices to/from an MDM server.
Create an org device activity for assignment, unassignment, migration deadline updates,
or migration cancellation.

:param device_ids: List of device IDs.
:param server_id: The ID of the MDM server.
:param action: 'assign' or 'unassign'.
:param server_id: The ID of the MDM server for assign/unassign flows. Optional for
deadline updates and migration cancellation.
:param action: Apple org device activity type.
:param access_token: The access token for authentication.
:param mdm_migration_deadline_date_time: ISO 8601 date-time string (e.g.,
"2026-03-15T17:00:00.000Z") for migration workflows. Cannot be more than
90 days in the future.
"""
url = f'https://api-business.apple.com/v1/orgDeviceActivities'

devices_data = [
{
"id": did,
Expand All @@ -252,23 +263,36 @@ def assign_unassign_device_to_mdm_server(
for did in device_ids
]

request_data = {
"data": {
"type": "orgDeviceActivities",
"attributes": {
"activityType": action
},
"relationships": {
"devices": {
"data": devices_data
},
"mdmServer": {
attributes = {"activityType": action}
if mdm_migration_deadline_date_time is not None:
attributes["activityTypeMetadata"] = {
"mdmMigrationDeadlineDateTime": mdm_migration_deadline_date_time
}

relationships = {
"devices": {
"data": devices_data
}
}

if action in {"ASSIGN_DEVICES", "UNASSIGN_DEVICES", "ASSIGN_DEVICES_WITH_MDM_MIGRATION_DEADLINE"}:
if not server_id:
raise ValueError(f"server_id is required for activity type {action}")
relationships["mdmServer"] = {
"data": {
"id": server_id,
"type": "mdmServers"
}
}
}

if action in {"ASSIGN_DEVICES_WITH_MDM_MIGRATION_DEADLINE", "UPDATE_MDM_MIGRATION_DEADLINE"} and not mdm_migration_deadline_date_time:
raise ValueError(f"mdm_migration_deadline_date_time is required for activity type {action}")

request_data = {
"data": {
"type": "orgDeviceActivities",
"attributes": attributes,
"relationships": relationships,
}
}

Expand All @@ -277,7 +301,7 @@ def assign_unassign_device_to_mdm_server(
response = self.session.post(
url,
headers=self._auth_headers(access_token),
json=request_data.model_dump()
json=request_data.model_dump(mode="json", exclude_none=True)
)

if response.status_code == HTTPStatus.CREATED:
Expand Down
93 changes: 73 additions & 20 deletions pyaxm/cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
import time
from datetime import datetime, timezone

import pandas as pd
Expand All @@ -24,13 +25,13 @@ def _output(data, format: str):


def _parse_audit_timestamp(value: str, *, end_of_day: bool = False) -> str:
"""Parse an audit-event date/timestamp argument.
"""Parse a date/timestamp argument.

Accepts YYYY-MM-DD or full ISO 8601 datetimes.
Accepts YYYY-MM-DD or full ISO 8601 datetimes (with or without a trailing Z).
Date-only values are converted to UTC start/end of day.
"""
try:
parsed = datetime.fromisoformat(value)
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
raise typer.BadParameter(
"Invalid date/time format. Use YYYY-MM-DD or ISO 8601 like 2025-12-31 or 2025-12-31T23:59:59Z."
Expand All @@ -45,6 +46,25 @@ def _parse_audit_timestamp(value: str, *, end_of_day: bool = False) -> str:
return parsed.isoformat().replace("+00:00", "Z")


def _run_device_activity(activity, format: str):
"""Output an org device activity result and download its CSV report."""
info = {"id": activity.id}
if activity.attributes:
info.update(activity.attributes.model_dump())

_output(info, format)

typer.echo(
"Waiting 10 seconds for the activity report to be ready before downloading "
"(this also avoids Apple API rate limiting)..."
)
time.sleep(10)

file_path = download_activity_csv(activity)
if file_path:
typer.echo(f"Report downloaded successfully to: {file_path}")


# ── device commands ─────────────────────────────────────────────────


Expand Down Expand Up @@ -141,20 +161,27 @@ def mdm_server_assigned(
def assign_device(
device_ids: Annotated[List[str], typer.Argument()],
server_id: Annotated[str, typer.Argument()],
deadline: Annotated[
Optional[str],
typer.Option(
"--deadline",
help="Migration deadline: YYYY-MM-DD or ISO 8601 (e.g. 2026-03-15 or "
"2026-03-15T17:00:00.000Z), max 90 days in the future. When set, devices are "
"assigned with an MDM migration deadline.",
),
] = None,
format: Annotated[str, typer.Option("--format", help="Output format")] = "yaml",
):
"""Assign one or more devices to an MDM server."""
client = Client()
activity = client.assign_unassign_device_to_mdm_server(device_ids, server_id, "ASSIGN_DEVICES")
info = {"id": activity.id}
if activity.attributes:
info.update(activity.attributes.model_dump())

_output(info, format)

file_path = download_activity_csv(activity)
if file_path:
typer.echo(f"Report downloaded successfully to: {file_path}")
action = "ASSIGN_DEVICES_WITH_MDM_MIGRATION_DEADLINE" if deadline else "ASSIGN_DEVICES"
activity = client.assign_unassign_device_to_mdm_server(
device_ids,
server_id,
action,
mdm_migration_deadline_date_time=_parse_audit_timestamp(deadline) if deadline else None,
)
_run_device_activity(activity, format)


@app.command()
Expand All @@ -166,15 +193,41 @@ def unassign_device(
"""Unassign one or more devices from an MDM server."""
client = Client()
activity = client.assign_unassign_device_to_mdm_server(device_ids, server_id, "UNASSIGN_DEVICES")
info = {"id": activity.id}
if activity.attributes:
info.update(activity.attributes.model_dump())
_run_device_activity(activity, format)

_output(info, format)

file_path = download_activity_csv(activity)
if file_path:
typer.echo(f"Report downloaded successfully to: {file_path}")
@app.command()
def update_mdm_migration_deadline(
device_ids: Annotated[List[str], typer.Argument()],
deadline: Annotated[
str,
typer.Argument(
help="Migration deadline: YYYY-MM-DD or ISO 8601 (e.g. 2026-03-15 or "
"2026-03-15T17:00:00.000Z), max 90 days in the future."
),
],
format: Annotated[str, typer.Option("--format", help="Output format")] = "yaml",
):
"""Update the MDM migration deadline for one or more devices."""
client = Client()
activity = client.assign_unassign_device_to_mdm_server(
device_ids,
None,
"UPDATE_MDM_MIGRATION_DEADLINE",
mdm_migration_deadline_date_time=_parse_audit_timestamp(deadline),
)
_run_device_activity(activity, format)


@app.command()
def cancel_mdm_migration(
device_ids: Annotated[List[str], typer.Argument()],
format: Annotated[str, typer.Option("--format", help="Output format")] = "yaml",
):
"""Cancel an in-progress MDM migration for one or more devices."""
client = Client()
activity = client.assign_unassign_device_to_mdm_server(device_ids, None, "CANCEL_MDM_MIGRATION")
_run_device_activity(activity, format)


# ── audit events ────────────────────────────────────────────────────
Expand Down
13 changes: 11 additions & 2 deletions pyaxm/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
MdmServerDevicesLinkagesResponse,
OrgDeviceAssignedServerLinkageResponse,
OrgDeviceActivity,
OrgDeviceActivityType,
AuditEvent,
User,
)
Expand Down Expand Up @@ -119,10 +120,18 @@ def _wait_for_device_activity_completion(
return activity_response.data

def assign_unassign_device_to_mdm_server(
self, device_ids: List[str], server_id: str, action: str
self,
device_ids: List[str],
server_id: Optional[str],
action: OrgDeviceActivityType,
mdm_migration_deadline_date_time: Optional[str] = None,
) -> OrgDeviceActivity:
response = self.abm.assign_unassign_device_to_mdm_server(
device_ids, server_id, action, self.token_manager.get_token_value()
device_ids,
server_id,
action,
self.token_manager.get_token_value(),
mdm_migration_deadline_date_time,
)
return self._wait_for_device_activity_completion(response.data.id)

Expand Down
27 changes: 20 additions & 7 deletions pyaxm/models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
from pydantic import BaseModel, ConfigDict, AnyHttpUrl, AwareDatetime, Field
from typing import Annotated, List, Optional, Literal, TypeAlias, Union

OrgDeviceActivityType: TypeAlias = str
OrgDeviceActivityType: TypeAlias = Literal[
"ASSIGN_DEVICES",
"UNASSIGN_DEVICES",
"ASSIGN_DEVICES_WITH_MDM_MIGRATION_DEADLINE",
"UPDATE_MDM_MIGRATION_DEADLINE",
"CANCEL_MDM_MIGRATION",
"RELEASE_DEVICES",
]
AppleCareCoverageStatus: TypeAlias = str
AppleCareCoveragePaymentType: TypeAlias = str
MdmMigrationStatus: TypeAlias = Literal["REQUESTED", "STARTED", "SUCCESS", "FAILED"]
MdmServerStatus: TypeAlias = str
MdmServerProductFamily: TypeAlias = str
UserStatus: TypeAlias = str
Expand Down Expand Up @@ -55,8 +63,9 @@ class Attributes(BaseModel):
serialNumber: Optional[str] = None
status: Optional[str] = None
updatedDateTime: Optional[AwareDatetime] = None
# releaserEntityType: Optional[str] = None Documented, but not returned
# releaserId: Optional[str] = None Documented but not returned
isMdmMigrationCapable: Optional[bool] = None
mdmMigrationStatus: Optional[MdmMigrationStatus] = None
mdmMigrationDeadlineDateTime: Optional[AwareDatetime] = None

class Relationships(BaseModel):
class AssignedServer(BaseModel):
Expand Down Expand Up @@ -98,16 +107,20 @@ class Attributes(BaseModel):
class OrgDeviceActivityCreateRequest(BaseModel):
class Data(BaseModel):
class Attributes(BaseModel):
class ActivityTypeMetadata(BaseModel):
mdmMigrationDeadlineDateTime: Optional[AwareDatetime] = None

activityType: OrgDeviceActivityType

activityTypeMetadata: Optional[ActivityTypeMetadata] = None

class Relationships(BaseModel):
class Devices(BaseModel):
class Data(BaseModel):
id: str
type: Literal['orgDevices']

data: List[Data]

class MdmServer(BaseModel):
class Data(BaseModel):
id: str
Expand All @@ -116,7 +129,7 @@ class Data(BaseModel):
data: Data

devices: Devices
mdmServer: MdmServer
mdmServer: Optional[MdmServer] = None

attributes: Attributes
relationships: Relationships
Expand Down
Loading