How to programatically get value printed by Kubernetes in --discovery-token-ca-cert-hash after using kubeadm init

2.7k Views Asked by At

I have this specific use case, in which we remotely create Kubernetes clusters on a significant number of machines. When we run kubeadm init at the end the join commands gets printed as:

kubeadm join [IPv6-Address]:6443 --token TOKEN_VALUE --discovery-token-ca-cert-hash CERT_HASH

In order to programmatically join worker nodes we have a script that needs both the TOKEN_VALUE and the CERT_HASH.

As now I'm acquiring the TOKEN_VALUE with the following command: sudo kubeadm token list | awk 'NR == 2 {print $1}'. However, I haven't found an easy way(or any way at all) to obtain the CERT_HASH.

Any help or pointer would be appreciated.

3

There are 3 best solutions below

0
nazar On BEST ANSWER

For those with the same problem, there doesn't seem to be a super clean or easy way to get it. But after looking at some places, the one that worked for me is openssl x509 -in /etc/kubernetes/pki/ca.crt -noout -pubkey | openssl rsa -pubin -outform DER 2>/dev/null | sha256sum | cut -d' ' -f1

1
Gurvinder Singh Bindra On

Just run below command on control node

kubeadm token create --print-join-command

Refer the documentation here.

0
hegerdes On

In case you are using ansible to automate the join process, you can use the x509_certificate_info module:

# Get cert info
- name: Get CA certificate hash
  delegate_to: "{{ groups.k8s_master }}"
  community.crypto.x509_certificate_info:
    path: /etc/kubernetes/pki/ca.crt
  register: __k8s_pki_ca

# Use the info
- name: debug
  debug:
    msg: 'sha256:{{ __k8s_pki_ca["public_key_fingerprints"]["sha256"] | replace(":","") }}'

Using this allows to automate the join command even with the new kubeadm conf option. More about the crypto-cert module can be found in the ansible docs