kem*_*102 3 ruby hash yaml webhooks hiera
我在YAML文件中有一堆哈希(它用于某些服务器的基于Puppet/Hiera的配置),如下所示:
---
apache_vhosts:
'webuser.co.uk':
ip: '*'
port: '80'
serveraliases: ['www.webuser.co.uk',]
add_listen: false
docroot: '/home/webuser/public_html'
docroot_owner: 'webuser'
docroot_group: 'apache'
serveradmin: 'webmaster@webuser.co.uk'
scriptalias: '/home/webuser/public_html/cgi-bin/'
access_log_format: '\"%{X-Forwarded-For}i\" %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
override: 'all'
users:
'webuser':
ensure: 'present'
gid: '500'
managehome: true
home: '/home/webuser'
password: '$6$zix5AzRheEzQwadthjvLNh.8maO6o4DU4Y0POTaS6xfgjfdvihP2O/UQN6eVDHjG2hTCT6VTLk5HsXeB9FF0xMlYiYY9W1'
password_max_age: '99999'
password_min_age: '0'
shell: '/sbin/nologin'
uid: '500'
Run Code Online (Sandbox Code Playgroud)
我需要以自动方式在Ruby中附加这些哈希值.这个想法是一个请求进来并命中一个运行ruby脚本的webhook,该脚本添加了一个新的Apache VHost和随附的用户.从操作YAML的角度来看,Ruby文档非常不合适,谷歌搜索没有提出任何相关的东西.也许有人可以指出我正确的方向?
在Ruby中使用YAML并不多.我想你只需要知道两种方法:YAML.load和YAML.dump.
假设文件是file.yml,其中包含您提供的内容:
# YAML is part of the standard library.
require 'yaml'
# YAML.load parses a YAML string to appropriate Ruby objects.
# So you can first load the contents of the file with File#read,
# then parse it.
yaml_string = File.read "file.yml"
data = YAML.load yaml_string
# Now you have all of it in data.
data["apache_vhosts"]
# => {"webuser.co.uk"=>{"ip"=>"*", ...
# Once you are done manipulating them, dump it back with YAML.dump
# to convert it back to YAML.
output = YAML.dump data
File.write("file.yml", output)
Run Code Online (Sandbox Code Playgroud)
我认为这就是它.
UPDATE
好的,现在它实际上是附加已解析的数据.通过解析我的意思是解析的数据格式应该与现有格式一致.
假设您有一个名为的新用户的有效解析信息new_user:
new_user_info = {"ensure"=>"present", "gid"=>"900", "managehome"=>true, "home"=>"/home/new_user"}
Run Code Online (Sandbox Code Playgroud)
要将其附加到原始YAML内容(解析为ruby对象),您可以执行以下操作:
data["users"]["new_user"] = new_user_info
Run Code Online (Sandbox Code Playgroud)
转储后,这将添加另一个用户条目,该条目new_user位于用户列表的底部(在users:YAML文件下).主机也可以以相同的方式添加,一旦获得域名和其他信息,您可以像这样添加它们:
data["apache_vhosts"]["new_domain_name"] = info
Run Code Online (Sandbox Code Playgroud)
同样重要的是将信息安排在正确的层次结构中.
| 归档时间: |
|
| 查看次数: |
5301 次 |
| 最近记录: |