6 minutes read

Apache Spark Demo

Use the API and Python to automate the provisioning of an Apache Spark cluster on Bare Metal Cloud.
Marko Aleksic
· Updated
November 27, 2026

Use the Bare Metal Cloud (BMC) API and Python to automate Apache Spark cluster deployment. This tutorial shows how to provision three BMC servers and configure them as the Spark master and worker nodes.

The code examples are available on the GitHub BMC Spark Demo repository. The tutorial highlights specific code segments to complete the deployment steps.

Prerequisites

Log in to the BMC portal (if you are a new user, set up your account and create API credentials). SSH access to the provisioned servers.

Step 1: Get Access Token

The following Python function generates the access token for the API:

def get_access_token(client_id: str, client_secret: str) -> str:
"""Retrieves an access token from BMC auth by using the client ID and the 
client Secret."""
    credentials = "%s:%s" % (client_id, client_secret)
    basic_auth = standard_b64encode(credentials.encode("utf-8"))
    response = requests.post(' https://api.phoenixnap.com/bmc/v0/servers',
        headers={
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic %s' % basic_auth.decode("utf-8")},
        data={'grant_type': 'client_credentials'})
    if response.status_code != 200:
        raise Exception('Error: {}. {}'.format(response.status_code, response.json()))
    return response.json()['access_token']
Code language: Python (python)

It sends the credentials to the authentication endpoint and returns the access token.

Step 2: Create BMC Server Instances

Send a POST request to the /servers endpoint to provision the servers.

The following function submits a creation request:

def __do_create_server(session, server):
    response = session.post('https://api.phoenixnap.com/bmc/v0/servers'),
                            data=json.dumps(server))
    if response.status_code != 200:
        print("Error creating server: {}".format(json.dumps(response.json())))
    else:
        print("{}".format(json.dumps(response.json())))
        return response.json()
Code language: Python (python)

Each request must include the required parameters, such as the location, server type, and operating system. Their configuration is specified in the server-settings.conf file.

The example configuration creates three s1.c1.small servers in Phoenix. Replace the example SSH key with your public key.

{
  "ssh-key" : "ssh-rsa [SSK_KEY]",
  "servers_quantity" : 3,
  "type" : "s1.c1.small",
  "hostname" : "spark",
  "description" : "spark",
  "public" : true,
  "location" : "PHX",
  "os" : "ubuntu/bionic"
}
Code language: JSON / JSON with Comments (json)

Confirm the selected server type and operating system are available before running the script.

After submitting the requests, the script checks the server status until provisioning is complete and the servers are powered on.

Example output:

Retrieving token 
Successfully retrieved API token 
Creating servers... 
Server created, provisioning spark-1... 
Server created, provisioning spark-0... 
Server created, provisioning spark-2... 
Waiting for servers to be provisioned...Code language: plaintext (plaintext)

The complete output includes each server's data.

Step 3: Configure Apache Spark Cluster

After the servers are provisioned, the Python script connects to each server over SSH using its public IP address. It then installs the Java Development Kit (JDK), Scala, Git, and Apache Spark on the Ubuntu servers.

Step 3.1: Prepare Each Server

Execute the all_hosts.sh script on every server. The script downloads and installs the required software and configures environment variables required to run Spark.

The first server to finish provisioning is assigned as the Spark master. The remaining servers become worker nodes.

The following function illustrates how the script identifies and assigns the master node:

def wait_server_ready(function_scheduler, server_data):
    json_server = bmc_api.get_server(REQUEST, server_data['id'])
    if json_server['status'] == "creating":
        main_scheduler.enter(2, 1, wait_server_ready, (function_scheduler, server_data))
    elif json_server['status'] == "powered-on" and not data['has_a_master_server']:
        server_data['status'] = json_server['status']
        server_data['master'] = True
        server_data['joined'] = True
        data['has_a_master_server'] = True
        data['master_ip'] = json_server['publicIpAddresses'][0]
        data['master_hostname'] = json_server['hostname']
        print("ASSIGNED MASTER SERVER: {}".format(data['master_hostname']))
Code language: Python (python)

Step 3.2: Configure the Master Node

Execute the master_host.sh script on the selected master server:

#!/bin/bash
echo "Setting up master node"
/opt/spark/sbin/start-master.sh
Code language: Bash (bash)

The script starts the Spark master service.

Step 3.3: Configure Worker Nodes

Once the master is configured, execute the worker configuration script on the remaining servers. The script adds the master to the worker's /etc/hosts file and starts the worker service.

Example worker_host.sh file:

#!/bin/bash
echo "Setting up master node on /etc/hosts"
echo "$1 $2 $2" | sudo tee -a /etc/hosts
echo "Starting worker node"
echo "Joining worker node to the cluster"
/opt/spark/sbin/start-slave.sh spark://$2:7077
Code language: Bash (bash)

The script uses the supplied arguments to configure the host entry and connect the worker to the Spark master.

Example output:

ASSIGNED MASTER SERVER: spark-2
Running all_host.sh script on spark-2
Setting up /etc/hosts
Installing jdk, scala and git
Downloading spark-2.4.5
Unzipping spark-2.4.5
Setting up environment variables
Running master_host.sh script on spark-2
Setting up master node
starting org.apache.spark.deploy.master.Master, logging to /opt/spark/logs/spark-ubuntu-org.apache.spark.deploy.master.Master-1-spark-2.out
Master host installed
Running all_host.sh script on spark-0
Setting up /etc/hosts
Installing jdk, scala and git
Downloading spark-2.4.5
Unzipping spark-2.4.5
Setting up environment variables
Running all_host.sh script on spark-1
Setting up /etc/hosts
Installing jdk, scala and git
Downloading spark-2.4.5
Unzipping spark-2.4.5
Setting up environment variables
Running slave_host.sh script on spark-0
Setting up master node on /etc/hosts
Starting worker node
Joining worker node to the cluster
starting org.apache.spark.deploy.worker.Worker, logging to /opt/spark/logs/spark-ubuntu-org.apache.spark.deploy.worker.Worker-1-spark-0.out
Running slave_host.sh script on spark-1
Setting up master node on /etc/hosts
Starting worker node
Joining worker node to the cluster
starting org.apache.spark.deploy.worker.Worker, logging to /opt/spark/logs/spark-ubuntu-org.apache.spark.deploy.worker.Worker-1-spark-1.out
Setup servers done
Master node UI: http://[MASTER_PUBLIC_IP]:8080Code language: plaintext (plaintext)

The output shows the master and worker configuration process.

Step 4: Access Apache Spark Dashboard

After the setup completes, the Python script outputs the Spark master dashboard URL.

Open the generated URL in a browser to access the dashboard. The default port shown in the example is 8080; use the actual master server's public IP address.

Ensure the required network access is configured before attempting to connect to the dashboard.