Reputation: 1255
I want to be able to add dns record entries to kubernetes core-dns config map. I already know how to do this manually with this
kubectl -n kube-system edit cm coredns
Then add entries under NodeHosts
Is there a supported way to do this? or am I left to my own devices of parsing json and yaml output and replacing config map files with code?
Upvotes: -3
Views: 66
Reputation: 1255
I gave in and just created a python script that does the work for me:
#!/usr/bin/env python3
import subprocess
import json
import os
# Define the entries to add
entries = [
"127.1.1.11 test1.example.com",
"127.1.1.12 test2.example.com"
]
namespace = "kube-system"
configmap = "coredns"
def run_command(command):
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True)
return result.stdout.decode('utf-8')
coredns_config_json = run_command(f"kubectl get cm {configmap} -n {namespace} -o json")
coredns_config = json.loads(coredns_config_json)
nodehosts = coredns_config['data'].get('NodeHosts', '')
for entry in entries:
if entry not in nodehosts:
nodehosts += f"\n{entry}"
coredns_config['data']['NodeHosts'] = nodehosts
updated_config_json = json.dumps(coredns_config, indent=4)
with open('updated_coredns.json', 'w') as f:
f.write(updated_config_json)
apply_command = "kubectl apply -f updated_coredns.json"
run_command(apply_command)
os.remove('updated_coredns.json')
print("CoreDNS ConfigMap updated successfully.")
Upvotes: 1
Reputation: 1127
Technically No, but here are some workarounds:
The entries can be added via coredns-custom
config map, like:
# coredns-custom.yaml
custom.server=example.local:53 {
hosts {
192.168.1.101 app1.local
192.168.1.102 app2.local
fallthrough
}
}
and then
kubectl -n kube-system create configmap coredns-custom \
--from-file=coredns-custom.yaml -o yaml --dry-run=client | kubectl apply -f -
Create a kustomization.yaml
file:
apiVersion: v1
kind: ConfigMap
metadata:
name: coredns
namespace: kube-system
data:
NodeHosts: |
192.168.1.100 app.local
and then apply it.
If you frequently update CoreDNS with new hosts, you can automate it with a script:
#!/bin/bash
NEW_ENTRY="192.168.1.101 newapp.local"
kubectl get cm coredns -n kube-system -o yaml | \
yq e '.data.NodeHosts += "\n'"$NEW_ENTRY"'"' - | \
kubectl apply -f -
kubectl rollout restart deployment coredns -n kube-system
Upvotes: 0