Reputation: 31
I need to set my environment in my code based on kubernetes(in AKS) cluster name in python. I have 2 clusters stg-my-cluster, prod-my-cluster, How can I access to this info from inside my pod? there is a better way ? thx
Upvotes: 0
Views: 2155
Reputation: 31
here is a hack I found in order to get it ( not directly the cluster name, but the resourceGroup )
clusters = set()
config.load_incluster_config()
core = client.CoreV1Api()
configmaps = core.list_namespaced_config_map('kube-system', timeout_seconds=10)
for item in configmaps.items:
try:
cluster = (item.__dict__)['_data']['CLUSTER_RESOURCE_ID']
if cluster:
cluster_resource_id = re.search(r"resourceGroups/([\s\S]+)/providers",cluster).group(1)
clusters.add(cluster_resource_id)
except:
pass
In my case, I use a resourceGroup per env. So I just have to :
if 'my-resource-group-production' in clusters:
.....
Upvotes: 0
Reputation: 160013
Once you're inside the cluster, it doesn't know that it has a "name". This only exists for management tools, such as the context name in your .kube/config
file.
The setup I use day-to-day uses Helm as the primary installation mechanism, and there is a separate Helm values file per environment. Our CD system knows how to helm upgrade -f $CLUSTER_NAME.yaml
. In that file we set:
# values.prod.yaml
cluster: prod-my-cluster
And then you can include that as an environment variable in your Deployment:
env:
- name: CLUSTER
value: {{ .Values.cluster }}
Once you have it in an environment variable, in Python you can access it using os.environ
.
Upvotes: 3