### Setup Development Environment Source: https://github.com/jrxfive/python-nomad/blob/master/docs/index.md Create a virtual environment, activate it, and install development requirements. ```bash virutalenv venv source venv/bin/activate pip install -r requirements-dev.txt ``` -------------------------------- ### Install Development Requirements Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Install all development dependencies for the project. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install python-nomad Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Install the python-nomad library using pip. ```bash pip install python-nomad ``` -------------------------------- ### Basic Request Example Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Demonstrates a basic request with path arguments. This method is inherited from the Requester class. ```python self.request("something","further") >>> ENDPOINT/something/further ``` -------------------------------- ### Start Development Nomad Agent and Run Tests Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Starts a local development Nomad agent and then runs Python tests with code coverage. Ensure the NOMAD_IP environment variable is set correctly. ```bash ./nomad agent -dev -node pynomad1 --acl-enabled NOMAD_IP=127.0.0.1 NOMAD_VERSION= py.test --cov=nomad --cov-report=term-missing --runxfail tests/ ``` -------------------------------- ### Run Integration Tests with Vagrant Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Start a local Nomad environment using Vagrant and run integration tests with coverage reporting. ```bash vagrant up --provider virtualbox py.test --cov=nomad --cov-report=term-missing --runxfail tests/ ``` -------------------------------- ### Register Job Test Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Example test function for registering a job with Nomad. Requires a running Nomad instance and an example job definition file. ```python import pytest import json import uuid # integration tests requires nomad Vagrant VM or Binary running def test_register_job(nomad_setup): with open("example.json") as fh: job = json.loads(fh.read()) nomad_setup.job.register_job("example", job) assert "example" in nomad_setup.job ``` -------------------------------- ### Get Default Event Stream Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/event.md Sets up a default event stream that listens to all topics. The stream is returned as a tuple containing a thread, an exit event, and a queue for events. This is useful for general monitoring. ```python import nomad n = nomad.Nomad() stream, stream_exit_event, events = n.event.stream.get_stream() stream.start() while True: event = events.get() print(event) events.task_done() ``` -------------------------------- ### Get Node Metrics Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/metrics.md Retrieves metrics for the Nomad node. Ensure the Nomad Python client is installed and configured with the correct host. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') metrics = my_nomad.metrics.get_metrics() ``` -------------------------------- ### List All Nomad Allocations Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/allocations.md Use this snippet to retrieve a list of all allocations managed by Nomad. Ensure the 'nomad' library is installed and configured with your Nomad host. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') allocations = my_nomad.allocations.get_allocations() for allocation in allocations: print (allocation) ``` -------------------------------- ### List Deployments with Python Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployments.md Use this snippet to retrieve a list of all deployments in your Nomad cluster. Ensure the 'nomad' library is installed and configured with your Nomad host address. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') deployments = my_nomad.deployments.get_deployments() for deployment in deployments: print (deployment) ``` -------------------------------- ### Get Job Allocations Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Retrieve all allocations for a given job ID. ```python example_allocation = n.job.get_allocations(j) ``` -------------------------------- ### Set and Get Working Namespace Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/namespace.md Manage the active namespace for the current session. This allows you to set a working workspace and then retrieve the currently active one. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') namespace = { "Name": "api-prod", "Description": "Production API Servers" } my_nomad.namespace.create_namespace(namespace) # Activate workspace on requests my_nomad.set_namespace("api-prod") # Show current workspace for the session print (my_nomad.get_namespace()) ``` -------------------------------- ### Nomad Job Operations with Python Client Source: https://github.com/jrxfive/python-nomad/blob/master/docs/nomad/examples.md Shows how to check if a job exists, retrieve a job ID, get its allocations, and deregister the job using the Python Nomad client. ```python "example" in n.jobs ``` ```python j = n.jobs["example"]["ID"] ``` ```python example_allocation = n.job.get_allocations(j) ``` ```python n.job.deregister_job(j) ``` -------------------------------- ### List Nomad Variables Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/variables.md Retrieves and prints all registered variables in the Nomad system. Requires the 'nomad' Python library to be installed and a Nomad client connection. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') variables = my_nomad.variables.get_variables() for var in variables: print(var) ``` -------------------------------- ### Test Get Namespaces with Mocked Response Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md This snippet demonstrates how to test the `get_namespaces` method using the `responses` library to mock the Nomad API. It asserts that the returned value is a list. ```python @responses.activate def test_get_namespaces(nomad_setup): responses.add( responses.GET, "http://{ip}:{port}/v1/namespaces".format(ip=common.IP, port=common.NOMAD_PORT), status=200, json=[ { "CreateIndex": 31, "Description": "Production API Servers", "ModifyIndex": 31, "Name": "api-prod" }, { "CreateIndex": 5, "Description": "Default shared namespace", "ModifyIndex": 5, "Name": "default" } ] ) assert isinstance(nomad_setup.namespaces.get_namespaces(), list) == True ``` -------------------------------- ### List Nomad Evaluations Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/evaluations.md Use this snippet to retrieve a list of all evaluations in your Nomad cluster. Ensure the Nomad Python client is installed and configured with your Nomad host. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') evaluations = my_nomad.evaluations.get_evaluations() for evaluation in evaluations: print (evaluation) ``` -------------------------------- ### Set up Python Virtual Environment Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Create a virtual environment and activate it for project dependencies. ```bash virtualenv .venv source .venv/bin/activate ``` -------------------------------- ### Get Nomad Leader Address Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/status.md Retrieve the address of the current leader in the Nomad region. Requires the nomad library to be installed. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') leader = my_nomad.status.leader.get_leader() ``` -------------------------------- ### Initialize Python Nomad Client Source: https://github.com/jrxfive/python-nomad/blob/master/docs/nomad/examples.md Demonstrates various ways to initialize the Nomad client, including HTTP, HTTPS with certificate validation options, and with namespace and ACL token. ```python import nomad # For HTTP Nomad instances n = nomad.Nomad(host="172.16.100.10", timeout=5) ``` ```python # For HTTPS Nomad instances with non-self-signed SSL certificates n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=True) ``` ```python # For HTTPS Nomad instances with self-signed SSL certificates and no validate the cert n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=False) ``` ```python # For HTTPS Nomad instances with self-signed SSL certificates that mus validate with cert n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=True, cert="/path/to/certfile") # See http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification ``` ```python # For HTTPS Nomad instances with cert file and key n = nomad.Nomad(host="https://172.16.100.10", secure=True, timeout=5, verify=True, cert=("/path/to/certfile", "/path/to/key") # See http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification ``` ```python # For HTTPS Nomad instances with namespace and acl token n = nomad.Nomad(host="172.16.100.10", secure=True timeout=5, verify=False, namespace='Namespace-example',token='3f4a0fcd-7c42-773c-25db-2d31ba0c05fe') ``` -------------------------------- ### Initialize Nomad Client for HTTPS with Certificate and Key Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance using a certificate and key file. SSL verification is enabled. ```python # For HTTPS Nomad instances with cert file and key n = nomad.Nomad(host="https://172.16.100.10", secure=True, timeout=5, verify=True, cert=("/path/to/certfile", "/path/to/key")) # See http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification ``` -------------------------------- ### Configure Nomad Client with Environment Variables Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Configure the Nomad client using environment variables for address, namespace, token, region, and client certificates. ```bash NOMAD_ADDR=http://127.0.0.1:4646 NOMAD_NAMESPACE=default NOMAD_TOKEN=xxxx-xxxx-xxxx-xxxx NOMAD_REGION=us-east-1a NOMAD_CLIENT_CERT=/path/to/tls/client.crt NOMAD_CLIENT_KEY=/path/to/tls/client.key ``` -------------------------------- ### Initialize Nomad Client for HTTPS with CA, Certificate, and Key Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance using a CA certificate, client certificate, and key file. SSL verification is enabled. ```python # For HTTPS Nomad instance with cert file and key and CA file n = nomad.Nomad(host="https://172.16.100.10", secure=True, timeout=5, verify="/path/to/cacert", cert=("/path/to/certfile", "/path/to/key")) ``` -------------------------------- ### Get Allocation Test Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Tests retrieving a specific allocation by its ID. Asserts that the returned value is a dictionary. ```python def test_get_allocation(nomad_setup): id = nomad_setup.job.get_allocations("example")[0]["ID"] assert isinstance(nomad_setup.allocation.get_allocation(id), dict) == True ``` -------------------------------- ### Check Job Existence and Get Job ID Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Check if a job exists in Nomad and retrieve its ID. ```python "example" in n.jobs j = n.jobs["example"]["ID"] ``` -------------------------------- ### Initialize Nomad Client for HTTPS with Verification Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance. Enable SSL verification and set a timeout. ```python # For HTTPS Nomad instances with non-self-signed SSL certificates n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=True) ``` -------------------------------- ### Get Allocation Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/allocation.md Reads information about a specific allocation. This is useful for monitoring the status and details of a running task. ```APIDOC ## GET /allocation/{allocation_id} ### Description Reads information about a specific allocation. ### Method GET ### Endpoint /allocation/{allocation_id} ### Parameters #### Path Parameters - **allocation_id** (string) - Required - The ID of the allocation to retrieve. ### Response #### Success Response (200) - **allocation** (object) - Details of the allocation. ### Request Example ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') allocation = my_nomad.allocation.get_allocation('32c54571-fb79-97d2-ee38-16673bab692c') print (allocation) ``` ``` -------------------------------- ### Get All Jobs Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Lists all jobs registered with Nomad. This method returns a list of jobs and can raise BaseNomadException or URLNotFoundNomadException. ```python def get_jobs(self): """ Lists all the jobs registered with Nomad. https://www.nomadproject.io/docs/http/jobs.html returns: list raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException """ return self.request(method="get").json() ``` -------------------------------- ### Initialize Nomad Client with Namespace and Token Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance, specifying a namespace and an ACL token. SSL verification is disabled. ```python # For HTTPS Nomad instances with namespace and acl token n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=False, namespace='Namespace-example',token='3f4a0fcd-7c42-773c-25db-2d31ba0c05fe') ``` -------------------------------- ### Get Length of Entity Iterable Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Returns the number of items in the entity iterable. This is achieved by calling get_jobs and returning its length. ```python len(n.endpoint) ``` ```python def __len__(self): jobs = self.get_jobs() return len(jobs) ``` -------------------------------- ### Initialize Nomad Client Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/client.md Instantiate the Nomad client object to interact with the API. Ensure the host IP address is correctly set to the target Nomad client. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') ``` -------------------------------- ### Get Specific Allocation Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/allocation.md Retrieves information about a specific allocation using its ID. Requires the nomad library and a Nomad client instance. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') allocation = my_nomad.allocation.get_allocation('32c54571-fb79-97d2-ee38-16673bab692c') print (allocation) ``` -------------------------------- ### Initialize Nomad Client for HTTPS with Custom Certificate Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance with a custom certificate file. SSL verification is enabled. ```python # For HTTPS Nomad instances with self-signed SSL certificates that must validate with cert n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=True, cert="/path/to/certfile") # See http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification ``` -------------------------------- ### Configure Nomad Client via Environment Variables Source: https://github.com/jrxfive/python-nomad/blob/master/docs/index.md Configure the Nomad client using environment variables for address, namespace, token, and region. This unifies configuration with Nomad CLI tools. ```bash NOMAD_ADDR=http://127.0.0.1:4646 NOMAD_NAMESPACE=default NOMAD_TOKEN=xxxx-xxxx-xxxx-xxxx NOMAD_REGION=us-east-1a ``` -------------------------------- ### Update Existing Job Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md This endpoint registers a new job or updates an existing job. Refer to the 'Create New Job' documentation for examples. ```APIDOC ## Update Existing Job ### Description Registers a new job or updates an existing job. ### Method PUT ### Endpoint /v1/jobs/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The ID of the job to update. ### Request Body (Job definition in HCL or JSON format) ### Request Example (See 'Create New Job' example) ### Response #### Success Response (200) (Job registration confirmation) #### Response Example (Job registration confirmation) ``` -------------------------------- ### Parsed Job Dictionary Structure Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/jobs.md Example structure of a Python dictionary representing a parsed Nomad job. This is the output of a successful `nomad_client.jobs.parse()` call. ```python {'AllAtOnce': None, 'Constraints': None, 'CreateIndex': None, 'Datacenters': ['dc1'], 'Dispatched': False, 'ID': 'example', 'JobModifyIndex': None, 'Meta': None, 'Migrate': {'HealthCheck': 'checks', 'HealthyDeadline': 300000000000, 'MaxParallel': 1, 'MinHealthyTime': 10000000000}, 'ModifyIndex': None, 'Name': 'example', 'Namespace': None, 'ParameterizedJob': None, 'ParentID': None, 'Payload': None, 'Periodic': None, 'Priority': None, 'Region': None, 'Reschedule': None, 'Stable': None, 'Status': None, 'StatusDescription': None, 'Stop': None, 'SubmitTime': None, 'TaskGroups': [{'Constraints': None, 'Count': 1, 'EphemeralDisk': {'Migrate': None, 'SizeMB': 300, 'Sticky': None}, 'Meta': None, 'Migrate': None, 'Name': 'cache', 'ReschedulePolicy': None, 'RestartPolicy': {'Attempts': 2, 'Delay': 15000000000, 'Interval': 1800000000000, 'Mode': 'fail'}, 'Tasks': [{'Artifacts': None, 'Config': {'image': 'redis:3.2', 'port_map': [{'db': 6379}]}, 'Constraints': None, 'DispatchPayload': None, 'Driver': 'docker', 'Env': None, 'KillSignal': '', 'KillTimeout': None, 'Leader': False, 'LogConfig': None, 'Meta': None, 'Name': 'redis', 'Resources': {'CPU': 500, 'DiskMB': None, 'IOPS': None, 'MemoryMB': 256, 'Networks': [{'CIDR': '', 'Device': '', 'DynamicPorts': [{'Label': 'db', 'Value': 0}], 'IP': '', 'MBits': 10, 'ReservedPorts': None}]}, 'Services': [{'AddressMode': '', 'CanaryTags': None, 'CheckRestart': None, 'Checks': [{'AddressMode': '', 'Args': None, 'CheckRestart': None, 'Command': '', 'GRPCService': '', 'GRPCUseTLS': False, 'Header': None, 'Id': '', 'InitialStatus': '', 'Interval': 10000000000, 'Method': '', 'Name': 'alive', 'Path': '', 'PortLabel': '', 'Protocol': '', 'TLSSkipVerify': False, 'Timeout': 2000000000, 'Type': 'tcp'}], 'Id': '', 'Name': 'redis-cache', ``` -------------------------------- ### Create Job Plan Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Use this snippet to create a job plan by invoking a dry-run of the scheduler for a given job definition. Ensure the 'nomad' library is imported and a Nomad client is initialized. ```python import nomad job = {'Job': {'AllAtOnce': None, 'Constraints': None, 'CreateIndex': None, 'Datacenters': ['dc1'], 'ID': 'example', 'JobModifyIndex': None, 'Meta': None, 'ModifyIndex': None, 'Name': 'example', 'Namespace': None, 'ParameterizedJob': None, 'ParentID': None, 'Payload': None, 'Periodic': None, 'Priority': None, 'Region': None, 'Stable': None, 'Status': None, 'StatusDescription': None, 'Stop': None, 'SubmitTime': None, 'TaskGroups': [{'Constraints': None, 'Count': 1, 'EphemeralDisk': {'Migrate': None, 'SizeMB': 300, 'Sticky': None}, 'Meta': None, 'Name': 'cache', 'RestartPolicy': {'Attempts': 10, 'Delay': 25000000000, 'Interval': 300000000000, 'Mode': 'delay'}, 'Tasks': [{'Artifacts': None, 'Config': {'image': 'redis:3.2', 'port_map': [{'db': 6379}]}, 'Constraints': None, 'DispatchPayload': None, 'Driver': 'docker', 'Env': None, 'KillTimeout': None, 'Leader': False, 'LogConfig': None, 'Meta': None, 'Name': 'redis', 'Resources': {'CPU': 500, 'DiskMB': None, 'IOPS': None, 'MemoryMB': 256, 'Networks': [{'CIDR': '', 'Device': '', 'DynamicPorts': [{'Label': 'db', 'Value': 0}], 'IP': '', 'MBits': 10, 'ReservedPorts': None}]}, 'Services': [{'AddressMode': '', 'CheckRestart': None, 'Checks': [{'Args': None, 'CheckRestart': None, 'Command': '', 'Header': None, 'Id': '', 'InitialStatus': '', 'Interval': 10000000000, 'Method': '', 'Name': 'alive', 'Path': '', 'PortLabel': '', 'Protocol': '', 'TLSSkipVerify': False, 'Timeout': 2000000000, 'Type': 'tcp'}], 'Id': '', 'Name': 'global-redis-check', 'PortLabel': 'db', 'Tags': ['global', 'cache']}], 'ShutdownDelay': 0, 'Templates': None, 'User': '', 'Vault': None}], 'Update': None}], 'Type': 'service', 'Update': {'AutoRevert': False, 'Canary': 0, 'HealthCheck': None, 'HealthyDeadline': 180000000000, 'MaxParallel': 1, 'MinHealthyTime': 10000000000, 'Stagger': None}, 'VaultToken': None, 'Version': None}} my_nomad = nomad.Nomad(host='192.168.33.10') plan = my_nomad.job.plan_job("example", job) ``` -------------------------------- ### Initialize Nomad Client for HTTP Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTP Nomad instance. Set a timeout for requests. ```python import nomad # For HTTP Nomad instances n = nomad.Nomad(host="172.16.100.10", timeout=5) ``` -------------------------------- ### Get Specific Item from Entity Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Retrieves a specific item from the entity by ID or Name. Raises KeyError if the item is not found or if URLNotFoundNomadException occurs. ```python n.endpoint["something"] ``` ```python def __getitem__(self, item): try: jobs = self.get_jobs() for j in jobs: if j["ID"] == item: return j if j["Name"] == item: return j else: raise KeyError except nomad.api.exceptions.URLNotFoundNomadException: raise KeyError ``` -------------------------------- ### Promote All Task Groups in a Deployment Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployment.md Initiates the promotion of all task groups within a deployment. Use this when canaries are healthy and the rolling upgrade should proceed. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') promote = my_nomad.deployment.promote_deployment_all("52c47d49-eefa-540f-f0f1-d25ba298c87f",True) ``` -------------------------------- ### Mocking Enterprise Endpoints Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Demonstrates how to mock responses for enterprise Nomad endpoints, such as namespace and sentinel, for testing purposes. ```python import tests.common as common import pytest import responses ``` -------------------------------- ### List Allocations for a Deployment Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployment.md Fetches a list of allocations associated with a given deployment ID. Useful for monitoring or debugging. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') allocations = my_nomad.deployment.get_deployment_allocations('a8061a1c-d4c9-2a7d-a4b2-932c8f83e587') for allocation in allocations: print (allocation) ``` -------------------------------- ### Create Policy Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/sentinel.md Creates a new Sentinel policy. ```APIDOC ## Create Policy ### Description Create a policy. ### Method POST ### Endpoint /sentinel/policy ### Parameters #### Request Body - **Name** (string) - Required - The name of the policy. - **Description** (string) - Optional - A description of the policy. - **Scope** (string) - Required - The scope of the policy (e.g., "submit-job"). - **EnforcementLevel** (string) - Required - The enforcement level of the policy (e.g., "advisory", "hard-mandatory"). - **Policy** (string) - Required - The Sentinel policy code. ### Request Example ```json { "Name": "my-policy", "Description": "This is a great policy", "Scope": "submit-job", "EnforcementLevel": "advisory", "Policy": "main = rule { true }" } ``` ### Response #### Success Response (200) - **ID** (string) - The unique identifier of the created policy. - **Name** (string) - The name of the policy. - **Description** (string) - A description of the policy. - **Scope** (string) - The scope of the policy. - **EnforcementLevel** (string) - The enforcement level of the policy. - **Policy** (string) - The Sentinel policy code. - **CreateTime** (string) - The timestamp when the policy was created. - **CreateBy** (string) - The user or system that created the policy. - **UpdateTime** (string) - The timestamp when the policy was last updated. - **UpdateBy** (string) - The user or system that last updated the policy. #### Response Example ```json { "ID": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "Name": "my-policy", "Description": "This is a great policy", "Scope": "submit-job", "EnforcementLevel": "advisory", "Policy": "main = rule { true }", "CreateTime": "2023-10-27T10:00:00Z", "CreateBy": "nomad", "UpdateTime": "2023-10-27T10:00:00Z", "UpdateBy": "nomad" } ``` ``` -------------------------------- ### List Job Versions Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Fetches all versions associated with a given job. Iterates through the 'Versions' key in the response. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') versions = my_nomad.job.get_versions("example") for version in versions["Versions"]: print (version) ``` -------------------------------- ### Parse Nomad Job Definition Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/jobs.md Example of a Python dictionary representing a Nomad job definition. This structure is used when creating or updating jobs via the API. ```python { 'Datacenters': ['dc1'], 'Name': 'my-job', 'Type': 'service', 'Update': { 'AutoRevert': False, 'Canary': 0, 'HealthCheck': None, 'HealthyDeadline': 180000000000, 'MaxParallel': 1, 'MinHealthyTime': 10000000000, 'ProgressDeadline': None, 'Stagger': None }, 'VaultToken': None, 'Version': None } ``` -------------------------------- ### Set and Get Session Token Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/acl.md Manage the token used for Nomad authentication after it has been created. This snippet demonstrates setting a token and then retrieving the currently set token. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') bootstrap = my_nomad.acl.generate_bootstrap() print (bootstrap["SecretID"]) 10f0cf19-2c8c-cb4b-721a-fda2a388740b my_nomad.set_token(bootstrap["SecretID"]) print (my_nomad.get_token()) ``` -------------------------------- ### List Allocations for Deployment Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployment.md Lists the allocations created or modified for a given deployment. ```APIDOC ## List Allocations for Deployment ### Description Lists the allocations created or modified for the given deployment. ### Method GET ### Endpoint /v1/deployment/{deploymentID}/allocations ### Parameters #### Path Parameters - **deploymentID** (string) - Required - The ID of the deployment. ``` -------------------------------- ### List Job Deployments Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Retrieves a list of all deployments for a specific job. Deployments manage job updates. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') deployments = my_nomad.job.get_deployments("example") for deployment in deployments: print (deployment) ``` -------------------------------- ### Set Job Stability Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Sets the stability of a job to a specific version. This operation is useful for controlling job rollout and rollback behavior. The 'nomad' library must be installed. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') current_job_version = my_nomad.job.get_deployment("example")["JobVersion"] my_nomad.job.stable_job("example", current_job_version, True) ``` -------------------------------- ### Initiate Garbage Collection Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/system.md Initializes an asynchronous garbage collection process for jobs, evaluations, allocations, and nodes. Requires the Nomad client to be initialized. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') my_nomad.system.initiate_garbage_collection() ``` -------------------------------- ### Get Filtered Event Stream Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/event.md Configures an event stream with specific filtering criteria, including an index, namespace, and topics of interest. This allows for more targeted event monitoring. ```python import nomad n = nomad.Nomad() stream, stream_exit_event, events = n.event.stream.get_stream(index=0, topic={"Node": "*"}, namespace="not-default") stream.start() while True: event = events.get() print(event) events.task_done() ``` -------------------------------- ### Create Nomad ACL Policy Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/acl.md Use this snippet to create a new ACL policy in Nomad. Ensure you have the Nomad Python client installed and provide valid host and token. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10', token='10f0cf19-2c8c-cb4b-721a-fda2a388740b') policy = { "Name": "my-policy", "Description": "This is a great policy", "Rules": "" } my_nomad.acl.create_policy("my-policy", policy) ``` -------------------------------- ### Initialize Nomad Client for HTTPS without Certificate Verification Source: https://github.com/jrxfive/python-nomad/blob/master/README.md Initialize the Nomad client for connecting to an HTTPS Nomad instance without validating the SSL certificate. Set a timeout. ```python # For HTTPS Nomad instances with self-signed SSL certificates and no validate the cert n = nomad.Nomad(host="172.16.100.10", secure=True, timeout=5, verify=False) ``` -------------------------------- ### Revert Job to Older Version Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Reverts a job to a previous version. This requires knowing the current job version and the desired prior version. Ensure the 'nomad' library is installed and configured. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') current_job_version = my_nomad.job.job.get_deployment("example")["JobVersion"] prior_job_version = current_job_version - 1 my_nomad.job.revert_job("example", prior_job_version, current_job_version) ``` -------------------------------- ### List Namespaces Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/namespaces.md This endpoint lists all namespaces within the Nomad environment. Requires Nomad Enterprise Edition. ```APIDOC ## GET /namespaces ### Description This endpoint lists all namespaces. ### Method GET ### Endpoint /namespaces ### Parameters ### Request Example ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') namespaces = my_nomad.namespaces.get_namespaces() for namespace in namespaces: print (token['Name']) ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Generate Bootstrap Token Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/acl.md Use this snippet to bootstrap the ACL system and obtain the initial management token. This operation can only be performed once until a reset. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') bootstrap = my_nomad.acl.generate_bootstrap() print (bootstrap["SecretID"]) 10f0cf19-2c8c-cb4b-721a-fda2a388740b ``` -------------------------------- ### List Nomad Namespaces Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/namespaces.md Use this snippet to retrieve a list of all namespaces configured in your Nomad environment. Ensure you have the 'nomad' Python library installed and are using Nomad Enterprise Edition version 0.7.0 or later. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') namespaces = my_nomad.namespaces.get_namespaces() for namespace in namespaces: print (token['Name']) ``` -------------------------------- ### Instantiate New Endpoint Object Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md When adding a new endpoint, instantiate a new object for it and assign it as an attribute in the main class. This prepares the object for use. ```python # Instantiate a new object and make it an attribute self._jobs = api.Jobs(**self.requester_settings) self._job = api.Job(**self.requester_settings) self._nodes = api.Nodes(**self.requester_settings) self._node = api.Node(**self.requester_settings) self._allocations = api.Allocations(**self.requester_settings) self._allocation = api.Allocation(**self.requester_settings) self._evaluations = api.Evaluations(**self.requester_settings) self._evaluation = api.Evaluation(**self.requester_settings) self._agent = api.Agent(**self.requester_settings) self._client = api.Client(**self.requester_settings) self._deployments = api.Deployments(**self.requester_settings) self._deployment = api.Deployment(**self.requester_settings) self._regions = api.Regions(**self.requester_settings) self._status = api.Status(**self.requester_settings) self._system = api.System(**self.requester_settings) self._operator = api.Operator(**self.requester_settings) self._validate = api.Validate(**self.requester_settings) self._namespaces = api.Namespaces(**self.requester_settings) self._namespace = api.Namespace(**self.requester_settings) self._acl = api.Acl(**self.requester_settings) self._sentinel = api.Sentinel(**self.requester_settings) self._metrics = api.Metrics(**self.requester_settings) self._ = api.(**self.requester_settings) ``` -------------------------------- ### Read Deployment Information Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployment.md Retrieves details for a specific deployment using its ID. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') deployment = my_nomad.deployment.get_deployment('a8061a1c-d4c9-2a7d-a4b2-932c8f83e587') print (deployment) ``` -------------------------------- ### Entity Request Method Source: https://github.com/jrxfive/python-nomad/blob/master/CONTRIBUTING.md Demonstrates how to add an entity by calling the inherited request method. Query string parameters are passed via the `params` keyword argument, and payloads via the `json` keyword argument. The HTTP method is specified using the `method` keyword argument. All requests return a `requests.Response` object or raise specific exceptions on failure. ```APIDOC ## Entity Request Method ### Description This method is used to make requests to Nomad entities. It supports passing query string parameters and JSON payloads, and allows specifying the HTTP method. ### Method GET, POST, PUT, DELETE (specified via `method` keyword argument) ### Parameters - **route_parts**: Variable arguments that form part of the URL path. - **params** (dict) - Optional - Query string parameters. - **json** (dict) - Optional - JSON payload for the request. - **method** (str) - Required - The HTTP method (e.g., "get", "post"). ### Returns - `requests.Response` object on success. ### Raises - `BaseNomadException` (status code 500) - `URLNotFoundNomadException` (status code 404) - `URLNotAuthorizedNomadException` (status code 403) - `BadRequestNomadException` (status code 400) ``` -------------------------------- ### List all Servers Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/agent.md Lists the known server nodes. Client nodes use this endpoint to query an agent in client mode for its list of known servers, which helps in dequeueing work and keeping configurations up to date. ```APIDOC ## GET /agent/servers ### Description This endpoint lists the known server nodes. The servers endpoint is used to query an agent in client mode for its list of known servers. Client nodes register themselves with these server addresses so that they may dequeue work. The servers endpoint can be used to keep this configuration up to date if there are changes in the cluster. ### Method GET ### Endpoint /agent/servers ### Response #### Success Response (200) - **servers** (array) - A list of known server addresses. ### Request Example ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') servers = my_nomad.agent.get_servers() for server in servers: print (server) ``` ``` -------------------------------- ### Create Job Plan Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md This endpoint invokes a dry-run of the scheduler for the job. It allows you to plan a job without actually deploying it. ```APIDOC ## Create Job Plan ### Description This endpoint invokes a dry-run of the scheduler for the job. ### Method POST ### Endpoint /v1/jobs/{job_id}/plan ### Parameters #### Path Parameters - **job_id** (string) - Required - The ID of the job to plan. ### Request Body - **job** (object) - Required - The job specification to plan. ### Request Example ```json { "Job": { "AllAtOnce": null, "Constraints": null, "CreateIndex": null, "Datacenters": ["dc1"], "ID": "example", "JobModifyIndex": null, "Meta": null, "ModifyIndex": null, "Name": "example", "Namespace": null, "ParameterizedJob": null, "ParentID": null, "Payload": null, "Periodic": null, "Priority": null, "Region": null, "Stable": null, "Status": null, "StatusDescription": null, "Stop": null, "SubmitTime": null, "TaskGroups": [ { "Constraints": null, "Count": 1, "EphemeralDisk": { "Migrate": null, "SizeMB": 300, "Sticky": null }, "Meta": null, "Name": "cache", "RestartPolicy": { "Attempts": 10, "Delay": 25000000000, "Interval": 300000000000, "Mode": "delay" }, "Tasks": [ { "Artifacts": null, "Config": { "image": "redis:3.2", "port_map": [ { "db": 6379 } ] }, "Constraints": null, "DispatchPayload": null, "Driver": "docker", "Env": null, "KillTimeout": null, "Leader": false, "LogConfig": null, "Meta": null, "Name": "redis", "Resources": { "CPU": 500, "DiskMB": null, "IOPS": null, "MemoryMB": 256, "Networks": [ { "CIDR": "", "Device": "", "DynamicPorts": [ { "Label": "db", "Value": 0 } ], "IP": "", "MBits": 10, "ReservedPorts": null } ] }, "Services": [ { "AddressMode": "", "CheckRestart": null, "Checks": [ { "Args": null, "CheckRestart": null, "Command": "", "Header": null, "Id": "", "InitialStatus": "", "Interval": 10000000000, "Method": "", "Name": "alive", "Path": "", "PortLabel": "", "Protocol": "", "TLSSkipVerify": false, "Timeout": 2000000000, "Type": "tcp" } ], "Id": "", "Name": "global-redis-check", "PortLabel": "db", "Tags": [ "global", "cache" ] } ], "ShutdownDelay": 0, "Templates": null, "User": "", "Vault": null } ], "Update": null } ], "Type": "service", "Update": { "AutoRevert": false, "Canary": 0, "HealthCheck": null, "HealthyDeadline": 180000000000, "MaxParallel": 1, "MinHealthyTime": 10000000000, "Stagger": null }, "VaultToken": null, "Version": null } } ``` ### Response #### Success Response (200) - **Plan** (object) - The job plan details. #### Response Example ```json { "Plan": { "ExecGroups": [], "Resources": {}, "Stop": null, "SubmitTime": 1678886400000000000, "TaskGroups": [ { "Name": "cache", "Tasks": [ { "Name": "redis", "Resources": { "CPU": 500, "MemoryMB": 256 } } ] } ], "UpdateInfo": {} } } ``` ``` -------------------------------- ### Read Namespace Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/namespace.md Retrieves information about a specific namespace. ```APIDOC ## Read Namespace ### Description Reads information about a specific namespace. ### Method GET ### Endpoint /v1/namespace/{namespace_name} ### Parameters #### Path Parameters - **namespace_name** (string) - Required - The name of the namespace to read. ### Request Example (No request body or specific parameters other than path parameter) ### Response #### Success Response (200) (No specific response schema provided in source) #### Response Example (No specific response example provided in source) ``` -------------------------------- ### Create or Update Nomad Variable Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/variable.md This snippet demonstrates how to create or update a variable. It shows initializing the client, creating a variable with a path, and then creating another variable with a payload. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') job = my_nomad.variable.create_variable("path_to_variable") payload = { "Items": {"user": "test", "password": "test123"}, } my_nomad.variable.create_variable("variable_path", payload) ``` -------------------------------- ### List Job Allocations Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/job.md Retrieves all allocations for a specific job. Each allocation represents a running task. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') allocations = my_nomad.job.get_allocations("example") for allocation in allocations: print (allocation) ``` -------------------------------- ### List All Jobs Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/jobs.md Retrieves a list of all jobs currently registered in the Nomad system. Requires the Nomad client to be initialized with the host address. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') jobs = my_nomad.jobs.get_jobs() for job in jobs: print (job) ``` -------------------------------- ### List Node Allocations Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/node.md Lists all allocations for a given node, including their status and resource usage. Requires the node ID. ```APIDOC ## List Node Allocations ### Description Lists all of the allocations for the given node. This can be used to determine what allocations have been scheduled on the node, their current status, and the values of dynamically assigned resources, like ports. ### Method GET ### Endpoint /v1/node/{node_id}/allocations ### Parameters #### Path Parameters - **node_id** (string) - Required - The ID of the node whose allocations to list. ``` -------------------------------- ### Promote Specific Task Groups in a Deployment Source: https://github.com/jrxfive/python-nomad/blob/master/docs/api/deployment.md Promotes a specified list of task groups for a deployment. Useful for phased rollouts. ```python import nomad my_nomad = nomad.Nomad(host='192.168.33.10') promote = my_nomad.deployment.promote_deployment_groups("52c47d49-eefa-540f-f0f1-d25ba298c87f",groups=['task1','task2']) ```