본문으로 바로가기

[Linux] bash script에서 yaml 파일 읽기

category Linux/Bash Script 2023. 3. 31. 18:47
반응형

yaml 파일의 내용을 Bash script에서 사용하는 방법입니다.

 

1. parse_yaml.sh 파일 생성

[root@hk-kvmhost yaml-to-bash]# cat parse_yaml.sh
#!/bin/sh
parse_yaml() {
   local prefix=$2
   local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
   sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
        -e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p"  $1 |
   awk -F$fs '{
      indent = length($1)/2;
      vname[indent] = $2;
      for (i in vname) {if (i > indent) {delete vname[i]}}
      if (length($3) > 0) {
         vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
         printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
      }
   }'
}

 

 

2.  config.yaml 파일에 bash script에서 사용할 변수를 정의

[root@hk-kvmhost yaml-to-bash]# cat config.yml
bond0:
  mem1: eno3
  mem2: eno4

host201:
  pxe_gw: 55.55.55.225
  osc_mgmt_vlan_id: 722
  osc_mgmt_ip1: 55.55.55.231
  osc_mgmt_ip2: 55.55.55.232
  osc_mgmt_ip3: 55.55.55.233

 

3.  bash script에 적용 및 사용방법

3.1 echo script 샘플

[root@hk-kvmhost yaml-to-bash]# cat echo.sh
#!/bin/sh

# include parse_yaml function
source /root/hk-scripts/yaml-to-bash/parse_yaml.sh

# read yaml file
eval $(parse_yaml config.yml "config_")

# access yaml content

echo $config_host201_osc_mgmt_vlan_id

echo $config_bond0_mem1
echo $config_bond0_mem2

 

 

3.2 network 설정 파일을 생성해주는 bash script 샘플

#!/bin/sh

# include parse_yaml function
source /root/hk-scripts/yaml-to-bash/parse_yaml.sh

# read yaml file
eval $(parse_yaml config.yml "config_")


# include script info

/bin/cat << EOF > /root/hk-scripts/yaml-to-bash/test/route-eno1
55.55.54.0/27 via $config_host201_pxe_gw dev eno1
EOF

for bond in $config_bond0_mem1 $config_bond0_mem2;
do
/bin/cat << EOF > /root/hk-scripts/yaml-to-bash/test/ifcfg-$bond
TYPE=Ethernet
BOOTPROTO=none
NAME=$bond
DEVICE=$bond
ONBOOT=yes
MASTER=bond0
SLAVE=yes
EOF
done

/bin/cat << EOF > /root/hk-scripts/yaml-to-bash/test/ifcfg-bond0.$config_host201_osc_mgmt_vlan_id
TYPE=VLAN
BOOTPROTO=none
NAME=bond0.$config_host201_osc_mgmt_vlan_id
DEVICE=bond0.$config_host201_osc_mgmt_vlan_id
ONBOOT=yes
VLAN=yes
EOF


for ip1 in $config_host201_osc_mgmt_ip1 $config_host201_osc_mgmt_ip2 $config_host201_osc_mgmt_ip3;
do
        echo "#IPADDR=$ip1" >> /root/hk-scripts/yaml-to-bash/test/ifcfg-bond0.$config_host201_osc_mgmt_vlan_id
done

 

728x90