【问题标题】:YAML - substituting values for variables?YAML - 用值代替变量?
【发布时间】:2011-11-28 15:17:21
【问题描述】:

考虑下面的 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,我该怎么做?

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

谢谢

【问题讨论】:

标签: python yaml


【解决方案1】:

您可以重组您的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

【讨论】:

    【解决方案2】:

    这应该是一个读取文件、编辑数据和写回文件的简单过程。

    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))
    

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 2014-12-15
      • 2019-11-21
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多