Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create bash script to create yaml files from existing linux etc/hosts files

Tags:

bash

yaml

hosts

I'm new to scripting but have been tasked with creating yaml files from existing Linux /etc/hosts files. Using a hosts file here:

127.0.0.1      localhost
192.168.1.2    host1
192.168.1.3    host2
192.168.1.4    host3
192.168.1.5    host4

..to create yaml files that look like this:

host_entries:
  host1:
    ip: '192.168.1.2'
  host2:
    ip: '192.168.1.3'
  host3:
    ip: '192.168.1.4'
  host4:
    ip: '192.168.1.5'

I know there is more than one way to reach a desired solution. But I'm not quite sure how to script this in a way to get the correct format. Any suggestions would be appreciated.

like image 657
atomicsitup Avatar asked Nov 23 '25 08:11

atomicsitup


1 Answers

Easy and wrong (not strongly guaranteed that output will be valid YAML for all possible inputs):

{
  printf 'host_entries:\n'
  while read -r -a line; do
    [[ ${line[0]} ]] || continue             # skip blank lines
    [[ ${line[0]} = "#"* ]] && continue      # skip comments
    [[ ${line[0]} = 127.0.0.1 ]] && continue # skip localhost

    set -- "${line[@]}" # assign words read from line to current argument list
    ip=$1; shift        # assign first word from line to ip
    for name; do        # iterate over other words, treating them as names
      printf "  %s:\n    ip: '%s'\n" "$name" "$ip"
    done
  done
} </etc/hosts >yourfile.yaml

...for something that's shorter and wrong-er, see edit history (prior version also worked for your sample input, but couldn't correctly handle blank lines, comments, IPs with more than one hostname, etc).

Given your exact host file as input, this emits:

host_entries:
  host1:
    ip: '192.168.1.2'
  host2:
    ip: '192.168.1.3'
  host3:
    ip: '192.168.1.4'
  host4:
    ip: '192.168.1.5'
like image 81
Charles Duffy Avatar answered Nov 24 '25 22:11

Charles Duffy