2011-09-30 215 views
4

考慮以下YAMLYAML - 將變量值代入?

hadoop: 
    storage: '/x/y/z/a/b' 
    streaming_jar_path: '/x/c/d/f/r/*.jar' 
    commands: 
     mkdir: 'hadoop dfs -mkdir dir' 
     copyFromLocal: 'hadoop dfs -copyFromLocal from_path to_path' 
     run: 'hadoop jar $streaming_jar_path -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output' 

我想替換的streaming_jar_path$streaming_jar_path的價值,我該怎麼辦呢?

我知道我們可以在hashes使用&(anchors)merge但在這裏,我只是想改變一個價值
我很抱歉,如果這是件小事,我是很新的YAML

謝謝

+0

你要重命名'streaming_jar_path'到'streaming_jar_path_substitute'在YAML或分配的值稱爲'streaming_jar_path_substitute'到'streaming_jar_path'的Python變量? – NullUserException

+0

將streaming_jar_path的值賦給streaming_jar_path_substitute – daydreamer

+0

是你的問題[是否可以在YAML中進行字符串替換?](https://stackoverflow.com/q/30407488/674039) – wim

回答

-1

這應該是讀取文件,編輯數據和寫回文件的簡單過程。

import yaml 

infile = 'input.yaml' 
outfile = 'output.yaml' 

#read raw yaml data from file into dict 
with open(infile, 'r') as f: 
    data = yaml.load(f.read()) 

#make changes to dict 
data['hadoop']['streaming_jar_path'] = '$streaming_jar_path' 

#write dict back to yaml file 
with open(outfile, 'w') as f: 
    f.write(yaml.dump(data)) 
-1

這是一個使用我的解決辦法python的字符串格式化......

YAML文件...

hadoop: 
    streaming_jar_path: '/x/c/d/f/r/*.jar' 
    commands: 
     run: 'hadoop jar {} -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output' 

Python代碼:

s_jar_p = params['hadoop']['streaming_jar_path'] 
run_cmd = (params['hadoop']['commands']['run']).format(s_j_p) 

這對我的作品:-)

1

你可以res構建您的YAML文件並使用Ansible執行。

commands.yml:

- hosts: localhost 
    vars: 
    streaming_jar_path: '/x/c/d/f/r/*.jar' 
    tasks: 
    - name: mkdir 
     shell: "hadoop dfs -mkdir dir" 
    - name: copyFromLocal 
     shell: "hadoop dfs -copyFromLocal from_path to_path" 
    - name: run 
     shell: "hadoop jar {{ streaming_jar_path }} -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output" 

然後只需運行ansible-playbook執行shell命令:

ansible-playbook commands.yml