Midpoint CLI
This project is a command line client interface used to drive an Evolveum Midpoint identity management server.
Table of Contents
- Quick Start
- Features
- Installation
- Usage
- Usage Examples
- Setting up a sandbox environment
- Requirements
Features
The objectives of this tool are to enable:
- Administrator access to run tasks and review data
- Scripting for remote controlled automation
- Test scenarios implementation
Core Capabilities
The client currently supports:
- User Management: List, search, create, update, and delete users
- Organizational Units: Display and manage organizational structures
- Task Operations: List tasks with status and duration, run tasks synchronously with progress monitoring
- Resource Management: List resources, test connectivity, retrieve configurations
- Object Operations: Retrieve, create, update, and delete any Midpoint object type via XML
- XML Patch Support: Apply modifications to existing objects using XML patches
Task Duration Display
- Running tasks show real-time elapsed time since start
- Completed tasks display total execution time
- Human-readable format (e.g., "2h 35m 20s", "5m 30s", "45s")
- Automatic calculation from Midpoint timestamp fields
Interactive Mode Features
The strong points of this project are:
- Dual Execution Modes: Run commands directly from shell or use an interactive prompt session
- Colorized Output: Color-coded output when running in a terminal for improved readability
- Command History: Bash-compatible command line history with persistent storage across sessions
- Tab Completion: Auto-completion for commands, subcommands, options, object types, and task, user, role, organization and resource names, searched on the server
- Interactive Help: Full built-in help system with command-specific documentation
- Standard CLI Syntax: Classical
midpoint-cli [command] [options]syntax
Configuration Flexibility
- Multiple Auth Methods: Command-line arguments, environment variables, or configuration files
- Configuration Priority: Command-line > Environment variables > Config files > Defaults
- Secure Credential Storage: Use config files, environment variables or the
-Ppassword prompt to avoid exposing passwords on the command line
Quick Start
# Install via pip
pip3 install midpoint-cli
# Check version
midpoint-cli --version
# Start interactive session with credentials via command line
midpoint-cli -u administrator -p password -U https://localhost:8080/midpoint/
# Prompt for the password instead of exposing it in the process list and shell history
midpoint-cli -u administrator -P -U https://localhost:8080/midpoint/
# Or run a direct command
midpoint-cli -u administrator -p password -U https://localhost:8080/midpoint/ users
# Use environment variables for authentication (recommended)
export MIDPOINT_URL="https://localhost:8080/midpoint/"
export MIDPOINT_USERNAME="administrator"
export MIDPOINT_PASSWORD="password"
# Now you can run commands without specifying credentials
midpoint-cli
midpoint-cli users
midpoint-cli tasks
Usage
General syntax
usage: midpoint-cli [-h] [-v] [-u USERNAME] [-p PASSWORD] [-P] [-U URL]
[-t SECONDS] [--read-timeout SECONDS] [-c PATH]
[-o {table,json,csv,tsv}]
[command] ...
An interactive Midpoint command line client.
positional arguments:
command Optional command to be executed immediately.
arg Optional command arguments.
options:
-h, --help show this help message and exit
-v, --version Show version information and exit.
-u, --username USERNAME
Set the username to authenticate this session.
-p, --password PASSWORD
Set the password to authenticate this session.
-P, --ask-password Prompt for the password instead of passing it on the command line,
where it would be visible in the process list and the shell history.
-U, --url URL Midpoint base URL
-t, --timeout SECONDS
Keep retrying a request the server does not answer for up to SECONDS
(default: MIDPOINT_TIMEOUT, then the configuration file, then 120).
--read-timeout SECONDS
Wait up to SECONDS for the answer to each request; a read timeout is not retried
(default: MIDPOINT_READ_TIMEOUT, then the configuration file, then 300).
-c, --config PATH Read settings from this configuration file instead of ~/.midpoint-cli.cfg.
Defaults to the MIDPOINT_CLI_CONFIG environment variable when set.
-o, --output {table,json,csv,tsv}
Output format of list commands (ls, search, users, tasks, ...) and of the
user, role, org and task get details: a table, or json, csv or tsv for scripts.
Defaults to table on a terminal and to tsv when the output is redirected or piped.
The output command changes it during a session.
Available commands:
audit Query the Midpoint audit log (subcommands: ls, object, get).
connector Inspect connectors (subcommand: ls).
del Alias for delete.
delete Delete a server object by type and OID or name.
get Get an XML definition from the server by type and OID or name.
help List available commands with "help" or detailed help with "help cmd".
info Display server information (version, repository, subscription, nodes, account).
log Show and set server logger levels (subcommands: ls, set; or: log LOGGER LEVEL).
org Manage organizations (subcommands: ls, search, get).
orgs Shortcut for 'org ls' — list all organizations.
output Show or change the output format of this session (table, json, csv, tsv).
put Create or update a server object from an XML file.
report List and run reports (subcommands: ls, run).
resource Manage server resources (subcommands: ls, test, import, reconcile).
resources Shortcut for 'resource ls' — list all server resources.
rm Alias for delete.
role Manage roles (subcommands: ls, search, get).
roles Shortcut for 'role ls' — list all roles.
script Execute a local Python client script (subcommand: run).
search Search server objects of any type with a Midpoint Query Language filter.
shadow Inspect resource object shadows (subcommand: ls).
task Manage server tasks (subcommands: ls, run, suspend, resume, wait, get).
tasks Shortcut for 'task ls' — list all server tasks.
user Manage users (subcommands: ls, search, get, assign, unassign, enable, disable, passwd).
users Shortcut for 'user ls' — list all users.
Server URL and credentials can also be stored in ~/.midpoint-cli.cfg, or in a file
named with --config or MIDPOINT_CLI_CONFIG, or read from environment variables
MIDPOINT_URL, MIDPOINT_USERNAME and MIDPOINT_PASSWORD.
Prefer those, or -P, over -p: a password given on the command line is visible to other users.
The retry timeout (--timeout) can also be set with MIDPOINT_TIMEOUT or a timeout
key in the configuration file; it defaults to 120 seconds.
The read timeout (--read-timeout) can also be set with MIDPOINT_READ_TIMEOUT or a
read_timeout key in the configuration file; it defaults to 300 seconds.
Midpoint-cli version 1.6.0, created and maintained by Yannick Kirschhoffer alcibiade@alcibiade.org
Global options must come before the command: everything after the command word is passed
to the command unchanged, so midpoint-cli put -p patch.xml object.xml uses -p as the
put patch flag, not as the password. Likewise write midpoint-cli -o json users, not
midpoint-cli users -o json.
Output formats and scripting (since v1.6)
Every list command (user ls/search, role ls/search, org ls/search, task ls,
resource ls, shadow ls, connector ls, report ls, search, audit ls/object/get,
log ls and the users, roles, orgs, tasks and resources shortcuts) prints its rows in
the format chosen with -o/--output, and so does info, as Property/Value rows:
table: the colored, boxed table, followed by aTotal: N ...line. This is the default on a terminal.tsv: a header line, then one tab-separated line per row, with full values (OIDs are never shortened). Backslash, tab and newline inside a value are written as\\,\tand\n. This is the default when standard output is redirected or piped.csv: the same rows as RFC 4180 CSV, with a header line.json: an array of objects keyed by column name, e.g.[{"OID": "...", "Name": "..."}].
Standard output carries data only: tables, rows, object details and XML. Errors, warnings,
status lines (Waiting for task ..., Object uploaded: ...), totals and task progress go to
standard error, so midpoint-cli get user OID > user.xml never writes an error into
user.xml, and midpoint-cli tasks | grep ... only sees task rows. With audit ... --show-deltas
and audit get, the machine formats carry the deltas as XML in an extra Deltas column instead
of the delta tree.
The audit listings end with an EventIdentifier column (before Deltas), the value
audit get takes:
midpoint-cli -o tsv audit ls --since 1h | cut -f8 # event identifiers, after the header line
The detail views user get, role get, org get and task get follow -o too. The table
format shows the same tables as before; the machine formats give:
-
json: one object per object shown, or an array of objects whentask getis given several tasks. Every value is a string. Related records are arrays of objects keyed by the column names of their table: a user hasRolesandOrgs(OID,Name,Status) andProjections(Shadow OID,Resource,Account Name,Kind,Intent); a task hasTransitions(From State,To State,Count) andActions(Type,Action,Success,Failure). A user's attributes keep their schema names (name,fullName, ...), and a property present several times is an array of its values. Role and org objects carry all their properties, empty ones included, so every object has the same keys.midpoint-cli -o json user get jdoe | jq -r '.Roles[].Name' midpoint-cli -o json task get 'Recompute users' | jq '.Actions[] | select(.Failure != "0")'
-
csv,tsv:Property/Valuerows, one per value, likeinfo. Values of related records are named by their path, e.g.Roles[0].NameorActions[1].Failure; a repeated property issubtype[0],subtype[1]. With several tasks, their rows follow each other, each task starting with itsOIDrow.
get is not affected: it always prints the XML exactly as the server returned it.
In an interactive session or a piped command script, output FORMAT switches the format for
the commands that follow, and output alone shows the current one:
midpoint> output json
ℹ Output format set to json
midpoint> user get jdoe
{ ... }
midpoint> output table
External configuration files (since v1.2)
Settings can be provided from an external configuration file. A single file is read:
- the file named with
--config PATH(-c PATH), if given; - otherwise the file named by the
MIDPOINT_CLI_CONFIGenvironment variable, if set; - otherwise
.midpoint-cli.cfgin the home directory of the current user, if it exists.
A named file that does not exist or cannot be parsed is an error. A midpoint-cli.cfg in the
current working directory is not read implicitly (since v1.6): a file picked up from
whatever directory you happen to be in could redirect the server URL your credentials are
sent to. Name it explicitly instead, for example midpoint-cli --config midpoint-cli.cfg.
Values from the configuration file are overridden by environment variables, which are in turn overridden by command-line options.
Without any setting, the URL defaults to http://localhost:8080/midpoint/ and the user to
administrator. There is no default password (since v1.6): when none comes from -p/-P,
MIDPOINT_PASSWORD or the configuration file, midpoint-cli prompts for it if standard input is
a terminal, and otherwise stops with an error (exit code 2) instead of trying the Midpoint demo
password. Code that builds a MidpointClientConfiguration directly gets no default password
either: the client refuses to send a REST call until one is set.
A configuration file holding a password should be readable by you alone (chmod 600). When it
is accessible by group or other users, midpoint-cli prints an SSH-style warning on stderr,
unless the server URL is a loopback address such as the local sandbox.
An interactive session starts by naming the server URL, user, retry timeout and read timeout in effect and where each
setting came from (command-line option, environment variable, which configuration file, or
default), and points out a midpoint-cli.cfg in the working directory that is not being read.
The info command prints the same line before the server information, also in one-shot
and piped use, where there is no banner.
The syntax is as follows:
[Midpoint]
url = https://localhost:8080/midpoint/
username = administrator
password = ...
# Optional: seconds to keep retrying a request the server does not answer (default 120)
timeout = 300
# Optional: seconds to wait for the answer to one request (default 300)
read_timeout = 900
Environment variables (since v1.2)
The script will scan environment variables to read input parameters. This is particularly useful for injection of password or in-container execution.
The variables are:
- MIDPOINT_URL
- MIDPOINT_USERNAME
- MIDPOINT_PASSWORD
- MIDPOINT_TIMEOUT: how long, in seconds, to keep retrying a request when the server
does not answer (refused connection, connect timeout), for example while it is still
booting. Defaults to 120. Scripts that start a Midpoint server and call the CLI straight
away should wait for the server first, or raise this value. The
-t SECONDS(--timeout SECONDS) option overrides it, and it overrides atimeoutkey in the configuration file. A value that is not a positive number is a usage error (exit code 2) on the command line and in the configuration file; inMIDPOINT_TIMEOUTit is ignored with a warning. - MIDPOINT_READ_TIMEOUT: how long, in seconds, to wait for the answer to one request once
the server has accepted it. Defaults to 300; raise it for calls that legitimately take
longer (large searches, slow resource tests, synchronous task runs). A read timeout is
reported at once and never retried, since the server may still be processing the request.
The
--read-timeout SECONDSoption overrides it, and it overrides aread_timeoutkey in the configuration file, with the same validation asMIDPOINT_TIMEOUT. - MIDPOINT_CLI_FOLLOW_SYMLINKS: set to
1(ortrue,yes,on) to letget ... FILEandput -p ... -wwrite through a symbolic link. By default they refuse (since v1.6): see Get user details.
Usage Examples
Interactive Mode
The interactive mode is one of the strongest features of midpoint-cli. It provides a persistent session with command history, tab completion, colorized output, and a built-in help system. This is ideal for exploring your Midpoint server, troubleshooting, and performing multiple operations without re-authenticating.
Starting an Interactive Session
# Start interactive session with authentication
midpoint-cli -u administrator -p mypassword -U https://midpoint.example.com/midpoint/
# Or use environment variables (recommended)
export MIDPOINT_URL="https://midpoint.example.com/midpoint/"
export MIDPOINT_USERNAME="administrator"
export MIDPOINT_PASSWORD="mypassword"
midpoint-cli
# Or use a configuration file
# Create ~/.midpoint-cli.cfg with your credentials
midpoint-cli
Interactive Features
Command History Navigation:
- Use arrow keys (↑/↓) to navigate through command history
- History is persistent across sessions (bash-compatible)
- Search history with Ctrl+R
Tab Completion:
- Complete commands, subcommands and
--optionsby pressing Tab - Object types after
getanddelete(e.g.get us<Tab>→user), then names when the type is a task, user, role, org or resource (e.g.delete user jd<Tab>→jdoe) - Names for
task get/run/wait/suspend/resume,user get/assign/unassign,role get,org get,resource testandaudit ls --user; names containing spaces are quoted for you - Names are looked up on the server by prefix (case-insensitive), at most 50 at a time
- File paths for
put,script runand the optional output file ofget
Colorized Output:
- Automatic color-coded output when running in a terminal
- Improved readability for status indicators and tables
Built-in Help System:
midpoint> help
# Shows all available commands
midpoint> help users
# Shows detailed help for the users command
midpoint> help task
# Shows task-related subcommands and usage
Common Interactive Workflows
Exploring Users and Organizations:
midpoint> users
# Lists all users with their details
midpoint> user search john
# Search for users matching "john" (in name, full name or email)
midpoint> user search +example.com Doe Smith
# Users at example.com who match Doe or Smith (mandatory + optional OR)
midpoint> org
# List all organizational units
midpoint> get user 12345678-abcd-1234-abcd-123456789012
# Get detailed XML definition of a specific user
Task Management Workflow:
midpoint> tasks
# View all tasks with status and duration
midpoint> task run "Recompute All Users"
# Execute a task and monitor progress
# For running tasks, duration shows elapsed time
# For completed tasks, duration shows total execution time
midpoint> tasks
# Check updated status after task completion
Resource Testing and Monitoring:
midpoint> resources
# List all configured resources
midpoint> resource test "Active Directory"
# Test connectivity to a specific resource
midpoint> tasks
# View any reconciliation tasks that may have been triggered
Quick Object Inspection:
midpoint> get user 00000000-0000-0000-0000-000000000002
# Get administrator user definition
midpoint> get task 12345678-task-1234-abcd-123456789012
# Get task details and configuration
midpoint> get resource 12345678-res1-1234-abcd-123456789012
# Get resource configuration
Interactive vs. Direct Execution
Interactive mode advantages:
- No need to re-authenticate for each command
- Command history for repeated operations
- Tab completion for faster input
- Persistent session for exploration
- Better for troubleshooting and manual operations
Direct execution advantages:
- Better for scripting and automation
- Can be used in CI/CD pipelines
- Single command operations
- Output can be easily piped to other commands
Commands can also be piped on standard input, one per line. Every line runs, and the process
exits with the code of the first line that failed (for example 3 for a script run that called
sys.exit(3)), or 0 when all of them succeeded.
Example comparison:
# Direct execution - requires full authentication each time
midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/ users
midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/ tasks
midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/ resources
# Interactive mode - authenticate once, run multiple commands
midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/
midpoint> users
midpoint> tasks
midpoint> resources
midpoint> task run "Recompute All Users"
midpoint> tasks
midpoint> exit
User Management
List all users
# Direct command execution
midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/ users
# Output example:
# OID Name Title FullName Status EmpNo Email OU
# ------------------------------------ ------------- -------------- --------------- -------- ------- ----------------------- ----
# 00000000-0000-0000-0000-000000000002 administrator Administrator enabled admin@example.com
# 12345678-abcd-1234-abcd-123456789012 jdoe IT Manager John Doe enabled E12345 jdoe@example.com IT
Limit and filter a listing
Every ls command (user, role, org, task, resource) accepts --limit N and
--filter TEXT. With either option the server filters and pages the list instead of the CLI
downloading the whole collection, which matters on deployments with many objects:
# The first 20 users, sorted by name
midpoint-cli user ls --limit 20
# Tasks whose name contains "recon" (case-insensitive)
midpoint-cli task ls --filter recon
# Both
midpoint-cli role ls --filter admin --limit 10
Without these options ls lists the whole collection, as before.
Search for a specific user
# Search by name, full name or email (OR: matches users containing "john" OR "jane")
midpoint-cli user search john jane
# Mandatory terms with + prefix (AND: must contain both "john" AND "doe")
midpoint-cli user search +john +doe
# Mixed: email must contain example.com AND name must match Doe or Smith
midpoint-cli user search +example.com Doe Smith
Searches run on the server. Terms are case-insensitive and matched as substrings of the user's
name, full name and email address (role search and org search match the name and display
name). Name matching uses Midpoint's normalized form, so accents are ignored (e.g. francois
matches François).
Get user details (XML definition)
# Retrieve full XML definition of a user by OID
midpoint-cli get user 12345678-abcd-1234-abcd-123456789012
# Save user definition to a file
midpoint-cli get user 12345678-abcd-1234-abcd-123456789012 > user-backup.xml
# A name works too
midpoint-cli get user jdoe
# Or let midpoint-cli write the file, readable by you only (mode 0600)
midpoint-cli get user 12345678-abcd-1234-abcd-123456789012 user-backup.xml
Files written by midpoint-cli itself (get TYPE OID FILE, and the <patchfile>.xml written by
put -p PATCH -w) can hold passwords and personal data, so they are created with mode 0600 and
an existing file is tightened to 0600 before it is overwritten. Since v1.6 midpoint-cli also
refuses to write when the target is a symbolic link, because a link planted in a shared
directory would otherwise redirect the export to another file and overwrite it. The command
fails with an error naming the link and nothing is written. Directories along the path may still
be links. If you write through a link on purpose, give the link target instead (for example
"$(readlink -f user-backup.xml)"), or set MIDPOINT_CLI_FOLLOW_SYMLINKS=1.
Create or update a user
# Upload a user definition from an XML file
midpoint-cli put user-definition.xml
# Upload a user definition after applying a patch file to it
midpoint-cli put -p user.patch user-definition.xml
When the root element has an oid attribute, put creates or replaces the object at that
OID and prints Object uploaded: UserType <oid>. Without one, it creates a new object, the
server assigns the OID and put prints Object created: UserType <oid>. If the server
accepts the object without creating it yet (for example while an approval is pending), put
prints Object accepted without an OID.
See Apply patches to objects for the patch file format.
Assign roles, orgs, archetypes and services
# Assign a role (the default target type), then remove the assignment
midpoint-cli user assign jdoe "Employee"
midpoint-cli user unassign jdoe "Employee"
# Org membership, archetype and service assignments
midpoint-cli user assign jdoe --org "Sales"
midpoint-cli user assign jdoe --archetype "Contractor"
midpoint-cli user unassign jdoe --service "Printer"
The option names the type of the target, which is looked up by name or OID in that type
only: user assign jdoe --org Employee fails if no org is named Employee, even when a role
is.
Enable, disable and set passwords
# Set the administrative status of one or more users
midpoint-cli user disable jdoe asmith
midpoint-cli user enable jdoe
# Set a password: asked twice, without echo, on a terminal
midpoint-cli user passwd jdoe
# In scripts, the first line of standard input is the password...
printf '%s\n' "$NEW_PASSWORD" | midpoint-cli user passwd jdoe
# ...or an environment variable names it
NEW_PASSWORD=... midpoint-cli user passwd jdoe --password-env NEW_PASSWORD
The password is sent as a protected string in clear (t:clearValue) and the server encrypts
or hashes it as its policy says; the server also checks it against the password policy. It is
never printed, logged or written to the command history, and no option takes the password
itself, so it never appears in the process list. In a command script piped to midpoint-cli,
the password is the line after user passwd.
Delete a user
# Delete a user by OID
midpoint-cli delete user 12345678-abcd-1234-abcd-123456789012
# Delete a user by name: asks for confirmation in a terminal (the question is written
# on stderr); scripts must add --yes
midpoint-cli delete user jdoe --yes
Names and OIDs
Every command that takes an object (get, delete, user get/assign/unassign/
enable/disable/passwd, role get, org get, task run/get/wait/suspend/resume,
resource test/import/reconcile, shadow ls --resource, report run and
audit ls --user) accepts an OID or a name. A value in OID form is used as an OID. Names
are looked up on the server, exactly and case-sensitively. Some names are not unique: task
names, for instance, often repeat. When a name matches several objects, the command lists
their OIDs and does nothing with them, instead of acting on whichever came first:
$ midpoint-cli task run Recompute
Error: Ambiguous task name 'Recompute': 2 objects have it (OIDs: 3f2a..., 9c41...). Use an OID instead.
Organization Management
List organizational units
# List all organizational units
midpoint-cli org
# Interactive mode
midpoint> org
# OID Name Parent Description
# ------------------------------------ -------------- -------- ---------------------
# 12345678-org1-1234-abcd-123456789012 Engineering Root Engineering Department
# 12345678-org2-1234-abcd-123456789012 IT Operations Root IT Operations Team
Get organization details
# Get full XML definition of an org unit
midpoint-cli get org 12345678-org1-1234-abcd-123456789012
Task Management
List all tasks
# List all tasks with status and duration
midpoint-cli tasks
# Output shows running tasks with elapsed time and completed tasks with total execution time
# Task Name Status Duration Last Run
# --------------------------- --------- ---------- --------------------
# Import from HR System running 1h 25m 30s 2025-10-14 10:30:00
# Recompute All Users closed 5m 42s 2025-10-14 09:15:00
# Reconciliation Task waiting - Not yet started
List tasks by status
# Suspended tasks, and tasks whose last run failed (fatal or partial error)
midpoint-cli task ls --status suspended
midpoint-cli task ls --status failed
# Repeat --status to list tasks in any of several states
midpoint-cli task ls --status running --status runnable
--status takes an execution state (running, runnable, waiting, suspended, closed)
or the result of the last run (in_progress, success, warning, failed). The server
filters the tasks, so it combines with --limit and --filter.
Execute a task synchronously
# Run a task and wait for completion
midpoint-cli task run "Recompute All Users"
# Run task by OID
midpoint-cli task run 12345678-task-1234-abcd-123456789012
While task run and task wait follow a task, standard error shows one mark per processed
item: . for a success and F for a failure, where failures are the failed actions of the
task statistics. A summary with the success and error counts ends the progress. On a terminal,
the progress is a single animated line instead: a bar (filled against the expected total when
the task has one), the items processed, the success and failure counts, the most recent marks
(failures in red) and the time since the task started:
⠙ ━━━━━━━━━━━━━━━━╺━━━━━━━ 40/60 66% ✓ 35 ✗ 5 F.............FF 0:30
When a task fails, its details, transitions and action counts are printed before the error. While the server cannot be reached, a terminal shows a spinner with the number of retries and the time waited; elsewhere, a dot is printed per retry.
Get task details
# Get task status and XML definition
midpoint-cli get task 12345678-task-1234-abcd-123456789012
Monitor long-running tasks
# In interactive mode, you can repeatedly check task status
midpoint> task run "Import from HR System"
# Task started: 12345678-task-1234-abcd-123456789012
# Status: running (Duration: 5m 30s)
midpoint> tasks
# Check all running tasks with real-time duration updates
Resource Management
List all resources
# List configured resources
midpoint-cli resources
# Example output:
# OID Name Type Status
# ------------------------------------ ---------------- ------------ --------
# 12345678-res1-1234-abcd-123456789012 Active Directory LDAP UP
# 12345678-res2-1234-abcd-123456789012 HR Database Database UP
resource ls (and resources) exits with status 1 when any listed resource reports an
availability status other than up. Resources with no recorded status (e.g. never tested)
and an empty resource list do not affect the exit status.
Shadow metrics
# Count the shadows of each resource by synchronization situation
midpoint-cli resource ls --metrics
midpoint-cli -o csv resource ls --metrics --filter HR
--metrics adds the columns Linked, Unlinked, Unmatched, Disputed, Deleted,
No Situation and Shadows (the total) to each resource. The counts cover every shadow the
repository holds for the resource (all kinds and intents, dead shadows included); they are
read with the raw option, so no resource is contacted.
The metrics are optional because their cost depends on the server version:
- Midpoint 4.10 and later count on the server (
returnTotalCount), with six small searches per resource whatever its size. - Midpoint 4.4 to 4.9 cannot return a count over REST, so all shadows of each resource are
downloaded in one search and counted by the CLI. On resources with many thousands of
accounts this is slow and memory hungry: narrow the listing with
--filteror--limit.
A resource whose shadows cannot be counted (e.g. the account may not read shadows) gets empty cells and a warning on standard error; the exit status still only reflects availability.
Test a resource connection
# Test resource connectivity
midpoint-cli resource test 12345678-res1-1234-abcd-123456789012
# Test by resource name
midpoint-cli resource test "Active Directory"
Import and reconcile a resource
# Import the accounts of a resource, following the task like `task run`
midpoint-cli resource import "HR Database"
# Reconcile the entitlements of one intent
midpoint-cli resource reconcile "Active Directory" --kind entitlement --intent group
# Select by object class instead, and return at once with the task OID on standard output
TASK_OID=$(midpoint-cli resource import "Active Directory" --object-class inetOrgPerson --no-wait)
Midpoint's REST API has no import or reconciliation operation for a kind and intent, so these
commands create the task the Midpoint GUI would create (an activity-based task with the Import
or Reconciliation task archetype, named after the resource and the time) and the server starts
it. Without --kind and --object-class, the accounts of the resource are processed. The
task stays on the server: task run runs it again.
List shadows and connectors
# Shadows of one resource, kind and intent, with their synchronization situation
midpoint-cli shadow ls --resource "HR Database" --kind account --intent default
# Connectors installed on the server, with their type, version and bundle
midpoint-cli connector ls
shadow ls reads the Midpoint repository only (a raw search): it shows what Midpoint last
saw on the resource without contacting it.
Get resource configuration
# Retrieve full resource definition
midpoint-cli get resource 12345678-res1-1234-abcd-123456789012 > ad-resource.xml
Server Information
midpoint-cli info
# Same data as Property/Value rows, for scripts
midpoint-cli -o json info
info gathers what the REST API tells about the server, in the spirit of the web UI's
About page:
| Property | Source | Notes |
|---|---|---|
| Midpoint Version, Build, Branch, Build Timestamp, License | actuator/info |
All versions 4.4 to 4.11. Without it, the version comes from the nodes' build. |
| Repository | the version | native (PostgreSQL) from 4.10 on, where the generic repository is gone. Earlier versions do not report it over REST: see the About page. |
| Deployment Name, Subscription | system configuration (deploymentInformation) |
Only says whether a subscription identifier is configured, never the identifier itself; the server decides whether it is valid. |
| Nodes, Node id | ws/rest/nodes |
Host, execution state, Midpoint build and last check-in of each cluster node. |
| Logged In As | ws/rest/self |
The account the CLI authenticated as. |
A source the account may not read (or a proxy hides) is left out with a warning on standard
error, and info still succeeds. It fails when nothing can be read, or at once when the server
does not answer or rejects the credentials.
Logger Levels
# Raise the level of a logger, adding it to the logging configuration if needed
midpoint-cli log lu.lns.connector DEBUG
# Same, with the explicit subcommand
midpoint-cli log set com.evolveum.midpoint.model.impl.lens.Clockwork TRACE
# List the configured class loggers; the root logger level follows the table
midpoint-cli log ls
log edits the logging section of the system configuration (OID
00000000-0000-0000-0000-000000000001), which Midpoint applies as soon as it is saved. The level is
one of ALL, OFF, ERROR, WARN, INFO, DEBUG and TRACE, in any case. Only the logging items
are sent, as a REST PATCH: the level of an existing class logger is replaced, a new logger is
added without appenders, so its messages go to the root logger's appenders. Setting the level a logger
already has sends nothing. log ls honours -o (Logger, Level and Appenders columns).
Use log set for a logger literally named ls or set.
Reports
# List reports, then run one and wait for it
midpoint-cli report ls
midpoint-cli report run "Users in MidPoint"
report run creates a report export task, like the Midpoint GUI. The server stores the output
as a report data object, which the GUI lists under Reports > Created reports.
Searching any object type
# Disabled users, with a Midpoint Query Language filter evaluated by the server
midpoint-cli search user --filter 'activation/administrativeStatus = "disabled"'
# At most 10 roles whose name starts with App
midpoint-cli search role --filter 'name startsWith "App"' --limit 10
# Shadows of a resource, searched in the repository only (--raw)
midpoint-cli search shadow --raw --filter 'resourceRef matches (oid = "<resource OID>") and kind = "account"'
search takes any object type that get takes. The filter is written in the Midpoint Query
Language (Axiom), which the REST search of Midpoint 4.4 and later accepts; a filter the server
cannot parse is reported as an error.
Audit Log
# Latest audit events, then the history of one object
midpoint-cli audit ls --since 1h --limit 20
midpoint-cli audit object 00000000-0000-0000-0000-000000000002
# One event with its deltas, by the EventIdentifier column of audit ls
midpoint-cli audit get 1715251800000-0-1
Midpoint has no REST endpoint for audit search, so audit (and the change stream shown by
task run) sends a small Groovy script to rpc/executeScript.
The task run change stream starts 60 seconds before the client's clock, or at the run start
reported by the server when that is later, so a client clock ahead of the server's does not
hide the first events. If the same task ran shortly before, the stream can therefore begin
with the last events of that earlier run.
The script uses Midpoint-internal classes, so the CLI reads the server version from
actuator/info and adapts the script to it. If a server release moves or changes those
classes, the CLI reports that the script could not be compiled or run on that server version.
Midpoint 4.11 and later
Midpoint 4.11 refuses Groovy by default, even for administrators, and the CLI then reports which server check blocked it. To enable audit search:
-
In
config.xml, setsafeScriptingLanguagesOnlytofalseand restart Midpoint. Skip this step if yourconfig.xmlhas no such setting.<expressions> <safeScriptingLanguagesOnly>false</safeScriptingLanguagesOnly> </expressions>
-
In the system configuration, add an expression profile that allows Groovy and use it for privileged principals:
<expressions> <expressionProfile> <identifier>privileged-groovy</identifier> <decision>allow</decision> </expressionProfile> <defaults> <privilegedPrincipal>privileged-groovy</privilegedPrincipal> </defaults> </expressions>
This gives privileged principals the same unrestricted scripting they had before 4.11, so weigh it against your security requirements.
Scripting and Automation
Batch operations with scripts
#!/bin/bash
# Script to backup all users
MIDPOINT_URL="https://midpoint.example.com/midpoint/"
MIDPOINT_USERNAME="administrator"
MIDPOINT_PASSWORD="mypassword"
export MIDPOINT_URL MIDPOINT_USERNAME MIDPOINT_PASSWORD
# Create backup directory
mkdir -p user-backups
# List users as TSV (OID and Name are the first two columns), skip the header, back up each one
midpoint-cli -o tsv users | tail -n +2 | while IFS=$'\t' read -r OID NAME _; do
echo "Backing up user: $NAME ($OID)"
midpoint-cli get user "$OID" > "user-backups/${NAME}.xml"
done
echo "Backup completed!"
Automated user provisioning
#!/bin/bash
# Create users from a list
MIDPOINT_CLI="midpoint-cli -u admin -p pass -U https://localhost:8080/midpoint/"
# Read user list and create each user
while IFS=',' read -r username fullname email; do
cat > /tmp/new-user.xml <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
<name>$username</name>
<fullName>$fullname</fullName>
<emailAddress>$email</emailAddress>
<credentials>
<password>
<value>
<t:clearValue>ChangeMe123</t:clearValue>
</value>
</password>
</credentials>
</user>
EOF
echo "Creating user: $username"
$MIDPOINT_CLI put /tmp/new-user.xml
done < users.csv
Task automation with environment variables
# Use environment variables for credentials (more secure)
export MIDPOINT_URL="https://midpoint.example.com/midpoint/"
export MIDPOINT_USERNAME="administrator"
export MIDPOINT_PASSWORD="$(cat /secure/location/password.txt)"
# Run tasks without exposing credentials in command line
midpoint-cli task run "Daily User Reconciliation"
midpoint-cli task run "Nightly Cleanup Task"
# Check task status: names of the tasks whose execution status is running or runnable
midpoint-cli -o tsv task ls --status running --status runnable | tail -n +2 | cut -f 2
Continuous monitoring script
#!/bin/bash
# Monitor running tasks and send alerts
while true; do
RUNNING_TASKS=$(midpoint-cli -o json task ls --status running --status runnable | jq length)
if [ "$RUNNING_TASKS" -gt 5 ]; then
echo "WARNING: More than 5 tasks running simultaneously!"
# Send alert (e.g., via email or Slack)
fi
# Check for suspended tasks (OID and name of each)
FAILED_TASKS=$(midpoint-cli -o json tasks | jq -r '.[] | select(."Execution Status" == "suspended") | "\(.OID) \(.Name)"')
if [ -n "$FAILED_TASKS" ]; then
echo "ALERT: Failed tasks detected:"
echo "$FAILED_TASKS"
fi
sleep 60 # Check every minute
done
Running Python client scripts
script run executes a local Python file (or standard input with -) with two variables in
scope: client, the authenticated MidpointClient, and tc, a unittest.TestCase for
assertions. A failed assertion or an uncaught exception exits with status 1, and the script may
call sys.exit() to choose its own exit code, which makes it convenient for end-to-end checks:
echo 'assert len(client.get_users()) > 0' | midpoint-cli script run -
midpoint-cli script run checks/provisioning.py
Scripts can import the rest of the client API from midpoint_cli.client. Object types are the
values of MidpointObjectTypes (for example MidpointObjectTypes.USER.value). To look one up from
a string, use MidpointObjectTypes.find_by_name (lenient: user, User, UserType) or one of
the exact lookups find_by_tagname('user'), find_by_java_type('UserType') and
find_by_endpoint('users'). All of them raise midpoint_cli.client.objects.MidpointTypeNotFound
when nothing matches:
echo "from midpoint_cli.client import MidpointObjectTypes
print(client.get_xml(MidpointObjectTypes.find_by_name('role'), 'role-oid'))" | midpoint-cli script run -
Scripts run as-is, with full access to the server through the configured credentials. Only run scripts you trust, exactly as you would with any other program handed your administrator password.
Working with XML Definitions
Export configuration for version control
# Export all critical configurations
mkdir -p midpoint-config
# Export resources (resources exits 1 when a resource is not up, hence the "|| true")
{ midpoint-cli -o tsv resources || true; } | tail -n +2 | while IFS=$'\t' read -r OID NAME _; do
midpoint-cli get resource "$OID" > "midpoint-config/resource-${NAME}.xml"
done
# Export roles
midpoint-cli get role 00000000-0000-0000-0000-000000000004 > midpoint-config/superuser-role.xml
# Commit to version control
git add midpoint-config/
git commit -m "Backup Midpoint configuration"
Apply patches to objects
put -p PATCH FILE... applies a patch file to each XML file before uploading it. This keeps one
exported definition and adapts it per environment, for example to swap host names and secrets
between test and production. The patch only edits the text sent to the server: the XML files
on disk are not changed. With -w, the patched XML is also saved to PATCH.xml (mode 0600),
which helps to check the result.
# Export a resource once
midpoint-cli get resource 12345678-res1-1234-abcd-123456789012 ldap.xml
# Production values; quote the heredoc delimiter so the shell leaves backslashes alone
cat > prod.patch <<'EOF'
# Host names: escape the dots so they only match literally
ldap-test\.example\.com => ldap.example.com
# Replace the whole element content, whatever it was
<baseContext>[^<]*</baseContext> => <baseContext>dc=example,dc=com</baseContext>
# Password s3\cret: the backslash is doubled in the replacement
CHANGEME => s3\\cret
# A line without '=>' deletes every match
<!-- DEBUG -->
EOF
# Upload the patched resource, and keep a copy of what was sent in prod.patch.xml
midpoint-cli put -p prod.patch -w ldap.xml
Patch file format
A patch file is a list of regular-expression substitutions, applied in order to the whole XML text (each line works on the result of the previous ones):
- Each line is
PATTERN => REPLACEMENT. Every match ofPATTERNis replaced, not only the first one. Whitespace around both sides is ignored. - Only the first
=>(a space followed by=>) splits the line, so a replacement may itself contain=>. A pattern cannot contain=>; write it[ ]=>instead. - A line without
=>(or with nothing after it) is a deletion: every match of the pattern is removed. - Blank lines and lines starting with
#are ignored. PATTERNis a Python regular expression. Metacharacters keep their regex meaning:.matches any character, soldap.example.comalso matchesldapXexample.com. Escape. ^ $ * + ? { } [ ] \ | ( )with a backslash to match them literally (ldap\.example\.com)..does not match a line break, so<!--.*removes a comment opening up to the end of its line.REPLACEMENTis a Pythonre.subtemplate:\1,\2, ... insert the groups captured by the pattern, so<port>(\d+)</port> => <port>\1</port><ssl>false</ssl>keeps the port. A literal backslash must be doubled: a passwords3\cretis writtens3\\cret.- A line that matches nothing prints a warning naming the line and leaves the XML unchanged; the upload goes ahead.
- A line that is not a valid pattern or replacement (for example an unbalanced
(, or a single backslash in the replacement such ass3\cret) stopsputbefore that file is uploaded, and the files after it are skipped. The error names the file and the offending line, and the command exits with status 1.
Using Configuration Files
Create a configuration file for each environment and select one with --config or
MIDPOINT_CLI_CONFIG; without either, only ~/.midpoint-cli.cfg is read:
~/.midpoint-cli.cfg (Production):
[Midpoint]
url = https://midpoint.production.example.com/midpoint/
username = automation-user
password = secure-production-password
./midpoint-cli.cfg (Development - used only when named explicitly, it replaces the home directory config):
[Midpoint]
url = https://localhost:8080/midpoint/
username = administrator
password = 5ecr3t
Then simply run commands without authentication parameters:
# Uses configuration from ~/.midpoint-cli.cfg
midpoint-cli users
midpoint-cli tasks
midpoint-cli resource test "AD Resource"
# Uses the development configuration instead
midpoint-cli --config midpoint-cli.cfg users
export MIDPOINT_CLI_CONFIG=./midpoint-cli.cfg
midpoint-cli tasks
Requirements
This program is compatible with Python version 3.11 or above.
Installation
Through PyPI
The most common way to install midpoint-cli on your own computer is to use the PyPI repository:
pip3 install midpoint-cli
The installation will automatically install all required dependencies including:
requestsandurllib3for HTTP communication with the Midpoint REST APIrichfor tables, colors and progress displaydefusedxmlfor safe parsing of XML returned by the serverprompt-toolkitfor the interactive prompt, history and tab completionpygmentsfor XML syntax highlightingunidecodefor accent-insensitive searching
Standalone Linux binary
Each release also ships a single-file binary, midpoint-cli-linux-amd64, that needs no Python
installation. Download it from the assets of the
release page, or directly by tag:
TAG=1.6.0 # the release tag
curl -fLo midpoint-cli "https://gitlab.com/api/v4/projects/alcibiade%2Fmidpoint-cli/packages/generic/midpoint-cli/${TAG}/midpoint-cli-linux-amd64"
chmod +x midpoint-cli
./midpoint-cli --version
The binary is built on AlmaLinux 8 and runs on x86_64 Linux distributions with glibc 2.28 or
later: RHEL, Rocky and AlmaLinux 8+, Debian 10+, Ubuntu 20.04+, Amazon Linux 2023, openSUSE Leap
15.6 and current Fedora. It does not run on older glibc (Amazon Linux 2, CentOS 7) or on musl
distributions such as Alpine; use pip3 install midpoint-cli there.
Binaries are attached to releases after 1.5.0.
Development build
Dependency management, build and test is managed using Python Poetry.
To install Poetry, please refer to the official Python Poetry website.
To install the current development version from GIT:
git clone https://gitlab.com/alcibiade/midpoint-cli.git
cd midpoint-cli
poetry install
poetry run midpoint-cli --version
poetry.lock is committed so that every checkout and CI run installs the same dependency
versions. After changing a dependency in pyproject.toml, run poetry lock and commit the
updated lock file.
Anaconda
Anaconda packages are not available yet.
Setting up a sandbox environment
If you wish to test this project locally and don’t have a midpoint server available, you can use the following instructions.
Using the Evolveum managed Docker image
Pull the image locally:
yk@lunar:~$ docker pull evolveum/midpoint
Using default tag: latest
latest: Pulling from evolveum/midpoint
[...]
Digest: sha256:1e29b7e891d17bf7b1cf1853c84609e414c3a71d5c420aa38927200b2bdecc8e
Status: Downloaded newer image for evolveum/midpoint:latest
docker.io/evolveum/midpoint:latest
Then run the server and bind the port 8080:
yk@lunar:~$ docker run -d --name midpoint-1 -p8080:8080 evolveum/midpoint
c048d519395ca48c8e94e361a2239b1c35c5e5305a29600895056e030d6a576f
yk@lunar:~$ midpoint-cli
Welcome to Midpoint client ! Type ? for a list of commands
midpoint> users
OID Name Title FullName Status EmpNo Email OU
------------------------------------ ------------- ------- ---------------------- -------- ------- ------- ----
00000000-0000-0000-0000-000000000002 administrator midPoint Administrator enabled
midpoint>
yk@lunar:~$ docker stop midpoint-1
midpoint-1
Metadata
Release files for midpoint-cli 1.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| midpoint_cli-1.6.0.tar.gz | 129.3 kB | Without provenance | Details for midpoint_cli-1.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| midpoint_cli-1.6.0-py3-none-any.whl | Python 3 | none | any | Details for midpoint_cli-1.6.0-py3-none-any.whl |
Total release size: 264.0 kB
Release files / midpoint_cli-1.6.0.tar.gz
| Download URL | midpoint_cli-1.6.0.tar.gz |
|---|---|
| Size | 129.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d8f54b94cff59b2163c3face233d56bb44397f80502fa2b883d44892703d084f
|
|
BLAKE2b-256 checksum How to use checksums |
7f77b17c68f1f684ebd5d5b0d6ce04d46ef86088866558be055447a222cb930e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / midpoint_cli-1.6.0-py3-none-any.whl
| Download URL | midpoint_cli-1.6.0-py3-none-any.whl |
|---|---|
| Size | 134.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e42c8573ba541dff48e0f1b09a3f5908a7fd0b7e6f8ea0269f5f09d8ce9ec537
|
|
BLAKE2b-256 checksum How to use checksums |
6b02f1b74e96b459190dd2f47c465891d1da907046809ce5e9c232766892c619
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for midpoint-cli 1.6.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.