Created
November 19, 2019 03:04
-
-
Save PaulFurtado/2a23badf3a39cb6c650c0ec3a9f68621 to your computer and use it in GitHub Desktop.
A python implementation of generating pod names from the metadata.generateName field for use in mutating webhook admission controllers
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
import random | |
def generate_name(prefix): | |
""" | |
Generates a name for a resource in the same way the Kubernetes API servers | |
would (appending a suffix of up to 5 random alphanumeric characters). | |
""" | |
# no vowels, so "bad words" can't be formed | |
alphanums = 'bcdfghjklmnpqrstvwxz2456789' | |
# Up to 5 random characters, don't exceed max name length | |
random_len = min(5, 63 - len(prefix)) | |
generated_part = ''.join(random.choice(alphanums) for _ in range(random_len)) | |
return prefix + generated_part | |
def ensure_pod_name(pod): | |
""" | |
Pods created by Deployments do not have a name set by the time they reach | |
the admission controllers, instead they have the generateName field set, | |
which contains the prefix for the pod name. This function materializes the | |
name and should be called if the admission controller requires knowledge | |
of the pod name. | |
""" | |
metadata = pod['metadata'] | |
if metadata.get('name'): | |
return | |
prefix = metadata.get('generateName') | |
if not prefix: | |
raise ValueError('Pod does not have name nor generateName set') | |
metadata['name'] = generate_name(prefix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment