CreateServiceInstanceToken

Updated at:

Retrieves the token and WebSocket URL required to log on to a container.

Try it now

Try this API in OpenAPI Explorer, no manual signing needed. Successful calls auto-generate SDK code matching your parameters. Download it with built-in credential security for local usage.

Test

RAM authorization

The table below describes the authorization required to call this API. You can define it in a Resource Access Management (RAM) policy. The table's columns are detailed below:

  • Action: The actions can be used in the Action element of RAM permission policy statements to grant permissions to perform the operation.

  • API: The API that you can call to perform the action.

  • Access level: The predefined level of access granted for each API. Valid values: create, list, get, update, and delete.

  • Resource type: The type of the resource that supports authorization to perform the action. It indicates if the action supports resource-level permission. The specified resource must be compatible with the action. Otherwise, the policy will be ineffective.

    • For APIs with resource-level permissions, required resource types are marked with an asterisk (*). Specify the corresponding Alibaba Cloud Resource Name (ARN) in the Resource element of the policy.

    • For APIs without resource-level permissions, it is shown as All Resources. Use an asterisk (*) in the Resource element of the policy.

  • Condition key: The condition keys defined by the service. The key allows for granular control, applying to either actions alone or actions associated with specific resources. In addition to service-specific condition keys, Alibaba Cloud provides a set of common condition keys applicable across all RAM-supported services.

  • Dependent action: The dependent actions required to run the action. To complete the action, the RAM user or the RAM role must have the permissions to perform all dependent actions.

Action

Access level

Resource type

Condition key

Dependent action

eas:CreateServiceInstanceToken

get

*Service

acs:eas:{#regionId}:{#accountId}:service/{#ServiceName}

None None

Request syntax

GET /api/v2/services/{ClusterId}/{ServiceName}/instances/{InstanceName}/token HTTP/1.1

Path Parameters

Parameter

Type

Required

Description

Example

ClusterId

string

Yes

The region ID.

cn-shanghai

ServiceName

string

Yes

The service name.

deepseekv3_3

InstanceName

string

Yes

The name of the service instance.

deepseekv3-3-7b56869574-44nq9

Request parameters

Parameter

Type

Required

Description

Example

WorkerName

string

No

The name of the service worker. You can call the ListServiceContainers API operation to obtain the worker name.

worker0

ActionType

string

No

The type of URL to retrieve. Valid values:

  • WorkBench: Logs on to the container through the Workbench page.

  • WebShell: Logs on to the container through a WebSocket URL. Processor-type services and services created before June 2026 are not supported.

Valid values:

  • WorkBench :

    WorkBench

WorkBench

Response elements

Element

Type

Description

Example

object

Schema of Response

RequestId

string

The request ID.

40325405-579C-4D82****

Token

string

The authentication token.

ak123

Url

string

The WebSocket URL.

wss://websocket.cn-hangzhou.pai-eas.aliyuncs.com/ws/cn-hangzhou/xxxxx

WorkbenchUrl

string

The URL used to log on to the container through Workbench. After you log on to the service instance, the returned messages use the WebSocket text message format, and the message content is Base64-encoded. Refer to the following script for processing.

#!/usr/bin/env python3
"""macOS/Linux: python webshell_minimal.py 'wss://...'; Ctrl+] disconnects."""
import argparse
import base64
import codecs
import getpass
import json
import os
import select
import shutil
import sys
import termios
import threading
import tty

import websocket


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('url', help='Url from CreateServiceInstanceToken(ActionType=WebShell)')
    args = parser.parse_args()
    if not sys.stdin.isatty():
        parser.error('Run from an interactive macOS/Linux terminal')
    token = os.environ.get('WEBSHELL_TOKEN') or getpass.getpass('Token: ')
    ws = websocket.create_connection(args.url, header={'Authorization': 'Bearer ' + token.strip()},
                                     subprotocols=['webtty'], timeout=10)
    ws.settimeout(None)
    stopped = threading.Event()

    def receive():
        try:
            while not stopped.is_set():
                message = ws.recv()  # websocket-client automatically replies to control Ping frames.
                if not message:
                    break
                if isinstance(message, str) and message[0] == '1':
                    sys.stdout.buffer.write(base64.b64decode(message[1:], validate=True))
                    sys.stdout.buffer.flush()  # Preserve terminal escape sequences and UTF-8 bytes.
                # '2' is webtty Pong; other types need no handling in this terminal client.
        except (websocket.WebSocketException, OSError, ValueError):
            pass
        finally:
            stopped.set()

    fd = sys.stdin.fileno()
    previous = termios.tcgetattr(fd)
    decoder = codecs.getincrementaldecoder('utf-8')()
    print('Connected. Ctrl+] disconnects; Ctrl+C is sent to the remote shell.', flush=True)
    reader = threading.Thread(target=receive, daemon=True)
    try:
        tty.setraw(fd)
        reader.start()
        size = None
        while not stopped.is_set():
            current = shutil.get_terminal_size((80, 24))
            if current != size:
                ws.send('3' + json.dumps({'columns': current.columns, 'rows': current.lines}))
                size = current
            if select.select([fd], [], [], 0.2)[0]:
                data = os.read(fd, 4096)
                if not data or b'\x1d' in data:  # Ctrl+]
                    break
                text = decoder.decode(data)  # Do not split a UTF-8 character across Text messages.
                if text:
                    ws.send('1' + text)  # Raw input, NOT base64 and NOT a JSON wrapper.
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, previous)
        stopped.set()
        try:
            ws.send_close()
        except (websocket.WebSocketException, OSError):
            pass
        ws.shutdown()
        if reader.ident is not None:
            reader.join(timeout=1)
        print('\nDisconnected.', flush=True)


if __name__ == '__main__':
    try:
        main()
    except websocket.WebSocketBadStatusException as exc:
        sys.exit(f'WebSocket handshake failed: HTTP {exc.status_code}')
    except (websocket.WebSocketException, OSError, UnicodeError, KeyboardInterrupt) as exc:
        sys.exit(f'WebShell stopped: {type(exc).__name__}')

https://ecs-workbench-disposable.aliyun.com/account/disposable/login/sst/180535184*******/uc2vx*****

StreamlogUrl

string

The URL for real-time service logs.

wss://websocket.cn-hangzhou.pai-eas.aliyuncs.com/ws/cn-hangzhou/xxxxx

Examples

Success response

JSON format

{
  "RequestId": "40325405-579C-4D82****",
  "Token": "ak123",
  "Url": "wss://test.com",
  "WorkbenchUrl": "https://ecs-workbench-disposable.aliyun.com/account/disposable/login/sst/180535184*******/uc2vx*****",
  "StreamlogUrl": "***"
}

Error codes

See Error Codes for a complete list.

Release notes

See Release Notes for a complete list.