
Cloud Manage Project
- 2.1k installs
- 546 repo stars
- Updated July 22, 2026
- elastic/agent-skills
Elastic Serverless project management.
About
The cloud-manage-project skill performs day-2 Elastic Cloud Serverless operations via Serverless REST API listing getting updating deleting resetting credentials resuming projects and loading saved credentials while resolving endpoints and scoped Elasticsearch API keys. Requires EC_API_KEY from cloud-setup with Admin or Editor for updates; 403 prompts permission verification. Manual fallback documents EC_API_KEY EC_BASE_URL in dotenv without pasting secrets in chat. Python 3.8 plus network to api.elastic-cloud.com for API commands; load-credentials works locally. Use connecting to existing serverless projects rotating credentials or looking up project details after provisioning. Day-2 Serverless REST API operations. List update delete resume reset credentials. EC_API_KEY Admin or Editor for updates. load-credentials works without network. dotenv fallback without chat secrets. Elastic Serverless project management. Day-2 serverless operations.
- Day-2 Serverless REST API operations.
- List update delete resume reset credentials.
- EC_API_KEY Admin or Editor for updates.
- load-credentials works without network.
- dotenv fallback without chat secrets.
Cloud Manage Project by the numbers
- 2,137 all-time installs (skills.sh)
- +166 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #177 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
cloud-manage-project capabilities & compatibility
- Capabilities
- project ops · credential reset
- Use cases
- devops
npx skills add https://github.com/elastic/agent-skills --skill cloud-manage-projectAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.1k |
|---|---|
| repo stars | ★ 546 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 22, 2026 |
| Repository | elastic/agent-skills ↗ |
Update serverless project credentials?
Manage Elastic Cloud Serverless projects: list update delete reset credentials resume via REST API.
Who is it for?
Teams managing Elastic Serverless.
Skip if: Self-hosted only.
When should I use this skill?
Day-2 serverless operations.
What you get
Connection details and API keys.
- .elastic-credentials file
- Serverless project IDs and endpoint URLs
Files
Manage Serverless Project
Perform day-2 operations on Elastic Cloud Serverless projects using the Serverless REST API.
Prerequisites and permissions
- Ensure
EC_API_KEYis configured. If not, runcloud-setupskill first. - Updating project settings requires Admin or Editor role on the target project.
- This skill does not perform a separate role pre-check. Attempt the requested operation and let the API enforce
authorization. If the API returns an authorization error (for example, 403 Forbidden), stop and ask the user to verify the provided API key permissions.
Manual setup fallback (when cloud-setup is unavailable)
If this skill is installed standalone and cloud-setup is not available, instruct the user to configure Cloud environment variables manually before running commands. Never ask the user to paste API keys in chat.
| Variable | Required | Description |
|---|---|---|
EC_API_KEY | Yes | Elastic Cloud API key used for project management operations. |
EC_BASE_URL | No | Cloud API base URL (default: https://api.elastic-cloud.com). |
Note: If EC_API_KEY is missing, or the user does not have a Cloud API key yet, direct the user to generate oneat Elastic Cloud API keys, then configure it locally using the steps below.
Preferred method (agent-friendly): create a .env file in the project root:
EC_API_KEY=your-api-key
EC_BASE_URL=https://api.elastic-cloud.comAll cloud/* scripts auto-load .env from the working directory.
Alternative: export directly in the terminal:
export EC_API_KEY="<your-cloud-api-key>"
export EC_BASE_URL="https://api.elastic-cloud.com"Terminal exports may not be visible to sandboxed agents running in separate shell sessions, so prefer .env when using an agent.
Critical principles
- Never display secrets in chat. Do not echo, log, or repeat API keys, passwords, or credentials in conversation
messages or agent thinking. Direct the user to the .elastic-credentials file instead. The admin password must never appear in chat history, thinking traces, or agent output — even when using it to create an API key, pass it directly via shell variable substitution without echoing.
- Confirm before destructive actions. Always ask the user to confirm before deleting a project or resetting
credentials.
- Credentials are saved to file. After a credential reset, the script writes the new password to
.elastic-credentials automatically. The password is redacted from stdout. Never read or display the contents of .elastic-credentials in chat.
- Admin credentials are for API key creation only. The
adminpassword saved bycreate-projectand
reset-credentials exists solely to bootstrap a scoped API key — never use it for direct Elasticsearch operations. load-credentials excludes admin credentials by default; pass --include-admin only for key creation.
- Always prefer API keys. Do not proceed with Elasticsearch operations until an
ELASTICSEARCH_API_KEYis set. If
only admin credentials are available, create a scoped API key via elasticsearch-authn. If that skill is not installed, ask the user to install it or create the key manually in Kibana > Stack Management > API keys.
- Identify projects by type and ID. Every command requires both
--typeand--id(exceptlist, which only needs
--type).
- Two kinds of API keys. This skill uses the Cloud API key (
EC_API_KEY) for project management operations
(list, get, update, delete). Elasticsearch operations require a separate Elasticsearch API key (ELASTICSEARCH_API_KEY) that authenticates against the project's Elasticsearch endpoint. Do not confuse the two.
Workflow: Connect to an existing project
Use this workflow when the user asks to query or manage a project the agent did not create in the current session. It resolves the project, saves its endpoints, and ensures working Elasticsearch credentials before proceeding.
This workflow only applies to Elastic Cloud Serverless projects. If the user's Elasticsearch instance is self-managed or Elastic Cloud Hosted, this skill does not apply — skip it and proceed with the relevant skill directly. If unsure, ask the user: "Is your Elasticsearch instance an Elastic Cloud Serverless project?"
Connect to Existing Project:
- [ ] Step 1: Resolve the project
- [ ] Step 2: Get project details and load credentials
- [ ] Step 3: Acquire Elasticsearch credentialsStep 1: Resolve the project
Ask the user for the project name if not already provided. Infer the project type from the user's request:
| User says | --type |
|---|---|
| "search project", "elasticsearch project", vector search | elasticsearch |
| "observability project", "o11y", logs, metrics, traces, APM | observability |
| "security project", "SIEM", detections, endpoint protection | security |
If the type is ambiguous, list all three types to find the project.
python3 skills/cloud/manage-project/scripts/manage-project.py list \
--type elasticsearchMatch the user's reference (name, partial name, or alias) against the list results. If multiple projects match or none match, present the candidates and ask the user to pick.
Step 2: Get project details and load credentials
Once a single project is identified, check whether .elastic-credentials already has entries for this project (from a previous session). If so, load them with load-credentials:
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--name "<project-name>")This sets all saved environment variables for the project — endpoints and any previously created Elasticsearch API keys — in a single command. Admin credentials (ELASTICSEARCH_USERNAME/ELASTICSEARCH_PASSWORD) are intentionally excluded. Later sections for the same project automatically overwrite earlier values, so the most recent credentials always win.
If load-credentials reports no matching entries, fetch the project details from the API and export endpoints manually:
python3 skills/cloud/manage-project/scripts/manage-project.py get \
--type elasticsearch \
--id <project-id>Then export the endpoint URLs from the response. The available endpoints depend on the project type.
All project types:
export ELASTICSEARCH_URL="<elasticsearch_endpoint>"
export KIBANA_URL="<kibana_endpoint>"Observability projects (additional):
export APM_URL="<apm_endpoint>"
export INGEST_URL="<ingest_endpoint>"Security projects (additional):
export INGEST_URL="<ingest_endpoint>"Step 3: Acquire Elasticsearch credentials
If load-credentials set ELASTICSEARCH_API_KEY, verify the credentials work:
curl -H "Authorization: ApiKey ${ELASTICSEARCH_API_KEY}" \
"${ELASTICSEARCH_URL}/_security/_authenticate"Confirm the response contains a valid username and "authentication_type": "api_key" before proceeding. If verification succeeds, skip the rest of this step.
If no credentials were loaded, or verification fails, ask the user: "Do you have an existing Elasticsearch API key for this project?"
If yes — have the user add it to .elastic-credentials (see "Credential file format"). Do not accept keys in chat. Reload and verify:
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--name "<project-name>")
curl -H "Authorization: ApiKey ${ELASTICSEARCH_API_KEY}" \
"${ELASTICSEARCH_URL}/_security/_authenticate"If no — follow this recovery path:
1. Confirm with the user, then reset the admin bootstrap credentials:
python3 skills/cloud/manage-project/scripts/manage-project.py reset-credentials \
--type elasticsearch \
--id <project-id>The new password is saved to .elastic-credentials with the project name in the header. Direct the user to that file — do not display its contents.
2. Load credentials with `--include-admin` so the admin password is available for API key creation:
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--name "<project-name>" --include-admin)Use the admin credentials to create a scoped Elasticsearch API key via elasticsearch-authn if available. If that skill is not installed, ask the user to install it or create the key manually in Kibana > Stack Management > API keys. Scope the key to only the privileges the user needs.
3. After creating the API key, save it to .elastic-credentials using the project-specific header format (see "Credential file format" below). Then reload without `--include-admin` to drop admin credentials from the environment and verify:
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--name "<project-name>")
curl -H "Authorization: ApiKey ${ELASTICSEARCH_API_KEY}" \
"${ELASTICSEARCH_URL}/_security/_authenticate"Confirm the response shows a valid username and "authentication_type": "api_key" before proceeding.
Credential file format
See references/credential-file-format.md for the full format specification.
Workflow: Load project credentials
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--name "<project-name>")Or by project ID:
eval $(python3 skills/cloud/manage-project/scripts/manage-project.py load-credentials \
--id <project-id>)Parses .elastic-credentials, merges all sections for the matching project, and prints export statements. Admin credentials (ELASTICSEARCH_USERNAME/ELASTICSEARCH_PASSWORD) are excluded by default — only endpoints and API keys are exported. Add --include-admin when you need admin credentials to create an API key.
Workflow: List projects
python3 skills/cloud/manage-project/scripts/manage-project.py list \
--type elasticsearchUse --type observability or --type security to list other project types.
Workflow: Get project details
python3 skills/cloud/manage-project/scripts/manage-project.py get \
--type elasticsearch \
--id <project-id>Workflow: Update a project
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type elasticsearch \
--id <project-id> \
--name "new-project-name"Only the fields provided are updated (PATCH semantics). Supported fields: --name, --alias, --tag, --search-power, --boost-window, --max-retention-days, --default-retention-days.
Alias
The alias is an RFC-1035 domain label (lowercase alphanumeric and hyphens, max 50 chars) that becomes part of the project's endpoint URLs. Changing the alias changes all endpoint URLs, which breaks existing clients pointing to the old URLs. Warn the user about this before applying.
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type elasticsearch \
--id <project-id> \
--alias "prod-search"Tags
Tags are key-value metadata pairs for team tracking, cost attribution, and organization. Pass --tag KEY:VALUE for each tag. Multiple tags can be set in a single update.
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type elasticsearch \
--id <project-id> \
--tag env:prod \
--tag team:searchTags are sent as metadata.tags in the API request. Setting tags replaces all existing tags on the project — include any existing tags the user wants to keep.
Elasticsearch search_lake settings
For Elasticsearch projects, two fields control query performance and data caching in the Search AI Lake. Ingested data is stored in cost-efficient general storage. A cache layer on top provides faster search speed for recent and frequently queried data — this cached data is considered search-ready.
| Flag | Range | Description |
|---|---|---|
--search-power | 28–3000 | Query performance level. Higher values improve performance but increase cost |
--boost-window | 1–180 | Days of data eligible for boosted caching (default: 7) |
Search Power
Search Power controls the speed of searches by provisioning more or fewer query resources. Common presets (matching the Cloud UI):
| Value | Preset | Behavior |
|---|---|---|
| 28 | On-demand | Autoscales with lower baseline. More variable latency, reduced max throughput |
| 100 | Performant | Consistently low latency, autoscales for moderately high throughput |
| 250 | High availability | Optimized for high-throughput scenarios, maintains low latency at high volumes |
When the user asks for a preset by name, map it to the corresponding value. Custom values within 28–3000 are also valid.
Warn the user about cost implications before updating `search_power`. Higher values increase VCU consumption and may result in higher bills. Confirm the new value with the user before applying.
Search Boost Window
Non-time-series data is always search-ready. The boost window determines how much time-series data (documents with a @timestamp field) is also kept in the fast cache layer. Increasing the window means a larger portion of time-series data becomes search-ready, which improves query speed for recent data but increases the search-ready data volume.
Security data retention settings
For security projects, two fields control how long data is retained in the Search AI Lake. Retention is configured per data stream, but these project-level settings enforce global boundaries.
| Flag | Unit | Description |
|---|---|---|
--max-retention-days | days | Maximum retention period for any data stream in the project |
--default-retention-days | days | Default retention applied to data streams without a custom one |
- Maximum retention — enforces an upper bound across all data streams. When lowered, it replaces the retention for
any stream that currently has a longer period. Data older than the new maximum is permanently deleted.
- Default retention — automatically applied to data streams that do not have a custom retention period set. Does not
affect streams with an existing custom retention.
Warn the user before reducing `max-retention-days`. Lowering the maximum permanently deletes data older than the new limit. Confirm the new value with the user before applying.
Workflow: Reset project credentials
Always confirm with the user before resetting.
python3 skills/cloud/manage-project/scripts/manage-project.py reset-credentials \
--type elasticsearch \
--id <project-id>The new password is saved to .elastic-credentials automatically. Tell the user to open that file — do not display its contents in chat.
Workflow: Delete a project
Always confirm with the user before deleting.
python3 skills/cloud/manage-project/scripts/manage-project.py delete \
--type elasticsearch \
--id <project-id>Workflow: Resume a suspended project
Projects can be automatically suspended after their trial period expires. Resume with:
python3 skills/cloud/manage-project/scripts/manage-project.py resume \
--type elasticsearch \
--id <project-id>After resuming, poll the project status until the phase changes from initializing to initialized.
Examples
List all security projects
python3 skills/cloud/manage-project/scripts/manage-project.py list --type securityUpdate search power on an Elasticsearch project
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type elasticsearch \
--id abc123def456abc123def456abc12345 \
--search-power 500Set data retention on a security project
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type security \
--id abc123def456abc123def456abc12345 \
--max-retention-days 396 \
--default-retention-days 396Change project alias
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type elasticsearch \
--id abc123def456abc123def456abc12345 \
--alias "prod-search"Tag a project for cost tracking
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type observability \
--id abc123def456abc123def456abc12345 \
--tag env:prod \
--tag team:platformRename an observability project
python3 skills/cloud/manage-project/scripts/manage-project.py update \
--type observability \
--id abc123def456abc123def456abc12345 \
--name "production-logs"Connect to an existing project (credentials on file)
User: I want to run a query against my search project "prod-search"
Agent: Let me find that project.
[runs: list --type elasticsearch]
I found "prod-search" (ID: abc123...). Loading saved credentials...
[runs: eval $(load-credentials --name prod-search)]
Credentials loaded. Verifying...
[runs: curl -H "Authorization: ApiKey ..." "${ELASTICSEARCH_URL}/_security/_authenticate"]
Verified — authenticated as user "my-service" via API key. You're all set.Connect to a project (no saved credentials)
User: let's ingest some logs into my o11y project "siem-prod"
Agent: Let me find that project.
[runs: list --type observability]
Found "siem-prod" (ID: def456...). No saved credentials found for this project.
[runs: get --type observability --id def456...]
Endpoints set. Since there are no Elasticsearch credentials on file, I can reset the
admin bootstrap password to get initial access. Shall I proceed?
User: yes
Agent: [runs: reset-credentials --type observability --id def456...]
Credentials saved to .elastic-credentials — open that file to retrieve the password.
[runs: eval $(load-credentials --name siem-prod --include-admin)]
Admin credentials loaded for API key creation. Creating a scoped Elasticsearch API key
now — what access does it need?
User: read-only on logs-*
Agent: [creates scoped API key via elasticsearch-authn using admin credentials]
[appends API key to .elastic-credentials with project header]
[runs: eval $(load-credentials --name siem-prod)]
[verifies against ELASTICSEARCH_URL]
API key created and verified. Admin credentials removed from environment.Delete a project after confirmation
User: delete my elasticsearch project abc123...
Agent: Are you sure you want to delete project abc123...? This cannot be undone.
User: yespython3 skills/cloud/manage-project/scripts/manage-project.py delete \
--type elasticsearch \
--id abc123def456abc123def456abc12345Guidelines
- Run the
cloud-setupskill first ifEC_API_KEYis not set. - Use the
cloud-create-projectskill to create new projects — this skill handles existing projects only. - When the user refers to a project the agent did not create, follow the "Connect to an existing project" workflow.
- Deletion is permanent. Always confirm with the user before proceeding.
- After resetting credentials, remind the user to update any stored passwords or environment variables.
- Warn about cost implications before increasing
search_power. Confirm the new value with the user first. - Warn about data loss before reducing
max-retention-days. Data older than the new maximum is permanently deleted. - Warn users that changing a project alias changes all endpoint URLs, which breaks existing clients.
- Setting tags replaces all existing tags. Retrieve current tags with
getfirst and include any the user wants to
keep.
Script reference
| Command | Description |
|---|---|
list | List projects by type |
get | Get project details by ID |
update | Update project name, alias, tags, or search_lake settings |
reset-credentials | Reset project credentials (new password) |
delete | Delete a project |
resume | Resume a suspended project |
load-credentials | Load a project's saved credentials from .elastic-credentials |
| Flag | Commands | Description |
|---|---|---|
--type | list, get, update, reset-credentials, delete, resume | Project type: elasticsearch, observability, security |
--id | get, update, reset-credentials, delete, resume, load-credentials | Project ID |
--name | update, load-credentials | Project name (update: new name; load-credentials: lookup) |
--alias | update | New project alias |
--tag | update | Tag as KEY:VALUE (repeatable, replaces all tags) |
--search-power | update | Search power 28–3000 (elasticsearch only) |
--boost-window | update | Boost window 1–180 days (elasticsearch only) |
--max-retention-days | update | Max data retention in days (security only) |
--default-retention-days | update | Default data retention in days (security only) |
--include-admin | load-credentials | Include admin username/password (API key bootstrapping only) |
--wait-seconds | reset-credentials | Seconds to wait for credential propagation (0 to skip) |
Environment variables
| Variable | Required | Description |
|---|---|---|
EC_API_KEY | Yes | Elastic Cloud API key (project management operations) |
EC_BASE_URL | No | Cloud API base URL (default: https://api.elastic-cloud.com) |
ELASTICSEARCH_URL | Output | Elasticsearch URL (set after resolving a project for downstream skills) |
KIBANA_URL | Output | Kibana URL (set after resolving a project for downstream skills) |
APM_URL | Output | APM endpoint (observability projects only) |
INGEST_URL | Output | OTLP ingest endpoint (observability and security projects) |
ELASTICSEARCH_API_KEY | Output | Elasticsearch API key (for stack-level operations) |
Additional resources
- For full API details, request/response schemas, and project-type options, see the
- For official documentation on Search AI Lake settings, data retention, and project features, see
Credential file format
Each section in .elastic-credentials starts with a header containing the project name and project ID. The load-credentials command uses these headers to retrieve credentials for a specific project.
Project section (written automatically by create-project and reset-credentials):
# Project: <project-name> | id=<project-id> | <timestamp>
ELASTICSEARCH_URL=https://...
KIBANA_URL=https://...
ELASTICSEARCH_USERNAME=admin
ELASTICSEARCH_PASSWORD=<password>API key section (append when creating Elasticsearch API keys):
# API Key: <key-name> | project=<project-name> | id=<project-id> | <details>
ELASTICSEARCH_API_KEY=<base64-encoded-key>Sections for the same project are merged by load-credentials. Later entries overwrite earlier ones. ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD are saved to the file but not exported by load-credentials unless --include-admin is passed. Use --include-admin only when creating an API key, then reload without it.
#!/usr/bin/env python3
"""Manage existing Elastic Cloud Serverless projects via the Serverless REST API.
Usage:
python3 manage-project.py <command> [options]
Commands:
list List projects of a given type
get Get project details
update Update project name, alias, tags, or search_lake settings
reset-credentials Reset project credentials
delete Delete a project
resume Resume a suspended project
load-credentials Load project credentials from .elastic-credentials
Commands that call the Cloud API require the EC_API_KEY environment variable.
"""
import argparse
import copy
import json
import os
import re
import shlex
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
def load_dotenv(path=".env"):
"""Load KEY=VALUE pairs from a .env file into os.environ (no overwrite)."""
try:
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip("'\""))
except FileNotFoundError:
pass
load_dotenv()
BASE_URL = os.environ.get("EC_BASE_URL", "https://api.elastic-cloud.com")
API_PREFIX = "/api/v1/serverless"
VALID_TYPES = ("elasticsearch", "observability", "security")
def get_api_key():
key = os.environ.get("EC_API_KEY")
if not key:
print("Error: EC_API_KEY environment variable is not set.", file=sys.stderr)
print("Run the cloud-setup skill to configure authentication.", file=sys.stderr)
sys.exit(1)
return key
def api_request(method, path, body=None):
url = f"{BASE_URL}{API_PREFIX}{path}"
headers = {
"Authorization": f"ApiKey {get_api_key()}",
"Content-Type": "application/json",
"User-Agent": "elastic-agentic",
}
data = json.dumps(body).encode() if body else None
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
raw = resp.read().decode()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
error_body = e.read().decode()
try:
error_json = json.loads(error_body)
print(json.dumps(error_json, indent=2), file=sys.stderr)
except json.JSONDecodeError:
print(error_body, file=sys.stderr)
print(f"\nHTTP {e.code}: {e.reason}", file=sys.stderr)
sys.exit(1)
except urllib.error.URLError as e:
print(f"Error: unable to reach {url}: {e.reason}", file=sys.stderr)
sys.exit(1)
def cmd_list(args):
result = api_request("GET", f"/projects/{args.type}")
items = result.get("items", [])
if not items:
print("No projects found.")
return
print(json.dumps(items, indent=2))
def cmd_get(args):
result = api_request("GET", f"/projects/{args.type}/{args.id}")
print(json.dumps(result, indent=2))
def cmd_update(args):
body = {}
if args.name:
body["name"] = args.name
if args.alias:
body["alias"] = args.alias
if args.tag:
tags = {}
for t in args.tag:
key, _, value = t.partition(":")
if not key or not value:
print(f"Error: invalid tag format '{t}', expected KEY:VALUE", file=sys.stderr)
sys.exit(1)
tags[key] = value
body["metadata"] = {"tags": tags}
search_lake = {}
if args.search_power is not None:
if args.type != "elasticsearch":
print("Error: --search-power is only supported for elasticsearch projects.", file=sys.stderr)
sys.exit(1)
search_lake["search_power"] = args.search_power
if args.boost_window is not None:
if args.type != "elasticsearch":
print("Error: --boost-window is only supported for elasticsearch projects.", file=sys.stderr)
sys.exit(1)
search_lake["boost_window"] = args.boost_window
data_retention = {}
if args.max_retention_days is not None:
if args.type != "security":
print("Error: --max-retention-days is only supported for security projects.", file=sys.stderr)
sys.exit(1)
data_retention["max_retention_days"] = args.max_retention_days
if args.default_retention_days is not None:
if args.type != "security":
print("Error: --default-retention-days is only supported for security projects.", file=sys.stderr)
sys.exit(1)
data_retention["default_retention_days"] = args.default_retention_days
if data_retention:
search_lake["data_retention"] = data_retention
if search_lake:
body["search_lake"] = search_lake
if not body:
print("Error: provide at least one field to update.", file=sys.stderr)
sys.exit(1)
result = api_request("PATCH", f"/projects/{args.type}/{args.id}", body)
print(json.dumps(result, indent=2))
print("\nProject updated.", file=sys.stderr)
def save_credentials(project_id, project_name, credentials):
"""Append credentials to .elastic-credentials in the working directory."""
creds_file = os.path.join(os.getcwd(), ".elastic-credentials")
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
fd = os.open(creds_file, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
os.fchmod(fd, 0o600)
with os.fdopen(fd, "a") as f:
f.write(f"# Project: {project_name} | id={project_id} | reset {timestamp}\n")
f.write(f"ELASTICSEARCH_USERNAME={credentials.get('username', '')}\n")
f.write(f"ELASTICSEARCH_PASSWORD={credentials.get('password', '')}\n\n")
return creds_file
_PROJECT_HEADER_RE = re.compile(
r"^#\s*Project:\s*(?P<name>[^|]+?)\s*\|\s*id=(?P<id>[a-f0-9]+)"
)
_API_KEY_HEADER_RE = re.compile(
r"^#\s*API Key:\s*[^|]+?\s*\|\s*project=(?P<name>[^|]+?)\s*\|\s*id=(?P<id>[a-f0-9]+)"
)
def parse_credentials_file(path=None):
"""Parse .elastic-credentials into per-project merged credential dicts.
Returns a dict keyed by (name, project_id) with merged KEY=VALUE pairs.
Later sections for the same project overwrite earlier values so the most
recent credentials win.
"""
if path is None:
path = os.path.join(os.getcwd(), ".elastic-credentials")
projects = {}
current_key = None
try:
with open(path) as f:
for line in f:
line = line.rstrip("\n")
m = _PROJECT_HEADER_RE.match(line) or _API_KEY_HEADER_RE.match(line)
if m:
current_key = (m.group("name").strip(), m.group("id"))
projects.setdefault(current_key, {})
continue
if not line or line.startswith("#"):
continue
if current_key and "=" in line:
key, _, value = line.partition("=")
projects[current_key][key.strip()] = value.strip()
except FileNotFoundError:
pass
return projects
def cmd_load_credentials(args):
"""Print export statements for a specific project's credentials."""
projects = parse_credentials_file()
if not projects:
print("Error: .elastic-credentials not found or empty.", file=sys.stderr)
sys.exit(1)
match_name = args.name.lower() if args.name else None
match_id = args.id.lower() if args.id else None
matched = []
for (name, pid), env_vars in projects.items():
if match_id and pid.lower() == match_id:
matched.append(((name, pid), env_vars))
elif match_name and name.lower() == match_name:
matched.append(((name, pid), env_vars))
if not matched:
print(
f"Error: no credentials found for "
f"{'name=' + args.name if args.name else 'id=' + args.id}.",
file=sys.stderr,
)
available = sorted({name for (name, _) in projects})
if available:
print(f"Available projects: {', '.join(available)}", file=sys.stderr)
sys.exit(1)
unique_ids = {pid for (_, pid), _ in matched}
if len(unique_ids) > 1:
print(
"Error: multiple projects match that name. Use --id to disambiguate:",
file=sys.stderr,
)
for (name, pid), _ in matched:
print(f" {name} (id={pid})", file=sys.stderr)
sys.exit(1)
_ADMIN_KEYS = {"ELASTICSEARCH_USERNAME", "ELASTICSEARCH_PASSWORD"}
include_admin = getattr(args, "include_admin", False)
merged = {}
for _, env_vars in matched:
merged.update(env_vars)
_SAFE_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
for key, value in merged.items():
if not include_admin and key in _ADMIN_KEYS:
continue
if not _SAFE_KEY_RE.match(key):
print(f"Warning: skipping invalid variable name: {key!r}", file=sys.stderr)
continue
print(f"export {key}={shlex.quote(value)}")
def cmd_reset_credentials(args):
project = api_request("GET", f"/projects/{args.type}/{args.id}")
project_name = project.get("name", args.id)
result = api_request("POST", f"/projects/{args.type}/{args.id}/_reset-credentials")
nested = result.get("credentials")
if isinstance(nested, dict):
credentials = {
"username": nested.get("username", ""),
"password": nested.get("password", ""),
}
else:
credentials = {
"username": result.get("username", ""),
"password": result.get("password", ""),
}
creds_file = save_credentials(args.id, project_name, credentials)
redacted = copy.deepcopy(result)
if "password" in redacted:
redacted["password"] = "REDACTED — see .elastic-credentials"
if isinstance(redacted.get("credentials"), dict) and "password" in redacted["credentials"]:
redacted["credentials"]["password"] = "REDACTED — see .elastic-credentials"
print(json.dumps(redacted, indent=2))
print(f"\nCredentials saved to {creds_file} — do not display in chat.", file=sys.stderr)
if args.wait_seconds > 0:
print(f"Waiting {args.wait_seconds} seconds for credential propagation…", file=sys.stderr)
time.sleep(args.wait_seconds)
def cmd_delete(args):
api_request("DELETE", f"/projects/{args.type}/{args.id}")
print(f"Project {args.id} deletion scheduled.")
def cmd_resume(args):
api_request("POST", f"/projects/{args.type}/{args.id}/_resume")
print(f"Project {args.id} resumption scheduled.", file=sys.stderr)
print("Poll project status until phase changes to 'initialized'.", file=sys.stderr)
def main():
parser = argparse.ArgumentParser(
description="Manage existing Elastic Cloud Serverless projects"
)
subparsers = parser.add_subparsers(dest="command", required=True)
p_list = subparsers.add_parser("list", help="List projects")
p_list.add_argument("--type", required=True, choices=VALID_TYPES)
p_list.set_defaults(func=cmd_list)
p_get = subparsers.add_parser("get", help="Get project details")
p_get.add_argument("--type", required=True, choices=VALID_TYPES)
p_get.add_argument("--id", required=True, help="Project ID")
p_get.set_defaults(func=cmd_get)
p_update = subparsers.add_parser("update", help="Update a project")
p_update.add_argument("--type", required=True, choices=VALID_TYPES)
p_update.add_argument("--id", required=True, help="Project ID")
p_update.add_argument("--name", help="New project name")
p_update.add_argument("--alias", help="New project alias")
p_update.add_argument(
"--tag", action="append", metavar="KEY:VALUE",
help="Project tag (repeatable, for example --tag env:prod --tag team:search)",
)
p_update.add_argument(
"--search-power", type=int,
help="Search power (28=on-demand, 100=performant, 250=high-availability; range 28-3000, elasticsearch only)",
)
p_update.add_argument(
"--boost-window", type=int,
help="Boost window in days (1-180, elasticsearch only)",
)
p_update.add_argument(
"--max-retention-days", type=int,
help="Maximum data retention period in days (security only)",
)
p_update.add_argument(
"--default-retention-days", type=int,
help="Default data retention period in days (security only)",
)
p_update.set_defaults(func=cmd_update)
p_reset = subparsers.add_parser("reset-credentials", help="Reset credentials")
p_reset.add_argument("--type", required=True, choices=VALID_TYPES)
p_reset.add_argument("--id", required=True, help="Project ID")
p_reset.add_argument(
"--wait-seconds", type=int, default=30,
help="Seconds to wait for credential propagation (0 to skip, default: 30)",
)
p_reset.set_defaults(func=cmd_reset_credentials)
p_delete = subparsers.add_parser("delete", help="Delete a project")
p_delete.add_argument("--type", required=True, choices=VALID_TYPES)
p_delete.add_argument("--id", required=True, help="Project ID")
p_delete.set_defaults(func=cmd_delete)
p_resume = subparsers.add_parser("resume", help="Resume a suspended project")
p_resume.add_argument("--type", required=True, choices=VALID_TYPES)
p_resume.add_argument("--id", required=True, help="Project ID")
p_resume.set_defaults(func=cmd_resume)
p_load = subparsers.add_parser(
"load-credentials",
help="Load credentials for a project from .elastic-credentials",
)
p_load_id = p_load.add_mutually_exclusive_group(required=True)
p_load_id.add_argument("--name", help="Project name")
p_load_id.add_argument("--id", help="Project ID")
p_load.add_argument(
"--include-admin", action="store_true",
help="Include ELASTICSEARCH_USERNAME/PASSWORD (only for API key bootstrapping)",
)
p_load.set_defaults(func=cmd_load_credentials)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
Related skills
Forks & variants (1)
Cloud Manage Project has 1 known copy in the catalog totaling 2 installs. They canonicalize to this original listing.
- elastic - 2 installs
How it compares
Use for Elastic Cloud Serverless project CLI lifecycle rather than Elasticsearch query or Kibana visualization skills.
FAQ
Required env?
EC_API_KEY via cloud-setup or dotenv.
Update settings role?
Admin or Editor on project.
No cloud-setup?
Configure EC_API_KEY in dotenv not chat.
Is Cloud Manage Project safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.