Skip to content

Instantly share code, notes, and snippets.

@cnosuke
Created May 25, 2018 09:56
Show Gist options
  • Save cnosuke/e73c3e7fc9f34195b9839371e70433b5 to your computer and use it in GitHub Desktop.
Save cnosuke/e73c3e7fc9f34195b9839371e70433b5 to your computer and use it in GitHub Desktop.
Script to create kubernetes client certification
#!/usr/bin/env ruby
require 'json'
require 'base64'
require 'tempfile'
def request_json(cn)
{
"CN" => cn,
"key" => {
"algo": "ecdsa",
"size": 384,
}
}.to_json
end
def k8s_csr(cn, csr)
b64 = Base64.encode64(csr).gsub("\n",'')
str =<<-EOB
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
name: #{cn}
spec:
groups:
- system:authenticated
request: #{b64}
usages:
- digital signature
- key encipherment
- server auth
EOB
return str
end
def check_command(cmd)
unless system("type #{cmd} > /dev/null 2> /dev/null")
puts "[ERROR] `#{cmd}` is not installed. Aborted."
exit 1
end
end
cn = ARGV.first
unless cn && cn.size != 0
puts "[ERROR] CommonName is needed."
exit 1
end
check_command("cfssl")
check_command("cfssljson")
check_command("kubectl")
j = request_json(cn)
result = `echo '#{j}' | cfssl genkey - | cfssljson -bare -stdout #{cn}`
success = $? == 0
unless success
puts "[ERROR] Unknown error. Aborted."
exit 1
end
key, csr = result.split("\n\n")
puts "Saving private key file #{cn}.key..."
open("#{cn}.key", "w") { |io| io.puts key }
t = Tempfile.open { |io| io.puts k8s_csr(cn, csr); io }
system("kubectl create -f #{t.path}")
str = ""
str << "=" * 20 + "\n"
str << `kubectl describe csr #{cn}` + "\n"
str << "=" * 20 + "\n"
str << "CSR successfully created.\n"
str << "Waiting for approval...\n"
str << "```\n"
str << "% kubectl certificate approve #{cn}\n"
str << "```\n\n"
str << "After approval, download certificate:\n"
str << "```\n"
str << "% kubectl get csr #{cn} -o jsonpath='{.status.certificate}' | base64 -D > #{cn}.crt\n"
str << "```\n"
puts str
t.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment