Drive instances from a script
Keep a pool of machines from a script, launching with tags and extra volumes, waiting for a state, finding machines by tag and relabelling them in one call.
Last updated 18 November 2026View as Markdown
What a script that keeps a pool of machines (preview boxes, runners) needs, without reading the console. Replace the ids and tag values with your own.
Prerequisites
- Permission for
ec2:RunInstancesandec2:DescribeInstances; withvolumes, alsoec2:CreateVolumeandec2:AttachVolume; with an instance role,iam:PassRoleon it. - Relabelling needs
tags:TagResourceto set andtags:UntagResourceto remove, on the instance.
Launch and wait
id=$(dcloud ec2 instances run --region-id de1 --availability-zone-id de1b \
--server-type dedicated-8 --machine-image-id ewi-0a1b2c3d \
--iam-role-name preview-box --tags pool=preview --tags slot=7 \
--volumes '{"sizeGib":40}' --json | jq -r .data.id)
dcloud ec2 instances wait "$id"POST /ec2/api/instances
{
"serverType": "dedicated-8",
"machineImageId": "ewi-0a1b2c3d",
"regionId": "de1",
"availabilityZoneId": "de1b",
"iamRoleName": "preview-box",
"tags": { "pool": "preview", "slot": "7" },
"volumes": [{ "sizeGib": 40 }]
}Then GET /ec2/api/instances/{id}/wait.
volumes(up to 4, 10 to 10 000 GiB each) are made in the instance's zone and attached as soon as it runs; each is encrypted and deleted with the instance unless you say"encrypted": falseor"deleteOnTermination": false. The instance's activity says when each was attached or deleted.waittakes--state running|stopped|terminated(defaultrunning) and--timeout-seconds(1 to 300, default 120).runningcounts only once the machine exists at the provider, so its public address is known. When the time runs out it answers408"… is pending, not running, after 120 s; call again to keep waiting", and409"… terminated before it was running" at once if the instance terminated first.tagsmust include your organization's required tag keys, if it has any; the tags also go onto the launch volumes.
Find and relabel
dcloud ec2 instances list --tag pool=preview,slot=7
dcloud ec2 instances set-tags "$id" --set owner=pr-42 --set state=busy --remove slotPATCH /ec2/api/instances/i-3f9a2c07/tags
{ "set": { "owner": "pr-42", "state": "busy" }, "remove": ["slot"] }List with GET /ec2/api/instances?tag=pool=preview,slot=7.
tagtakeskey=valueclauses separated by commas, at most 10 ("At most 10 tag clauses" otherwise), all of which must match; a barekeymeans the tag is present.- Every row of the list carries its
tags. The list also filters bystateand byname(a part of the name or id), and pages withlimit(1 to 500, default 100) andoffset, oldest first. set-tagsanswers with the tags the instance carries afterwards. A request with nothing to set or remove is refused with400"Give tags to set, keys to remove, or both".
A stable public address per slot: an elastic IP moved to the slot's new machine.
Related
Did this page help you?