YAML - 如何替换变量值?
考虑以下的yaml内容:
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
,我该怎么做呢?
我知道我们可以用&(锚点)
来合并
这些哈希
,但我这里只想改变一个值。
如果这个问题很简单,我很抱歉,我对YAML
还很陌生。
谢谢你!
2 个回答
0
这个过程应该很简单,就是读取你的文件,修改里面的数据,然后再把它写回文件。
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))
5
你可以重新整理你的 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
就可以执行这些命令了:
ansible-playbook commands.yml