Skip to content

Instantly share code, notes, and snippets.

@owen2345

owen2345/result.yaml

Last active May 8, 2019
Embed
What would you like to do?
Yaml does not permit to share values between documents in the same file. Then this script helps with that problem.
---
apiVersion: extensions/v1beta1
kind: Deployment
env: &env_vars
val1: "val1"
val2: "val2"
---
apiVersion: extensions/v1beta1
kind: Service
env:
val1: "val1"
val2: "val2"
documents:
- apiVersion: extensions/v1beta1
kind: Deployment
env: &env_vars
val1: "val1"
val2: "val2"
- apiVersion: extensions/v1beta1
kind: Service
env: *env_vars
# frozen_string_literal: true
# Generate a new yaml file "tmp_result.yml" for multiple documents sharing blocks/values between them
# Sample: ruby yaml_parser.rb 'pathtoyaml/sample.yaml'
# ARGV[0] = Filename
# ARGV[1] = Command
abort('Must define file name, sample: beta/deployment.yml') unless ARGV[0]
abort('Must define the command to run, sample: kubectl create') unless ARGV[1]
require 'yaml'
require 'json'
dir = __dir__
yaml_file = File.join(dir, ARGV[0])
old_yaml = YAML.load(File.read(yaml_file))
json_data = old_yaml.to_json # fix to skip anchors
data = YAML.load(json_data)
# parse yaml
file_path = File.join(dir, 'tmp_result.yml')
documents = data.delete('documents') || []
File.open(file_path, 'w+') do |f|
documents.each do |doc|
f << doc.to_yaml
end
end
# puts `#{ARGV[1]} -f #{file_path}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment