opensearchcli 0.2.7__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/PKG-INFO +2 -1
  2. opensearchcli-0.3.0/README.md +130 -0
  3. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/pyproject.toml +7 -2
  4. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/cli.py +56 -43
  5. opensearchcli-0.3.0/src/opensearchcli/client.py +85 -0
  6. opensearchcli-0.3.0/src/opensearchcli/commands/config.py +132 -0
  7. opensearchcli-0.3.0/src/opensearchcli/config.py +187 -0
  8. opensearchcli-0.3.0/src/opensearchcli/oidc.py +280 -0
  9. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli.egg-info/PKG-INFO +2 -1
  10. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli.egg-info/SOURCES.txt +9 -1
  11. opensearchcli-0.3.0/src/opensearchcli.egg-info/entry_points.txt +2 -0
  12. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli.egg-info/requires.txt +1 -0
  13. opensearchcli-0.3.0/tests/test_cli_errors.py +61 -0
  14. opensearchcli-0.3.0/tests/test_client.py +90 -0
  15. opensearchcli-0.3.0/tests/test_config.py +259 -0
  16. opensearchcli-0.3.0/tests/test_config_commands.py +320 -0
  17. opensearchcli-0.3.0/tests/test_oidc.py +362 -0
  18. opensearchcli-0.2.7/README.md +0 -86
  19. opensearchcli-0.2.7/src/opensearchcli/commands/config.py +0 -178
  20. opensearchcli-0.2.7/src/opensearchcli.egg-info/entry_points.txt +0 -2
  21. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/setup.cfg +0 -0
  22. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/__init__.py +0 -0
  23. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/__init__.py +0 -0
  24. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/cluster.py +0 -0
  25. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/cluster_settings.py +0 -0
  26. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/commands.py +0 -0
  27. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/exceptions.py +0 -0
  28. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/helpers.py +0 -0
  29. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/index.py +0 -0
  30. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/index_settings.py +0 -0
  31. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/raw.py +0 -0
  32. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli/commands/snapshot.py +0 -0
  33. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli.egg-info/dependency_links.txt +0 -0
  34. {opensearchcli-0.2.7 → opensearchcli-0.3.0}/src/opensearchcli.egg-info/top_level.txt +0 -0
@@ -1,8 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensearchcli
3
- Version: 0.2.7
3
+ Version: 0.3.0
4
4
  Summary: A CLI tool for OpenSearch
5
5
  Requires-Python: <4,>=3.10
6
6
  Requires-Dist: typer>=0.20.0
7
7
  Requires-Dist: opensearch-py<4.0.0,>=3.1.0
8
8
  Requires-Dist: tomlkit>=0.13.3
9
+ Requires-Dist: httpx>=0.28.1
@@ -0,0 +1,130 @@
1
+ # OpenSearch CLI
2
+
3
+ OpenSearch CLI is a command-line tool to manage and interact with OpenSearch clusters. It provides commands for cluster management, snapshots, raw API calls, and more, all from your terminal.
4
+
5
+ ## Features
6
+
7
+ - Manage OpenSearch clusters (health, settings, allocation, etc.)
8
+ - Run raw OpenSearch API calls
9
+ - Manage snapshots
10
+ - Profile-based configuration
11
+
12
+ ## Requirements
13
+
14
+ - Python 3.10+
15
+
16
+ ## Installation
17
+
18
+ Install:
19
+
20
+ ```bash
21
+ uv tool install opensearchcli
22
+ ```
23
+
24
+ or upgrade:
25
+
26
+ ```bash
27
+ uv tool upgrade opensearchcli
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ Run the CLI:
33
+
34
+ ```sh
35
+ opensearchcli --help
36
+ ```
37
+
38
+ Example: Check cluster health
39
+
40
+ ```sh
41
+ opensearchcli cluster health
42
+ ```
43
+
44
+ ## Configuration
45
+
46
+ The CLI uses a config file (default: `~/.config/opensearch-cli/config.toml`) to store connection profiles. You can specify a profile with `--profile` or the `OPENSEARCH_PROFILE` environment variable.
47
+
48
+ Example config file:
49
+
50
+ ```toml
51
+ [default]
52
+ domain = "localhost"
53
+ username = "admin"
54
+ password = "admin"
55
+ ```
56
+
57
+ ### OIDC login
58
+
59
+ Instead of a username and password, a profile can log in with any OIDC provider (e.g. Okta) using the
60
+ authorization code flow with PKCE. The CLI sends the access token as `Authorization: Bearer <token>`.
61
+
62
+ ```toml
63
+ [acc]
64
+ domain = "opensearch.example.com"
65
+ auth = "oidc"
66
+ oidc_issuer = "https://example.okta.com/oauth2/default"
67
+ oidc_client_id = "0oa..."
68
+ # Optional:
69
+ # oidc_scopes = "openid profile email groups offline_access"
70
+ # oidc_redirect_port = 8400
71
+ # Audience to request the access token for, sent as the `resource` parameter on the authorize,
72
+ # token and refresh requests. Unset sends no `resource`:
73
+ # oidc_resource = "opensearch.example.com"
74
+ ```
75
+
76
+ Or create it with:
77
+
78
+ ```sh
79
+ opensearchcli config add-profile --profile-name acc --domain opensearch.example.com \
80
+ --oidc-issuer https://example.okta.com/oauth2/default --oidc-client-id 0oa...
81
+ ```
82
+
83
+ Then log in (opens a browser) and use the profile as usual:
84
+
85
+ ```sh
86
+ opensearchcli --profile acc login
87
+ opensearchcli --profile acc cluster health
88
+ opensearchcli --profile acc logout
89
+ ```
90
+
91
+ Tokens are cached in `tokens/<profile>.json` next to the config file and refreshed automatically while the
92
+ refresh token is valid. Changing the profile's `oidc_issuer`, `oidc_client_id` or `oidc_resource` requires a
93
+ new `login`.
94
+
95
+ The OIDC client must be a public client (no secret) with PKCE, the authorization code and refresh token
96
+ grants, and `http://localhost:8400/callback` as redirect URI. OpenSearch must accept the provider's access
97
+ tokens through an `openid` auth domain, and the access token must carry the claims that domain reads (for
98
+ Okta: a `groups` claim with token type *Access Token*, which is separate from the ID token claim). Set
99
+ `oidc_scopes` if your provider has no `groups` scope.
100
+
101
+ ## Development
102
+
103
+ Clone the repository and install dependencies using [uv](https://github.com/astral-sh/uv):
104
+
105
+ ```sh
106
+ git clone <repo-url>
107
+ cd OpenSearch
108
+ uv sync
109
+ ```
110
+
111
+ Or, to run commands directly with uv (no manual activation needed):
112
+
113
+ ```sh
114
+ uv run opensearchcli --help
115
+ ```
116
+
117
+ ## Project Structure
118
+
119
+ - `src/opensearchcli/cli.py` — Main CLI entry point
120
+ - `src/opensearchcli/commands/` — Command modules (cluster, snapshot, etc.)
121
+
122
+ ## Dependencies
123
+
124
+ - [opensearch-py](https://pypi.org/project/opensearch-py/)
125
+ - [typer](https://pypi.org/project/typer/)
126
+ - [rich](https://pypi.org/project/rich/)
127
+
128
+ ## License
129
+
130
+ MIT (add your license here)
@@ -1,21 +1,26 @@
1
1
  [project]
2
2
  name = "opensearchcli"
3
3
  description = "A CLI tool for OpenSearch"
4
- version = "0.2.7"
4
+ version = "0.3.0"
5
5
  requires-python = " <4,>=3.10"
6
6
  dependencies = [
7
7
  "typer>=0.20.0",
8
8
  "opensearch-py (>=3.1.0,<4.0.0)",
9
9
  "tomlkit>=0.13.3",
10
+ "httpx>=0.28.1",
10
11
  ]
11
12
 
12
13
  [project.scripts]
13
- opensearchcli = "opensearchcli.cli:app"
14
+ opensearchcli = "opensearchcli.cli:main"
14
15
 
15
16
  [tool.uv]
16
17
  package = true
17
18
 
18
19
  [dependency-groups]
19
20
  dev = [
21
+ "pytest>=9.1.1",
20
22
  "ruff>=0.14.7",
21
23
  ]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
@@ -3,12 +3,14 @@ from typing import Annotated
3
3
 
4
4
  import typer
5
5
  from pathlib import Path
6
- from opensearchpy import OpenSearch
6
+ from opensearchpy.exceptions import ConnectionError, TransportError
7
7
  from rich.console import Console
8
- from opensearchcli.commands import cluster, config, snapshot, commands, raw, index
9
- import urllib3
8
+ from rich.markup import escape
9
+ from opensearchcli import config, oidc
10
+ from opensearchcli.client import OpenSearchCli
11
+ from opensearchcli.commands import cluster, snapshot, commands, raw, index
12
+ from opensearchcli.commands import config as config_cmd
10
13
 
11
- urllib3.disable_warnings()
12
14
 
13
15
  console = Console()
14
16
  app = typer.Typer(rich_markup_mode="rich", no_args_is_help=True)
@@ -26,7 +28,7 @@ app.add_typer(
26
28
  )
27
29
  app.add_typer(typer_instance=raw.app, name="raw", help="Make raw OpenSearch API calls")
28
30
  app.add_typer(
29
- typer_instance=config.app, name="config", help="Manage configuration profiles"
31
+ typer_instance=config_cmd.app, name="config", help="Manage configuration profiles"
30
32
  )
31
33
 
32
34
 
@@ -52,40 +54,29 @@ def version():
52
54
  console.print(f"Version: {version}")
53
55
 
54
56
 
55
- class OpenSearchCli:
56
- def __init__(
57
- self,
58
- config: config.Config,
59
- profile: config.ConfigProfile,
60
- config_file_path: str,
61
- json_output: bool = False,
62
- timeout: int = 30,
63
- ) -> None:
64
- self._opensearch: OpenSearch | None = None
65
- self.config = config
66
- self.profile = profile
67
- self.config_file_path = config_file_path
68
- self.timeout = timeout
69
- self.json_output = json_output
70
-
71
- @property
72
- def opensearch(self) -> OpenSearch:
73
- if self._opensearch is None:
74
- self._opensearch = OpenSearch(
75
- hosts=[
76
- {
77
- "host": self.profile.domain,
78
- "port": self.profile.port,
79
- }
80
- ],
81
- http_auth=(self.profile.username, self.profile.password),
82
- use_ssl=True,
83
- verify_certs=False,
84
- ssl_show_warn=False,
85
- timeout=self.timeout,
86
- headers={"Accept": "application/json"} if self.json_output else {},
87
- )
88
- return self._opensearch
57
+ @app.command(name="login")
58
+ def login(ctx: typer.Context) -> None:
59
+ """
60
+ Log in with OIDC for the selected profile
61
+ """
62
+ profile = ctx.obj.profile
63
+ if profile.auth != "oidc":
64
+ console.print(f"[red]Profile '{profile.profile_name}' does not use OIDC[/red]")
65
+ raise typer.Exit(code=1)
66
+ try:
67
+ oidc.login(settings=profile.oidc, token_file=ctx.obj.token_file)
68
+ except oidc.OidcError as error:
69
+ console.print(f"[red]{escape(str(error))}[/red]")
70
+ raise typer.Exit(code=1)
71
+ console.print(f"[green]✓ Logged in for profile '{profile.profile_name}'[/green]")
72
+
73
+
74
+ @app.command(name="logout")
75
+ def logout(ctx: typer.Context) -> None:
76
+ """
77
+ Remove the cached OIDC tokens for the selected profile
78
+ """
79
+ oidc.logout(token_file=ctx.obj.token_file)
89
80
 
90
81
 
91
82
  @app.callback()
@@ -108,14 +99,15 @@ def common(
108
99
 
109
100
  try:
110
101
  _config = config.read_config(config_file=config_file)
111
- _profile = _config.find_profile_by_name(profile_name=profile)
112
102
  except Exception as ex:
113
103
  console.log(f"Error while reading config {config_file}:", ex, style="red")
114
- exit(1)
104
+ raise typer.Exit(code=1)
115
105
 
106
+ # The profile is resolved lazily by OpenSearchCli, so commands that do not
107
+ # talk to a cluster (config add-profile, list, version) work without one.
116
108
  ctx.obj = OpenSearchCli(
117
109
  config=_config,
118
- profile=_profile,
110
+ profile_name=profile,
119
111
  config_file_path=config_file,
120
112
  json_output=json_output,
121
113
  timeout=timeout,
@@ -123,5 +115,26 @@ def common(
123
115
  ctx.meta["json_output"] = json_output
124
116
 
125
117
 
118
+ def _describe_transport_error(error: TransportError) -> str:
119
+ if isinstance(error, ConnectionError):
120
+ return f"Connection failed: {error.error}"
121
+ if isinstance(error.info, dict) and isinstance(error.info.get("error"), dict):
122
+ reason = error.info["error"].get("reason")
123
+ if reason:
124
+ return f"{error.status_code} {error.error}: {reason}"
125
+ return f"{error.status_code} {error.error}"
126
+
127
+
128
+ def main() -> None:
129
+ try:
130
+ app()
131
+ except config.ProfileNotFound as error:
132
+ console.print(f"[red]Error:[/red] {error}")
133
+ raise SystemExit(1)
134
+ except TransportError as error:
135
+ console.print(f"[red]Error:[/red] {escape(_describe_transport_error(error))}")
136
+ raise SystemExit(1)
137
+
138
+
126
139
  if __name__ == "__main__":
127
- app()
140
+ main()
@@ -0,0 +1,85 @@
1
+ from pathlib import Path
2
+
3
+ import typer
4
+ from opensearchpy import OpenSearch
5
+ from rich.console import Console
6
+ from rich.markup import escape
7
+
8
+ from opensearchcli import oidc
9
+ from opensearchcli.config import Config, ConfigProfile
10
+
11
+ console = Console()
12
+
13
+
14
+ class OpenSearchCli:
15
+ def __init__(
16
+ self,
17
+ config: Config,
18
+ profile_name: str,
19
+ config_file_path: str,
20
+ json_output: bool = False,
21
+ timeout: int = 30,
22
+ ) -> None:
23
+ self._opensearch: OpenSearch | None = None
24
+ self._profile: ConfigProfile | None = None
25
+ self.config = config
26
+ self.profile_name = profile_name
27
+ self.config_file_path = config_file_path
28
+ self.timeout = timeout
29
+ self.json_output = json_output
30
+
31
+ @property
32
+ def profile(self) -> ConfigProfile:
33
+ """Resolve the selected profile, raising ProfileNotFound if it is absent.
34
+
35
+ Resolution is deferred so commands that need no profile still run.
36
+ """
37
+ if self._profile is None:
38
+ self._profile = self.config.find_profile_by_name(
39
+ profile_name=self.profile_name
40
+ )
41
+ return self._profile
42
+
43
+ @property
44
+ def token_file(self) -> Path:
45
+ return (
46
+ Path(self.config_file_path).parent / "tokens" / f"{self.profile_name}.json"
47
+ )
48
+
49
+ @property
50
+ def opensearch(self) -> OpenSearch:
51
+ if self._opensearch is None:
52
+ headers = {"Accept": "application/json"} if self.json_output else {}
53
+ http_auth = None
54
+ if self.profile.auth == "oidc":
55
+ headers["Authorization"] = f"Bearer {self._oidc_access_token()}"
56
+ else:
57
+ http_auth = (self.profile.username, self.profile.password)
58
+ self._opensearch = OpenSearch(
59
+ hosts=[
60
+ {
61
+ "host": self.profile.domain,
62
+ "port": self.profile.port,
63
+ }
64
+ ],
65
+ http_auth=http_auth,
66
+ use_ssl=True,
67
+ verify_certs=True,
68
+ timeout=self.timeout,
69
+ headers=headers,
70
+ )
71
+ return self._opensearch
72
+
73
+ def _oidc_access_token(self) -> str:
74
+ try:
75
+ return oidc.access_token(
76
+ settings=self.profile.oidc, token_file=self.token_file
77
+ )
78
+ except oidc.LoginRequired as error:
79
+ console.print(
80
+ f"[red]{escape(str(error))}. Run: opensearchcli --profile {self.profile_name} login[/red]"
81
+ )
82
+ raise typer.Exit(code=1)
83
+ except oidc.OidcError as error:
84
+ console.print(f"[red]{escape(str(error))}[/red]")
85
+ raise typer.Exit(code=1)
@@ -0,0 +1,132 @@
1
+ from typing import Annotated, Sequence
2
+
3
+ import typer
4
+ from rich.console import Console
5
+ from rich.table import Table
6
+
7
+ from opensearchcli.config import ConfigProfile
8
+
9
+ app = typer.Typer(
10
+ rich_markup_mode="rich",
11
+ no_args_is_help=True,
12
+ help="Manage configuration profiles",
13
+ )
14
+ console = Console()
15
+
16
+
17
+ def _get_profiles_table(profiles: Sequence[ConfigProfile]) -> Table:
18
+ table = Table(show_header=True, header_style="cyan")
19
+ table.add_column(header="Profile Name")
20
+ table.add_column(header="Domain")
21
+ table.add_column(header="Auth")
22
+ table.add_column(header="Username")
23
+ table.add_column(header="Password")
24
+ for profile in profiles:
25
+ table.add_row(
26
+ f"{profile.profile_name}",
27
+ f"{profile.domain}",
28
+ f"{profile.auth}",
29
+ f"{profile.username}",
30
+ f"{'*' * len(profile.password) if profile.password else ''}",
31
+ )
32
+ return table
33
+
34
+
35
+ @app.command(name="list")
36
+ def list_profiles(ctx: typer.Context) -> None:
37
+ """List all configuration profiles.
38
+
39
+ Display a table showing all configured profiles with their details.
40
+ """
41
+ console.print(_get_profiles_table(profiles=ctx.obj.config.profiles))
42
+
43
+
44
+ @app.command(
45
+ name="show",
46
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
47
+ )
48
+ def show_profile(ctx: typer.Context, profile_name: str = "default") -> None:
49
+ """Show details for a specific configuration profile.
50
+
51
+ Display the profile information for the given profile name.
52
+
53
+ Args:
54
+ profile_name: Name of the profile to display (default: "default")
55
+ """
56
+ _profile = ctx.obj.config.find_profile_by_name(profile_name)
57
+ if not _profile:
58
+ typer.echo(message=f"No profile found for: {profile_name}")
59
+ return None
60
+ console.print(_get_profiles_table(profiles=[_profile]))
61
+
62
+
63
+ def _oidc_profile_data(
64
+ domain: str, issuer: str, client_id: str | None, resource: str | None
65
+ ) -> dict:
66
+ if not client_id:
67
+ console.print("[red]--oidc-client-id is required with --oidc-issuer[/red]")
68
+ raise typer.Exit(code=1)
69
+ data = {
70
+ "domain": domain,
71
+ "auth": "oidc",
72
+ "oidc_issuer": issuer,
73
+ "oidc_client_id": client_id,
74
+ }
75
+ if resource:
76
+ data["oidc_resource"] = resource
77
+ return data
78
+
79
+
80
+ def _basic_profile_data(domain: str, username: str, password: str | None) -> dict:
81
+ if password is None:
82
+ password = typer.prompt("Password", hide_input=True)
83
+ return {"domain": domain, "username": username, "password": password}
84
+
85
+
86
+ @app.command(name="add-profile")
87
+ def add_profile(
88
+ ctx: typer.Context,
89
+ profile_name: Annotated[str, typer.Option()],
90
+ domain: Annotated[str, typer.Option()],
91
+ username: Annotated[str | None, typer.Option()] = None,
92
+ password: Annotated[
93
+ str | None, typer.Option(help="Prompted for when omitted", hide_input=True)
94
+ ] = None,
95
+ oidc_issuer: Annotated[
96
+ str | None, typer.Option(help="OIDC issuer URL, enables OIDC login")
97
+ ] = None,
98
+ oidc_client_id: Annotated[str | None, typer.Option()] = None,
99
+ oidc_resource: Annotated[
100
+ str | None,
101
+ typer.Option(help="Audience to request the access token for (resource)"),
102
+ ] = None,
103
+ overwrite: Annotated[bool, typer.Option()] = False,
104
+ ) -> None:
105
+ """Create a new configuration file with default profile.
106
+
107
+ Use --username for basic auth (prompts for the password), or
108
+ --oidc-issuer and --oidc-client-id for OIDC login.
109
+ """
110
+ _config = ctx.obj.config
111
+ config_file = ctx.obj.config_file_path
112
+
113
+ if _config.has_profile(profile_name) and not overwrite:
114
+ console.print(
115
+ f"[red]Profile '{profile_name}' already exists in {config_file}. Use --overwrite to replace it.[/red]"
116
+ )
117
+ raise typer.Exit(code=1)
118
+
119
+ if oidc_issuer:
120
+ data = _oidc_profile_data(domain, oidc_issuer, oidc_client_id, oidc_resource)
121
+ elif username:
122
+ data = _basic_profile_data(domain, username, password)
123
+ else:
124
+ console.print("[red]Provide either --username or --oidc-issuer[/red]")
125
+ raise typer.Exit(code=1)
126
+
127
+ _config.upsert_profile(ConfigProfile(profile_name=profile_name, data=data))
128
+ _config.save(config_file=config_file)
129
+
130
+ console.print(
131
+ f"[green]✓ Configuration created successfully at {config_file}[/green]"
132
+ )