Skip to content

Instantly share code, notes, and snippets.

@owen2345
Last active May 8, 2019 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owen2345/7eb74573ce06fd3ad688fe174a8b1327 to your computer and use it in GitHub Desktop.
Save owen2345/7eb74573ce06fd3ad688fe174a8b1327 to your computer and use it in GitHub Desktop.
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