0

Is there a "simple" way (without functions or packages) to get the value of a YAML file in a terminal (bash/sh)?

I wanna extract the value of users -> user("kube-admin-local") -> client-certificate-data

This is the YAML example:

users:
- name: "kube-admin-local"
  user:
    client-certificate-data: 0FURS0tLS0tCk1JSUM2VENDQWRHZ0F3SUJBZ0lJT2wyZ0NHL1BnTWd3RFFZSktvWklodmNOQVFFTEJRQ
- name: kube-admin
  user:
    client-certificate-data: LS0tLS1CRUd=0FURS0tLS0tCk1JSUM2VENDQWRHZ0F3SUJBZ0lJT2wyZ0NHL1BnTWd3RFFZSktvWklodmNOQVFFTEJ

Jan
  • 12,992
  • 9
  • 53
  • 89
  • You would need to write a YAML parser in bash to do this properly, and I doubt that is feasable without functions. All proper solutions use a full fledged YAML parser, that is the simple solution as you don't have to worry about format changes in your YAML, or about added comments, files rewritten (partially) in flow-style etc. – Anthon Mar 30 '19 at 11:57

1 Answers1

0

This won't work in all systems, but

sed -n '/name: "kube-admin-local"/,/name:/s/.*client-certificate-data: \(.*\)/\1/p'

Should do it.

  • -n: don't print unless explicitly stated
  • /name: "kube-admin-local"/,/name:/: lines between those matches
  • rest : substitute data and print
daniu
  • 14,137
  • 4
  • 32
  • 53
  • 1
    I think you should assume that "without functions or packages" also assumes no programs external to bash. In any event it is not guaranteed for YAML that the keys and `name` and `user` are on consecutive lines (as it just happens to be in the example), they can be on the same line, have comment or emtpy lines in between, all without changing the semantics of the YAML file. So this "solution" breaks with the blink of an eye. – Anthon Mar 30 '19 at 11:55
  • Wow, nice! `sed` is totally ok for me. I was not clear with my requirements. Nearly every system has`sed` installed already. My goal was to prevent installing something new. thank you – Jan Mar 30 '19 at 12:21