Использование API для переменных
Клиент variable, содержащийся в пакете, позволяет работать с переменными в системе, используя описанные ниже методы.
Методы API для работы с переменными включают:
-
Получение информации — извлечение данных об одной или нескольких переменных по их идентификаторам.
-
Управление переменными — создание, обновление и удаление переменных.
Описания и примеры приведены для TypeScript (среда выполнения Deno) и Python.
Подготовка клиента для работы с переменными
Чтобы работать с переменными с помощью пакета SDK, импортируйте его:
import * as sdk from '@playbooks/sdk'
...
export async function main() {
...
const v = await sdk.variable.<method_name>(<arg_1>, <arg_2>, ..., <arg_m>)
console.log(v)
...
}
from playbooks.variable import VariableClient
...
def main():
...
client = VariableClient.initialize()
v = client.<method_name>(<arg_1>, <arg_2>, ..., <arg_m>)
print(v)
...
Здесь:
-
<method_name>: имя используемого метода; -
<arg_N>: параметры метода.
Объект Variable
Методы get и list возвращают объект со следующими полями:
-
id: идентификатор переменной. -
name: имя переменной. -
description: описание переменной. -
is_secret: индикатор, указывающий, является ли переменная секретом. -
type: тип переменной. -
status: статус: для TypeScript —"enabled"или"disabled", для Python —TrueилиFalse; -
data: данные переменной. Структура зависит от типа переменной:
| Тип переменной | TypeScript | Python |
|---|---|---|
Integer |
|
|
Bool |
|
|
String |
|
|
Timestamp |
|
|
Float |
|
|
Строка подключения |
|
|
Токен |
|
|
Учетные данные |
|
|
Сертификат |
|
|
Контейнер PKCS |
|
|
Контейнер PKCS12 |
|
|
Файл |
|
|
Объект |
|
|
Здесь:
-
<int>— целое число; -
<bool>— логическое значение; -
<str>— строка; -
<ts>— метка времени; -
<float>— число с плавающей точкой; -
<connection>— строка подключения; -
<token>— токен; -
<login>— имя пользователя; -
<password>— пароль учетной записи или приватного ключа; -
<certificate_file_path>— путь к файлу сертификата; -
<private_key_file_path>— путь к файлу приватного ключа; -
<file_id>— идентификатор файла; -
<file_name>— имя файла; -
<file_size>— размер файла в байтах; -
<key>— ключ поля в объекте; -
<value>— значение поля в объекте.
Создание переменной (create)
Метод используется для создания новой переменной.
Метод возвращает идентификатор созданной переменной (sourceId).
create в TypeScriptcreate({
sourceId: <source_id>, // string
name: <name>, // string
description: <description>, // string | undefined
isSecret: <is_secret>, // boolean | undefined
status: <status>, // Enum | undefined
data: {
value: <data> // any
})
create в Pythoncreate(
source_id=<source_id>, # str
name=<name>, # str
description=<description>, # str | None
is_secret=<is_secret>, # bool
enabled=<status>, # bool
data=<data> # Dict[str, Any]
)
Параметры метода включают в себя:
-
<source_id>: идентификатор переменной (строка). -
<name>: имя переменной (строка). -
<description>(необязательный): описание переменной (строка). -
<is_secret>: индикатор того, что переменная является секретом (логическое значение). -
<status>: статус переменной:-
для TypeScript:
enabled— включена илиdisabled— выключена (строка). -
для Python:
True— включена илиFalse— выключена (логическое значение).
-
-
<data>: данные переменной. Структура зависит от типа переменной, ознакомьтесь с таблицей.
Примеры создания переменной
Пример скрипта с create в TypeScript
id: create_variables_object_ts
name: Create disabled variables of all types
description: Этот скрипт создаст выключенные переменные всех типов
version: 0.0.1
type: script
source: !deno |
import * as sdk from "@playbooks/sdk";
export async function main() {
try {
const var_1 = await sdk.variable.create({
data: { value: { Integer: 1 } },
isSecret: false,
name: 'script_ts_integer',
sourceId: 'sourceid_1_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_1}`);
const var_2 = await sdk.variable.create({
data: { value: { Boolean: false } },
isSecret: false,
name: 'script_boolean_ts',
sourceId: 'sourceid_2_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_2}`);
const var_3 = await sdk.variable.create({
data: { value: { String: 'Пример строки' } },
isSecret: false,
name: 'script_string_ts',
sourceId: 'sourceid_3_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_3}`);
const var_4 = await sdk.variable.create({
data: { value: { Timestamp: '2026-05-20T09:29:00.000Z' } },
isSecret: false,
name: 'script_timestamp_ts',
sourceId: 'sourceid_4_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_4}`);
const var_5 = await sdk.variable.create({
data: { value: { Float: 0.30000000000000004 } },
isSecret: false,
name: 'script_float_ts',
sourceId: 'sourceid_5_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_5}`);
const var_6 = await sdk.variable.create({
data: { value: { Connection: 'https://example' } },
isSecret: false,
name: 'script_connection_ts',
sourceId: 'sourceid_6_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_6}`);
const var_7 = await sdk.variable.create({
data: { value: { Token: '98z0se9hedo' } },
isSecret: false,
name: 'script_token_ts',
sourceId: 'sourceid_7_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_7}`);
const var_8 = await sdk.variable.create({
data: { value: { Credentials: { login: 'admin', password: 'password' } } },
isSecret: false,
name: 'script_credentials_ts',
sourceId: 'sourceid_8_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_8}`);
const var_9 = await sdk.variable.create({
data: { value: { Certificate: 'secret/05833f98-1c43-419d-bdc8-8e41632edca8/certificate_file' } },
isSecret: false,
name: 'script_certificate_ts',
sourceId: 'sourceid_9_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_9}`);
const var_10 = await sdk.variable.create({
data: {
value: {
Pkcs12Container: {
private_key_password: 'admin12345pass',
certificate: 'secret/6273337b-af72-4865-8e28-cc048ba45516/certificate_file',
}
}
},
isSecret: false,
name: 'script_pkcs12container_ts',
sourceId: 'sourceid_10_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_10}`);
const var_11 = await sdk.variable.create({
data: {
value: {
PkcsContainer: {
private_key_password: 'admin12345pass',
certificate: 'secret/9eaa6fb8-c687-4d65-b170-446566091f71/certificate_file',
private_key: 'secret/9eaa6fb8-c687-4d65-b170-446566091f71/private_key_file'
}
}
},
isSecret: false,
name: 'script_pkcs_container_ts',
sourceId: 'sourceid_11_ts',
status: 'disabled',
});
console.log(`Created variable with sourceId: ${var_11}`);
const var_12 = await sdk.variable.create({
data: {
value: {
File: {
id: "5b6c1905-57a2-4ad3-9273-ad1c9a800f65",
name: "AMDRM_Install.log",
size: 630
}
}
},
isSecret: false,
name: "script_file_ts",
sourceId: "sourceid_12_ts",
status: "disabled",
});
console.log(`Created variable with sourceId: ${var_12}`);
const var_13 = await sdk.variable.create({
data: {
value: {
Object: "{\"key\":\"value\"}"
}
},
isSecret: false,
name: "script_object_ts",
sourceId: "sourceid_13_ts",
status: "disabled",
});
console.log(`Created variable with sourceId: ${var_13}`);
} catch (e) {
console.error("Error:", e);
}
}
Пример скрипта с create в Python
id: create_variable_object_py
name: create_variable_object_py
description: Этот скрипт создаст выключенные переменные всех типов
version: 0.4.2
type: script
source: !py |
from playbooks.variable import VariableClient, SecretDataType, SecretCredentials, BooleanInput, CertificateInput, ConnectionStringInput, TokenInput, Pkcs12ContainerInput, PkcsContainerInput, TimestampInput, ObjectStoreFileInput, ObjectInput
from typing import TypedDict, Optional, Union, Unpack
import json
class CreateInput(TypedDict):
source_id: str
name: str
data: Union[str, int, float, CertificateInput, ConnectionStringInput, Pkcs12ContainerInput, PkcsContainerInput, SecretCredentials, SecretDataType, TimestampInput, TokenInput, BooleanInput, ObjectStoreFileInput, ObjectInput]
enabled: bool
is_secret: bool
description: Optional[str]
variable_id = 'py_script_var'
def main():
try:
client = VariableClient.initialize()
variables = [
(variable_id + "_string", 'py_string', client.create(**CreateInput(
source_id=variable_id + "_string",
name='py_string',
data="Пример строки",
enabled=False,
is_secret=False
))),
(variable_id + "_integer", 'py_integer', client.create(**CreateInput(
source_id=variable_id + "_integer",
name='py_integer',
data=1,
enabled=False,
is_secret=False
))),
(variable_id + "_float", 'py_float', client.create(**CreateInput(
source_id=variable_id + "_float",
name='py_float',
data=0.30000000000000004,
enabled=False,
is_secret=False
))),
(variable_id + "_bool", 'py_bool', client.create(**CreateInput(
source_id=variable_id + "_bool",
name='py_bool',
data=BooleanInput(False),
enabled=False,
is_secret=False
))),
(variable_id + "_certificate", 'py_certificate', client.create(**CreateInput(
source_id=variable_id + "_certificate",
name='py_certificate',
data=CertificateInput('secret/05833f98-1c43-419d-bdc8-8e41632edca8/certificate_file'),
enabled=False,
is_secret=False
))),
(variable_id + "_connectionString", 'py_connectionString', client.create(**CreateInput(
source_id=variable_id + "_connectionString",
name='py_connectionString',
data=ConnectionStringInput('https://example'),
enabled=False,
is_secret=False
))),
(variable_id + "_token", 'py_token', client.create(**CreateInput(
source_id=variable_id + "_token",
name='py_token',
data=TokenInput('98z0se9hedo'),
enabled=False,
is_secret=False
))),
(variable_id + "_pkcs12Container", 'py_pkcs12Container', client.create(**CreateInput(
source_id=variable_id + "_pkcs12Container",
name='py_pkcs12Container',
data=Pkcs12ContainerInput('secret/6273337b-af72-4865-8e28-cc048ba45516/certificate_file',
'admin12345pass'),
enabled=False,
is_secret=False
))),
(variable_id + "_pkcsContainer", 'py_pkcsContainer', client.create(**CreateInput(
source_id=variable_id + "_pkcsContainer",
name='py_pkcsContainer',
data=PkcsContainerInput('secret/9eaa6fb8-c687-4d65-b170-446566091f71/certificate_file', 'secret/9eaa6fb8-c687-4d65-b170-446566091f71/private_key_file', 'admin12345pass'),
enabled=False,
is_secret=False
))),
(variable_id + "_credentials", 'py_credentials', client.create(**CreateInput(
source_id=variable_id + "_credentials",
name='py_credentials',
data=SecretCredentials('admin', 'password'),
enabled=False,
is_secret=False
))),
(variable_id + "_timestamp", 'py_timestamp', client.create(**CreateInput(
source_id=variable_id + "_timestamp",
name='py_timestamp',
data=TimestampInput('2026-05-20T09:29:00.000Z'),
enabled=False,
is_secret=False
))),
(variable_id + "_file", 'py_file', client.create(**CreateInput(
source_id=variable_id + "_file",
name='py_file',
data=ObjectStoreFileInput(
id="5b6c1905-57a2-4ad3-9273-ad1c9a800f65",
name="AMDRM_Install.log",
size=630
),
enabled=False,
is_secret=False
))),
(variable_id + "_object", 'py_object', client.create(**CreateInput(
source_id=variable_id + "_object",
name='py_object',
data=ObjectInput(json.loads('{"key":"value"}')), # Преобразуем JSON-строку в объект.
enabled=False,
is_secret=False
))),
]
for name, description, result in variables:
print(f"Created variable with sourceId: {result}")
except Exception as e:
print(f"Ошибка: {str(e)}")
Получение списка переменных (list)
Метод используется для получения списка расшифрованных переменных по массиву их идентификаторов.
list({
sourceIds: <source_ids> // string[]
})
list(
ids=<source_ids> # List[str]
)
Параметры метода включают в себя <source_ids> — список идентификаторов переменных, указанных при их создании (массив строк).
Возвращает список объектов Variable (см. Объект Variable).
Примеры получения списка переменных
Пример скрипта с list в TypeScript
id: list_variables_object_ts
name: list_variables_object_ts
description: Получение списка переменных
version: 0.0.1
type: script
source: !deno |
import * as sdk from "@playbooks/sdk"
export async function main() {
try {
// Идентификаторы переменных.
const sourceIds = [
'sourceid_1_ts',
'sourceid_2_ts',
'sourceid_3_ts',
'sourceid_4_ts',
'sourceid_5_ts',
'sourceid_6_ts',
'sourceid_7_ts',
'sourceid_8_ts',
'sourceid_9_ts',
'sourceid_10_ts',
'sourceid_11_ts',
'sourceid_12_ts',
'sourceid_13_ts',
];
const variables = await sdk.variable.list({
sourceIds: sourceIds
});
console.log(JSON.stringify(variables, null, 2));
} catch (e) {
console.error("Произошла ошибка:", e);
}
}
Пример скрипта с list в Python
id: list_variable_object_py
name: list_variable_object_py
description: Получение списка переменных
version: 0.1.8
type: script
source: !py |
from playbooks.variable import VariableClient, SecretDataType, SecretCredentials, BooleanInput, CertificateInput, ConnectionStringInput, TokenInput, Pkcs12ContainerInput, PkcsContainerInput, TimestampInput, ObjectStoreFileInput, ObjectInput
from typing import TypedDict, Optional, Union, Unpack, List
import json
class ListInput(TypedDict):
ids: List[str]
class GetInput(TypedDict):
id: str
# Идентификаторы переменных.
variable_ids = [
'py_script_var_string',
'py_script_var_integer',
'py_script_var_float',
'py_script_var_bool',
'py_script_var_certificate',
'py_script_var_connectionString',
'py_script_var_token',
'py_script_var_pkcs12Container',
'py_script_var_pkcsContainer',
'py_script_var_credentials',
'py_script_var_timestamp',
'py_script_var_file',
'py_script_var_object'
]
def main():
try:
client = VariableClient.initialize()
variables = client.list(**ListInput(ids=variable_ids))
print(json.dumps(variables, indent=2, default=str))
except Exception as error:
print("Произошла ошибка:", error)
import traceback
traceback.print_exc()
Получение данных о переменной (get)
Метод используется для получения расшифрованной переменной, в том числе секрета, по ее идентификатору.
get в TypeScriptget({
id: <id> // string
})
get в Pythonget(
id=<id> # str
)
В методе используется параметр <id> — идентификатор переменной (строка).
Может использоваться как source_id, указанный при создании переменной, так и внутренний UUID системы.
|
Метод get возвращает объект Variable (см. Объект Variable).
Примеры получения данных об одной переменной
Пример скрипта с get в TypeScript
id: get_variable_object_ts
name: get_variable_object_ts
description: Получение значения переменной по source_id
version: 0.0.1
type: script
source: !deno |
import * as sdk from "@playbooks/sdk"
export async function main() {
try {
const variables = await sdk.variable.get({ id: 'script_var_object' });
console.log(JSON.stringify(variables, null, 2));
} catch (e) {
console.log(e);
}
}
Пример скрипта с get в Python
id: get_variable_object_py
name: get_variable_object_py
description: Получение значения переменной по source_id
version: 0.0.1
type: script
source: !py |
from playbooks.variable import VariableClient, SecretDataType, SecretCredentials, BooleanInput, CertificateInput, ConnectionStringInput, TokenInput, Pkcs12ContainerInput, PkcsContainerInput, TimestampInput, ObjectStoreFileInput, ObjectInput
from typing import TypedDict, Optional, Union, Unpack
import json
class GetInput(TypedDict):
id: str
variable_source_id = 'script_var_object'
def main():
try:
client = VariableClient.initialize()
variable = client.get(**GetInput(id=variable_source_id))
print(json.dumps(variable, indent=2, default=str))
except Exception as error:
print("Ошибка:", error)
Обновление переменной (update)
Метод используется для обновления существующей переменной по ее идентификатору источника.
Метод возвращает идентификатор обновлённой переменной (sourceId).
update({
sourceId: <source_id>, // string
name: <name>, // string
description: <description> // string | undefined
isSecret: <is_secret>, // boolean | undefined
data: {
value: <data>, // any
}
status: <status>, // Enum | undefined
)
update(
source_id=<source_id>, # str
name=<name>, # str
description=<description>, # str | None
is_secret=<is_secret>, # bool
data=<data>, # Dict[str, Any]
enabled=<status> # bool
)
Параметры метода аналогичны параметрам метода create.
Примеры изменения переменной
Пример скрипта с update в TypeScript
id: update_variable_object_ts
name: update_variable_object_ts
description: Этот скрипт обновит переменные всех типов
version: 0.0.1
type: script
source: !deno |
import * as sdk from "@playbooks/sdk";
export async function main() {
try {
// Обновление переменных по sourceId.
const id1 = await sdk.variable.update({
data: { value: { Integer: 42 } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_integer_ts_updated',
sourceId: 'sourceid_1_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id1}`);
const id2 = await sdk.variable.update({
data: { value: { Boolean: true } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_boolean_ts_updated',
sourceId: 'sourceid_2_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id2}`);
const id3 = await sdk.variable.update({
data: { value: { String: 'обновленное значение string' } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_string_ts_updated',
sourceId: 'sourceid_3_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id3}`);
const id4 = await sdk.variable.update({
data: { value: { Timestamp: '2026-12-31T23:59:59.999Z' } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_timestamp_ts_updated',
sourceId: 'sourceid_4_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id4}`);
const id5 = await sdk.variable.update({
data: { value: { Float: 3.14159265359 } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_float_ts_updated',
sourceId: 'sourceid_5_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id5}`);
const id6 = await sdk.variable.update({
data: { value: { Connection: 'https://updated-connection.example.com' } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_connection_ts_updated',
sourceId: 'sourceid_6_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id6}`);
const id7 = await sdk.variable.update({
data: { value: { Token: 'UPDATED_TOKEN_XYZ123' } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_token_ts_updated',
sourceId: 'sourceid_7_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id7}`);
const id8 = await sdk.variable.update({
data: { value: { Credentials: { login: 'updated_user', password: 'updated_pass123' } } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_credentials_ts_updated',
sourceId: 'sourceid_8_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id8}`);
const id9 = await sdk.variable.update({
data: { value: { Certificate: 'secret/updated-certificate-id/certificate_file' } },
description: 'updated_description_ts',
isSecret: false,
name: 'script_certificate_ts_updated',
sourceId: 'sourceid_9_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id9}`);
const id10 = await sdk.variable.update({
data: {
value: {
Pkcs12Container: {
private_key_password: 'updated_password_123',
certificate: 'secret/updated-pkcs12-cert/certificate_file',
}
}
},
description: 'updated_description_ts',
isSecret: false,
name: 'script_pkcs12container_ts_updated',
sourceId: 'sourceid_10_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id10}`);
const id11 = await sdk.variable.update({
data: {
value: {
PkcsContainer: {
private_key_password: 'updated_password_456',
certificate: 'secret/updated-pkcs-cert/certificate_file',
private_key: 'secret/updated-pkcs-cert/private_key_file'
}
}
},
description: 'updated_description_ts',
isSecret: false,
name: 'script_pkcs_container_ts_updated',
sourceId: 'sourceid_11_ts',
status: 'enabled',
});
console.log(`Updated variable with sourceId: ${id11}`);
const id12 = await sdk.variable.update({
data: {
value: {
File: {
data: "VXBkYXRlZCBmaWxlIGNvbnRlbnQgYmFzZTY0IGVuY29kZWQ=",
name: "updated_file.log"
}
}
},
description: "updated_description_ts",
isSecret: false,
name: "script_file_ts_updated",
sourceId: "sourceid_12_ts",
status: "enabled",
});
console.log(`Updated variable with sourceId: ${id12}`);
const id13 = await sdk.variable.update({
data: {
value: {
Object: "{\"updated\":\"value\",\"new_field\":\"new_data\"}"
}
},
description: "updated_description_ts",
isSecret: false,
name: "script_object_ts_updated",
sourceId: "sourceid_13_ts",
status: "enabled",
});
console.log(`Updated variable with sourceId: ${id13}`);
} catch (e) {
console.error("Error updating variables:", e);
}
}
Пример скрипта с update в Python
id: update_variables_object_py
name: Update variables object py
description: Этот скрипт обновит переменные всех типов
version: 0.0.1
type: script
source: !py |
from playbooks.variable import VariableClient, SecretDataType, SecretCredentials, BooleanInput, CertificateInput, ConnectionStringInput, TokenInput, Pkcs12ContainerInput, PkcsContainerInput, TimestampInput, ObjectStoreFileInput, ObjectInput
from typing import TypedDict, Union, Optional
class UpdateInput(TypedDict):
source_id: str
name: str
data: Union[str, int, float, CertificateInput, ConnectionStringInput, Pkcs12ContainerInput, PkcsContainerInput, SecretCredentials, SecretDataType, TimestampInput, TokenInput, BooleanInput, ObjectStoreFileInput, ObjectInput]
enabled: bool
is_secret: bool
description: Optional[str]
variables_to_update = {
'py_script_var_string': {
'name': 'py_var_string_updated',
'data': 'обновленное значение string', # Новое значение.
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_integer': {
'name': 'py_var_integer_updated',
'data': 9999,
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_float': {
'name': 'py_var_float_updated',
'data': 3.14159265359,
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_bool': {
'name': 'py_var_bool_updated',
'data': BooleanInput(True),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_certificate': {
'name': 'py_var_certificate_updated',
'data': CertificateInput('secret/updated-certificate-id/certificate_file'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_connectionString': {
'name': 'py_var_connectionString_updated',
'data': ConnectionStringInput('https://updated-connection.example.com'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_token': {
'name': 'py_var_token_updated',
'data': TokenInput('UPDATED_TOKEN_XYZ123'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_pkcs12Container': {
'name': 'py_var_pkcs12Container_updated',
'data': Pkcs12ContainerInput('updated_password_123', 'secret/updated-pkcs12-cert/certificate_file'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_pkcsContainer': {
'name': 'py_var_pkcsContainer_updated',
'data': PkcsContainerInput('updated_password_456', 'secret/updated-pkcs-cert/certificate_file', 'secret/updated-pkcs-cert/private_key_file'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_credentials': {
'name': 'py_var_credentials_updated',
'data': SecretCredentials('updated_user', 'updated_pass123'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_timestamp': {
'name': 'py_var_timestamp_updated',
'data': TimestampInput('2026-12-31T23:59:59.999Z'),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_file': {
'name': 'py_var_file_updated',
'data': ObjectStoreFileInput(
id="23bf3e9d-aa42-4e41-91b2-eff0610d29e2",
data="VXBkYXRlZCBmaWxlIGNvbnRlbnQgYmFzZTY0IGVuY29kZWQ=",
name="updated_file.log",
size=630
),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
'py_script_var_object': {
'name': 'py_var_object_updated',
'data': ObjectInput({"key": "updated_value", "new_field": "new_data"}),
'enabled': True,
'is_secret': False,
'description': 'обновленное описание'
},
}
def main():
try:
client = VariableClient.initialize()
for source_id, update_data in variables_to_update.items():
result = client.update(
source_id=source_id,
**update_data
)
print(f"Updated variable with sourceId: {result}")
except Exception as error:
print("Произошла ошибка:", error)
Удаление переменной (delete)
Метод используется для удаления существующей переменной.
delete({
id: <source_id> // string
})
delete(
id=<source_id> # str
)
В методе используется параметр <source_id> — идентификатор переменной, которую необходимо удалить (строка). Этот идентификатор был задан при создании переменной.
Примеры удаления переменной
Пример скрипта с delete в TypeScript
id: delete_variables_object_ts
name: delete_variables_object_ts
description: Удаление массива переменных
version: 0.0.1
type: script
source: !deno |
import * as sdk from "@playbooks/sdk"
export async function main() {
try {
const entityIds = [
'sourceid_1_ts',
'sourceid_2_ts',
'sourceid_3_ts',
'sourceid_4_ts',
'sourceid_5_ts',
'sourceid_6_ts',
'sourceid_7_ts',
'sourceid_8_ts',
'sourceid_9_ts',
'sourceid_10_ts',
'sourceid_11_ts',
'sourceid_12_ts',
'sourceid_13_ts'
];
// Удаляем переменные параллельно.
const deletionPromises = entityIds.map((id) =>
sdk.variable.delete({ id })
);
// Ждем завершения всех операций удаления.
const results = await Promise.allSettled(deletionPromises);
let successCount = 0;
let errorCount = 0;
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Переменная с id: ${entityIds[index]} успешно удалена.`);
successCount++;
} else {
console.error(`Ошибка удаления переменной с id: ${entityIds[index]}. Ошибка:`, result.reason);
errorCount++;
}
});
console.log(`\nИтог: Успешно - ${successCount}, Ошибок - ${errorCount}`);
return {
success: true,
deletedCount: successCount,
errorCount: errorCount
};
} catch (error) {
console.error('Критическая ошибка:', error);
return {
success: false,
error: error.message
};
}
}
Пример скрипта с delete в Python
id: delete_variable_object_py
name: delete_variable_object_py
description: Удаление массива переменных
version: 0.0.1
type: script
source: !py |
from playbooks.variable import VariableClient, SecretDataType, SecretCredentials, BooleanInput, CertificateInput, ConnectionStringInput, TokenInput, Pkcs12ContainerInput, PkcsContainerInput, TimestampInput, ObjectStoreFileInput, ObjectInput
from typing import TypedDict, Unpack
class DeleteInput(TypedDict):
id: str
# Массив переменных для удаления
variable_ids = [
'py_script_var_string',
'py_script_var_integer',
'py_script_var_float',
'py_script_var_bool',
'py_script_var_certificate',
'py_script_var_connectionString',
'py_script_var_token',
'py_script_var_pkcs12Container',
'py_script_var_pkcsContainer',
'py_script_var_credentials',
'py_script_var_timestamp',
'py_script_var_file',
'py_script_var_object'
]
def main():
client = VariableClient.initialize()
# Delete variable
for variable_id in variable_ids:
try:
client.delete(**DeleteInput(id=variable_id))
print(f'Переменная с id: {variable_id} успешно удалена.')
except Exception as error:
print(f'Ошибка удаления переменной с id: {variable_id}. Ошибка: {error}')
Была ли полезна эта страница?