YAML - 用值替换变量?

day*_*mer 5 python 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'  
Run Code Online (Sandbox Code Playgroud)

streaming_jar_path我想替换to的值$streaming_jar_path,我该怎么做?

我知道我们可以merge使用hashes&(anchors)但在这里我只想更改一个值,
如果这是一件微不足道的事情,我很抱歉,我对YAML

谢谢

Aki*_*kif 5

您可以重构文件并使用AnsibleYAML执行。

命令.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"
Run Code Online (Sandbox Code Playgroud)

然后只需运行ansible-playbook即可执行shell命令:

ansible-playbook commands.yml
Run Code Online (Sandbox Code Playgroud)


Gra*_*art 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))
Run Code Online (Sandbox Code Playgroud)