Skip to content

Instantly share code, notes, and snippets.

@oxr463
Created January 21, 2021 21:40
Show Gist options
  • Save oxr463/268547a6dca78d1c0feb55a3c28a41df to your computer and use it in GitHub Desktop.
Save oxr463/268547a6dca78d1c0feb55a3c28a41df to your computer and use it in GitHub Desktop.
Iterating through cluster nodes via the Rancher API v3

Rancher Cluster Nodes in Python

Iterating through cluster nodes via the Rancher API v3

Dependencies

Examples

# Ensure the script is executable.
chmod +x nodes.py
# Specify the following environment variables.
API_URL=https://rancher.local/v3 API_USER="token-s1c9p" API_PASSWORD="0a11xq2wh34567dddabc8wr90dfkpbrzkr5kbfq12zjxjlwnnb1gt0" ./nodes.py

License

SPDX-License-Identifier: Apache-2.0

See Also

#!/usr/bin/env python3
# Iterate through cluster nodes via the Rancher API v3
# SPDX-License-Identifier: Apache-2.0
import os
import requests
from requests.auth import HTTPBasicAuth
URL = os.getenv('API_URL') # https://rancher.local/v3
USER = os.getenv('API_USER') # token-s1c9p
PASSWORD = os.getenv('API_PASSWORD') # 0a11xq2wh34567dddabc8wr90dfkpbrzkr5kbfq12zjxjlwnnb1gt0
def _get_request(_request):
_response = requests.get(_request, auth=HTTPBasicAuth(USER,PASSWORD))
return _response
api_response = _get_request(URL)
api_response_json = api_response.json()
#print(api_response_json)
clusters_response = _get_request(URL + '/clusters')
clusters_response_json = clusters_response.json()
#print(clusters_response_json)
def get_cluster_info(cluster):
_cluster_data = dict([
('cluster_id', cluster['id']),
#('friendly_cluster_name', cluster['name']),
('node_count', cluster['nodeCount']),
#('state', cluster['state']),
#('controller_manager', cluster['componentStatuses'][0]['type']),
#('etcd', cluster['componentStatuses'][1]['conditions'][0]['type']),
#('scheduler', cluster['componentStatuses'][2]['conditions'][0]['type']),
])
return _cluster_data
for _cluster in clusters_response_json['data']:
_cluster_info = get_cluster_info(_cluster)
_cluster_node_count = _cluster_info['node_count']
nodes_response = _get_request(URL + '/clusters/' + _cluster_info['cluster_id'] + '/nodes')
nodes_response_json = nodes_response.json()
#print(nodes_response_json)
for _node_count in range(_cluster_node_count):
_node = nodes_response_json['data'][_node_count]
print(_node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment