Applying Execution Environment Updates to Running Content

Problem

You want to apply execution environment changes to running content.

Solution

Warning

You must have administrator privileges to stop running jobs.

Stop all running jobs for content that uses the execution environment. When users visit the content in the Connect UI or build/deploy content via the Connect API, Connect uses the updated execution environment configuration to launch new jobs.

from posit.connect import Client

client = Client()

ENVIRONMENT_GUID = "<your-environment-guid>"
environment = client.environments.find(ENVIRONMENT_GUID)

# Find all content using the execution environment
content = [
    content
    for content in client.content.find()
    if content["environment_guid"] == environment['guid']
]

if not content:
    raise RuntimeError(f"No content found using execution environment: {environment['name']}")

for item in content:
    # Find all active jobs for each content item
    active_jobs = [
        job
        for job in item.jobs.fetch()
        if job["status"] == 0
    ]

    if not active_jobs:
        print(f"No active jobs found for content guid: {item['guid']}")
        continue

    # Destroy all active jobs for each content item
    print(f"Terminating all jobs executing within the execution environment: {environment['name']}")
    for job in active_jobs:
        print(f" - Content with GUID = {item['guid']}...TERMINATED.")
        job.destroy()

Example outputs

When content has running jobs:

Destroying job with key (Tg5g9ItbovpfGklp) for content guid (d144aa4f-6b9a-483f-9e39-f5b151cd2c0b)
Destroying job with key (W3HAUboCIQT32ujK) for content guid (08672b2c-8647-4018-9270-60141bbac7e2)

When content has no running jobs:

No active jobs found for content guid: d144aa4f-6b9a-483f-9e39-f5b151cd2c0b
No active jobs found for content guid: 08672b2c-8647-4018-9270-60141bbac7e2

When no content uses the execution environment:

RuntimeError: No content found using execution environment: eef79371-bf12-4d3e-8d42-2072c6a29c05

Discussion

When you update an execution environment’s configuration such as R/Python/Quarto versions or matching strategy, you can run this script to ensure running content picks up these changes.

In a busy system, this script may need to executed multiple times until no instances are found. Once all running jobs have been stopped, the execution environment will exit.