Dreamystify
Dreamystify

Reputation: 155

How can I parse a YAML file in Node.js

Im currently trying to parse an Ansible hosts.yaml file with the current content

all:
  masters:
    master_1: 
      ansible_host: ""
      image: ""
  workers:
    worker_1:
      ansible_host: ""
      image: ""
    worker_2:
      ansible_host: ""
      image: ""

In nodeJS with a library 'js-yaml', but the object it creates is

{
  all: {
    masters: { 
      master_1: {
        ansible_host: ""
        image: ""
      }
    },
    workers: { 
      worker_1: {
        ansible_host: ""
        image: ""
      }, 
      worker_2: {
        ansible_host: ""
        image: ""
      } 
    }
  }
}

The problem with this is being able to loop over the masters/workers hosts. I would expect it to have been an array like

{
  all: {
    masters: [ 
      { master_1: {
          ansible_host: ""
          image: ""
        }
      },
      {...}...
    ],
    workers: [ 
      {...},
      {...}...
    ]
  }
}

or something similar where I can get the count of the hosts and read the vars for the hosts. I also need to save it back to the hosts.yaml for ansible to use without errors. Is there something missing? Is this not possible?

Upvotes: 0

Views: 3903

Answers (1)

Dhruv Shah
Dhruv Shah

Reputation: 1651

The YAML-to-JSON parsing is correct. If you intend to read the values of the worker and master hosts, you can still do it in the following way:

const hosts = {
  all: {
    masters: { 
      master_1: {
        ansible_host: "m1",
        image: "m1_image"
      }
    },
    workers: { 
      worker_1: {
        ansible_host: "w1",
        image: "w1_image"
      }, 
      worker_2: {
        ansible_host: "w2",
        image: "w2_image"
      } 
    }
  }
};

const { masters, workers } = hosts.all;
const masterHosts = Object.keys(masters);
const workerHosts = Object.keys(workers);

// printing their lengths
console.log('masters', masterHosts.length);
console.log('workers', workerHosts.length);

// printing worker hosts
masterHosts.forEach(masterId => {
 console.log(masters[masterId].ansible_host);
  console.log(masters[masterId].image);
})

// printing worker hosts
workerHosts.forEach(worker => {
  console.log(workers[worker].ansible_host);
  console.log(workers[worker].image);
  // uupdating the hosts.
  workers[worker].ansible_host += '_updated';
});

console.log(hosts)

Upvotes: 1

Related Questions