IBM Cloud Global

 View Only

List it, Check it : Python powered IBM Cloud Load Balancer Management!

By Lavisha Bhatia posted 2 days ago

  

Managing IBM Cloud Load Balancers (CLBs) efficiently is key to ensuring optimal performance and uptime for your applications.

Imagine having a quick way to list all your CLBs and instantly check the status of any specific one without sifting through dashboards or logs. That’s exactly what Python brings to the table—a streamlined, automated approach to managing your load balancers.

In this blog, we’ll explore a simple yet powerful Python script to automate two essential tasks:

1.⁠ ⁠Listing all Cloud Load Balancers in your IBM Cloud account.

2.⁠ ⁠Checking the status of a specific load balancer with ease.

Whether you're troubleshooting, monitoring, or just curious about your CLB setup, this script empowers you to gain insights effortlessly. Plus, it’s designed with simplicity and usability in mind, making it a handy tool for both beginners and seasoned cloud professionals.

Ready to level up your IBM Cloud management game? Let’s get started!

Note: If you have a VPC Load Balancer and wondering if you can have same for that too, do not worry!
Check this out:
https://community.ibm.com/community/user/cloud/blogs/lavisha-bhatia/2024/11/18/ibm-cloud-vpc-load-balancer-management

⁠Listing all Cloud Load Balancers in your IBM Cloud account

import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import os

# IBM Classic Infrastructure credentials

# Fetch username and API key from environment variables
username = os.getenv("USERNAME")
api_key = os.getenv("API_KEY")

# Ensure both environment variables are available
if not username or not api_key:
    print("Error: Please ensure USERNAME and API_KEY environment variables are set.")
    sys.exit(1)

# API endpoint for the Classic Infrastructure Load Balancer
URL = "https://api.softlayer.com/rest/v3/SoftLayer_Network_LBaaS_LoadBalancer/getAllObjects"

def get_lb_status():
    # Make the API request
    response = requests.get(URL, auth=HTTPBasicAuth(username, api_key))

    # Check if the response is successful
    if response.status_code == 200:
        # Parse the response to JSON
        load_balancers = response.json()
        for lb in load_balancers:
            print(f"Load Balancer ID: {lb['id']}")
            print(f"Name: {lb['name']}")
            print(f"DNS Address: {lb['address']}")
            print (f"Location: {lb['datacenter']['longName']}")
            print(f"Operating Status: {lb['operatingStatus']}")
            print(f"Provisioning Status: {lb['provisioningStatus']}")
            print("-" * 40)
    else:
        print(f"Failed to fetch data, status code: {response.status_code}")
        print(response.text)

# Fetch and print the LB status
get_lb_status()

Usage example:

You need to set the environment variables USERNAME and API_KEY on your system. Here’s how to do it depending on your OS:

  • For Linux/macOS:
    You can set the environment variables in your shell (e.g., bash, zsh):
export USERNAME="your_username"
export API_KEY="your_api_key"

To make these variables persist across sessions, you can add the lines above to your shell configuration file (~/.bashrc, ~/.zshrc, etc.).

  • For Windows:
    You can set environment variables in the Command Prompt or PowerShell:
    setx USERNAME “your_username”
    setx API_KEY “your_api_key”


After setting the variables, restart your terminal or script to have them take effect.
Once setting the variables is done, you just need to run command : <python3 List_CLBs.py> (assuming that above code file name is "List_CLBs.py")

Sample output :

Load Balancer ID: 123456
Name: test-clb1-dal10
DNS Address: test-clb1-dal10-987654-dal10.clb.appdomain.cloud
Location: Dallas 10
Operating Status: ONLINE
Provisioning Status: ACTIVE
----------------------------------------
Load Balancer ID: 456789
Name: test-clb2-dal13
DNS Address: test-clb2-dal13-987654-dal13.clb.appdomain.cloud
Location: Dallas 13
Operating Status: ONLINE
Provisioning Status: ACTIVE
----------------------------------------
Load Balancer ID: 678906
Name: test-clb3-dal12
DNS Address: test-clb3-dal12-987654-dal12.clb.appdomain.cloud
Location: Dallas 12
Operating Status: ONLINE
Provisioning Status: ACTIVE
----------------------------------------

Checking the status of a specific load balancer with ease

import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import os


# IBM Classic Infrastructure credentials

# Fetch username and API key from environment variables
username = os.getenv("USERNAME")
api_key = os.getenv("API_KEY")

# Ensure both environment variables are available
if not username or not api_key:
    print("Error: Please ensure USERNAME and API_KEY environment variables are set.")
    sys.exit(1)

# API endpoint for the Classic Infrastructure Load Balancer
URL = "https://api.softlayer.com/rest/v3/SoftLayer_Network_LBaaS_LoadBalancer/getAllObjects"

def get_lb_status(lb_id):
    
    # Make the API request
    response = requests.get(URL, auth=HTTPBasicAuth(username, api_key))
    
    try:
        
        # Check if the response is successful
        if response.status_code == 200:
            # Parse the response to JSON
            load_balancers = response.json()
        
            for lb in load_balancers:
                
                if lb['id'] == lb_id:
                 # Output the relevant details for the matched load balancer

                    print(f"Load Balancer ID: {lb['id']}")
                    print(f"Name: {lb['name']}")
                    print(f"DNS Address: {lb['address']}")
                    print (f"Location: {lb['datacenter']['longName']}")
                    print(f"Operating Status: {lb['operatingStatus']}")
                    print(f"Provisioning Status: {lb['provisioningStatus']}")
                    
                    return # Exit after printing the details for the matching LB
           
            # If the LB ID wasn't found
            print("No load balancer found with the given ID.")
        
        else:
            print(f"Failed to fetch data, status code: {response.status_code}")
            print(response.text)
    
        
    except Exception as e:
        print(f"An error occurred: {e}")

# Fetch and print the LB status
lb_id = int ('LB_ID')  # Ensure lb_id is an integer or convert it appropriately
get_lb_status(lb_id)

Usage example:

Same like above you need to set the environment variables USERNAME and API_KEY on your system. 

Provide the LB_ID in the code. 

Once its done, you just need to run command : <python3 List_CLB_status.py> (assuming that above code file name is "List_CLB_status.py")

Sample output :

Load Balancer ID: 123456
Name: test-clb
DNS Address: test-clb-987650-che01.clb.appdomain.cloud
Location: Chennai 1
Operating Status: ONLINE
Provisioning Status: ACTIVE

By leveraging Python for managing IBM Cloud Classic Load Balancers, you can save time, reduce manual effort, and ensure your infrastructure runs smoothly. From listing all your CLBs to checking the status of specific ones, this script provides a simple yet effective way to stay in control of your load balancing setup.

Automation isn’t just a convenience—it’s a necessity in today’s fast-paced cloud environments. With this Python-based approach, you’re taking a step toward smarter, more efficient LB management.

Have questions or suggestions? Share your thoughts in the comments, and let’s continue exploring the power of Python together!

0 comments
10 views

Permalink