Last active
March 14, 2019 20:17
-
-
Save asc-adean/3c9611eed10e6433fa439017fcf087ed to your computer and use it in GitHub Desktop.
Kubernetes Discover External IPs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## If running in an RBAC-enabled cluster, the `default` service account in that namespace must have the following role, | |
## taking note to update the namespace: value | |
#--- | |
# apiVersion: rbac.authorization.k8s.io/v1 | |
# kind: Role | |
# metadata: | |
# name: default | |
# namespace: $NAMESPACE | |
# rules: | |
# - apiGroups: [""] | |
# resources: ["services"] | |
# verbs: ["get", "watch", "list"] | |
# - apiGroups: [""] | |
# resources: ["configmaps"] | |
# verbs: ["create", "update", "patch"] | |
# --- | |
# apiVersion: rbac.authorization.k8s.io/v1 | |
# kind: RoleBinding | |
# metadata: | |
# name: default | |
# namespace: $NAMESPACE | |
# roleRef: | |
# apiGroup: rbac.authorization.k8s.io | |
# kind: Role | |
# name: default | |
# subjects: | |
# - kind: ServiceAccount | |
# name: default | |
### Run this in a Cronjob resource like so, the image only needs Python3 and to copy the python code in the Dockerfile | |
### taking note to update the namespace: value again | |
# apiVersion: batch/v1beta1 | |
# kind: CronJob | |
# metadata: | |
# name: info-gatherer | |
# namespace: $NAMESPACE | |
# spec: | |
# schedule: "*/1 * * * *" | |
# jobTemplate: | |
# spec: | |
# template: | |
# spec: | |
# restartPolicy: OnFailure | |
# containers: | |
# - name: info-gatherer | |
# image: homemadeImageWithPython3/info-gatherer:latest | |
# command: ["python"] | |
# args: ["get-k8s-external-ips.py", "--namespace", "$NAMESPACE"] | |
# imagePullPolicy: Always | |
import sys, yaml, json, argparse, requests | |
from requests.packages.urllib3.exceptions import InsecureRequestWarning | |
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--namespace', action="store", default=False, required=True) | |
args = parser.parse_args() | |
token_file = "/var/run/secrets/kubernetes.io/serviceaccount/token" | |
kubernetes_api = "https://kubernetes.default.svc.cluster.local/api/v1/" | |
configmap_name = "external-ips-configmap" | |
try: | |
with open(token_file, "r") as token: | |
data=token.readlines() | |
header = { | |
"Content-Type": "application/json", | |
"Authorization": "Bearer " + data[0] | |
} | |
url = kubernetes_api + "namespaces/" + args.namespace + "/services" | |
req = requests.get(url, headers=header, verify=False) | |
if req.status_code <= 201: | |
service_payload = req.content | |
else: | |
print("Non-200 status code returned: " + str(req.status_code)) | |
except: | |
print("Error with getting services, status code returned: " + str(req.status_code)) | |
services = json.loads(service_payload) | |
configmap_data = [] | |
service_name_list = [] | |
service_external_ip_list = [] | |
for item in services["items"]: | |
try: | |
service_name_list.append("EXTERNAL_" + item["metadata"]["name"].upper().replace("-","_")) | |
service_external_ip_list.append(item["status"]["loadBalancer"]["ingress"][0]["ip"]) | |
except: # If the service does not have a loadBalancer ingress IP, populate it as "none" string | |
service_name_list.append("EXTERNAL_" + item["metadata"]["name"].upper().replace("-","_")) | |
service_external_ip_list.append("none") | |
configmap_data = {k:v for k,v in zip(service_name_list,service_external_ip_list)} | |
configmap_format = { "apiVersion": "v1", "kind": "ConfigMap", "data": configmap_data, "metadata": { "name": configmap_name, "namespace": args.namespace } } | |
configmap_payload = json.dumps(configmap_format) | |
try: | |
with open(token_file, "r") as token: | |
data=token.readlines() | |
header = { | |
"Content-Type": "application/json", | |
"Authorization": "Bearer " + data[0] | |
} | |
url = kubernetes_api + "namespaces/" + args.namespace + "/configmaps" | |
req = requests.post(url, headers=header, data=configmap_payload, verify=False) | |
if req.status_code <= 201: | |
service_payload = req.content | |
elif req.status_code == 409: | |
print(configmap_name + " already exists, will attempt to PUT") | |
url = kubernetes_api + "namespaces/" + args.namespace + "/configmaps/" + configmap_name | |
req = requests.put(url, headers=header, data=configmap_payload, verify=False) | |
if req.status_code == 200: | |
print("PUT successful") | |
else: | |
print("PUT Failed, status code returned: " + str(req.status_code)) | |
print(req.content) | |
else: | |
print("Non-200 status code returned: " + str(req.status_code)) | |
print(req.content) | |
except: | |
print("Error with getting services, status code returned: " + str(req.status_code)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment