Creating Entities
Function blocks can create new devices, interfaces, and device groups in the neops CMS — the foundation for device discovery, inventory automation, and dynamic topology management.
Why create entities from a function block?
Entity creation from within a function block removes the manual onboarding bottleneck: a discovery step scans a subnet, queries a CMDB, or parses a spreadsheet and feeds new entities directly into the neops data model — programmatically, repeatably, and idempotently.
Common use cases:
- Subnet discovery — ICMP/SNMP sweep that registers every responding device.
- CMDB synchronization — reconcile an external device list with neops.
- Interface enumeration — parse
show interfacesand create anInterfaceentity for each port.
Entity wrappers
The SDK provides three wrapper classes in neops_worker_sdk.workflow.entities:
| Wrapper | Extends | Use case |
|---|---|---|
Device |
DeviceTypeDto |
Create a new device in the CMS |
Interface |
InterfaceTypeDto |
Create a new interface on an existing or new device |
DeviceGroup |
DeviceGroupTypeDto |
Create a new logical group |
Each wrapper inherits every field from the underlying DTO and adds two fields:
| Field | Type | Purpose |
|---|---|---|
skip_if_identifier_exists |
bool |
Skip creation when a matching entity already exists |
identifier_fields |
groups of DeviceField\|InterfaceField\|GroupField |
Fields used to detect duplicates; see Identifier fields |
A Device also requires network_zone; see Network zones.
An id is auto-generated at instantiation via a cryptographically random
temporary value, usable immediately for cross-entity references (e.g., linking
a new Interface to its parent Device).
Creating a device
This function block discovers devices on a subnet and registers them in the
CMS by appending new Device instances to the context:
class DiscoverDevices(FunctionBlock[DiscoverParams, DiscoverResult]):
async def run(
self, params: DiscoverParams, context: WorkflowContext, meta: JobMeta
) -> FunctionBlockResult[DiscoverResult]:
discovered_ips = await self._scan_subnet(params.subnet)
for ip in discovered_ips:
new_device = Device(
hostname=f"discovered-{ip.replace('.', '-')}",
ip=ip,
network_zone=NetworkZone(name=meta.network_zone),
skip_if_identifier_exists=True,
identifier_fields=[[DeviceField.ip, DeviceField.network_zone]],
)
if context.devices is not None:
context.devices.append(new_device)
self.logger.info(f"Discovered {len(discovered_ips)} devices on {params.subnet}")
return FunctionBlockResult(
message=f"Discovered {len(discovered_ips)} devices.",
success=True,
data=DiscoverResult(discovered_count=len(discovered_ips)),
)
async def _scan_subnet(self, subnet: str) -> list[str]:
"""Placeholder: in practice, use icmplib or SNMP discovery."""
del subnet
return ["10.0.1.1", "10.0.1.2", "10.0.1.3"]
async def acquire(self, params: AcquireParams[DiscoverParams], meta: JobMeta) -> FunctionBlockAcquireResult:
del params
return FunctionBlockAcquireResult(message="No resources required.", success=True, acquires=None)
Key observations:
Device(...)creates a wrapper with standard DTO fields plus creation options, in the job’s network zone (meta.network_zone).context.devices.append(new_device)adds the entity to the context; the diffing engine detects it as new at the end of execution.- The temporary ID on
new_device.idis valid for cross-references within the same execution (e.g., creating anInterfacethat belongs to this device).
Deduplication with skip_if_identifier_exists
When skip_if_identifier_exists=True, the CMS checks whether an entity with
matching identifier field values already exists before inserting. If a match is
found, the creation is silently skipped.
This makes the function block idempotent with respect to entity creation. Running the same discovery twice against the same subnet does not produce duplicate devices — exactly the behavior you want for scheduled or retried workflows.
Identifier fields are mandatory when skipping
Setting skip_if_identifier_exists=True without specifying
identifier_fields raises a ValidationError at instantiation. The SDK
enforces this constraint via a Pydantic model validator.
Identifier fields
Identifier fields tell the CMS how to find an existing entity. Available options:
| Entity | Enum | Values |
|---|---|---|
| Device | DeviceField |
hostname, ip, network_zone |
| Interface | InterfaceField |
name |
| DeviceGroup | GroupField |
name |
These enums are validated against actual DTO model fields at import time — if the upstream API renames a field, the SDK fails fast rather than silently ignoring the mismatch.
identifier_fields is a list of groups, tried in order:
- every field of a group must match the same record;
- a group is skipped when the entity lacks one of its fields;
- the first group that finds a record decides;
- a bare field is a group of one, so
[DeviceField.hostname, DeviceField.ip]tries the hostname, then the IP.
Device(
hostname="core-rtr-01",
ip="10.0.0.1",
network_zone=NetworkZone(name=meta.network_zone),
skip_if_identifier_exists=True,
identifier_fields=[[DeviceField.ip, DeviceField.network_zone]],
)
A group that names network_zone looks only inside that zone; one that does not matches
devices in every zone. Every base block puts the zone in each device group. A group needs a
field besides network_zone, and an empty group is refused. A lookup that finds two records
fails the run.
Network zones
Every device is in one network zone; a
device without one is in default. A block sets the zone of each device it creates itself:
nothing fills it in.
| What | How |
|---|---|
| Create a device | Device(..., network_zone=NetworkZone(name=meta.network_zone)). Without network_zone the wrapper raises a ValidationError. Any zone the CMS holds is accepted, so map it from meta: the job’s zone is the one network its worker reached |
| Name an interface’s device | DeviceReference(id=...), or DeviceReference(hostname=..., ip=..., network_zone=...) with the device’s own zone. Without an id, a reference needs its zone and a hostname or an IP; otherwise it raises a ValidationError |
| Move a device | context.device.network_zone = NetworkZone(name="zone-a"). The device’s next jobs, with its credentials, go to that zone’s workers |
| Work on one zone’s devices | context.devices_in_zone(meta.network_zone) |
NetworkZone(name=...) is sent by name, as Platform(short_name=...) is; the CMS resolves it.
A zone a block writes, on a device or in a reference, always goes by its name alone, also one
copied from a locked device together with its id.
NetworkZone(name="default") stores no zone.
How a reference without an id is bound
Before the result leaves the worker, an interface’s device reference without an id is matched against the job’s devices, on every field it carries, its zone included, in this order:
- devices created in the same job: the reference becomes the device’s temporary id, which the CMS maps to the device it creates, or to the existing one it skips to;
- the device the job runs on (
context.device): the reference becomes that device’s id; - the devices the job holds: the same.
A reference that matches none of them, or carries no zone, is sent as it is, and the CMS
resolves it. The job fails with retryable=False, and none of its changes are sent, when a
reference matches two devices at one step, or matches a device of the job by hostname and IP
but names another zone. Name the device by its id where you have it, as
network_device_get_interfaces does for the device it runs on.
Narrow with devices_in_zone, never by removing devices
A device removed from context.devices is deleted in the CMS. devices_in_zone()
returns a read-only tuple of the context’s devices in that zone; the devices left out of
it stay where they are.
The diffing engine
You never call a “create entity” API yourself. Instead, the SDK tracks changes automatically:
flowchart LR
A["Context snapshot<br/>(deep copy at init)"] --> D["Diffing engine"]
B["Function block<br/>modifies context"] --> C["Current state<br/>(after execution)"]
C --> D
D --> E["CREATE ops"]
D --> F["PATCH ops"]
D --> G["DELETE ops"]
- At init, the SDK takes a deep copy of all entity lists (the snapshot).
- Your function block mutates the live lists: appending, modifying, or removing.
- After
run()returns,compute_db_updates()diffs current state vs snapshot.
The diff produces three operation types:
| Condition | Operation | DTO |
|---|---|---|
| Entity in current state but not in snapshot | CREATE | EntityCreateDto |
| Entity in both, with changed fields | PATCH | EntityPatchDto |
| Entity in snapshot but not in current state | DELETE | EntityDeleteDto |
Read-only and computed fields (id, created_at, updated_at, lock states,
permission fields) are excluded from diffing automatically.
The CMS applies a run’s operations in the order it receives them and refuses a write that
names an entity the run creates later. So every create is sent first, each after the creates it
names: a group before a device naming it in groups, a controller before the devices naming it in controller, a device before its
interfaces. Deletes and patches follow. Creates that name each other in a cycle, such as two new
devices each naming the other as controller, fail the job with retryable=False and none of
its changes are sent; leave one of the references to a later job.
Combine creation and modification
You can create new entities and modify existing ones in the same function block execution. The diffing engine handles mixed operations in a single pass.
Entity changes are not side effects
The engine applies these operations itself, and only when the whole run
succeeds. A block whose only changes are entity changes has no side effects
and registers is_pure=True, like the base blocks device_update_device
and global_add_devices.
Next: Pure and Idempotent Function Blocks — understand how safety semantics affect workflow retry and rollback behavior.

