如何访问GCE元数据

Facter包含GCE(Google计算引擎)元数据详细信息:

$ facter | grep gce gce => {"instance"=>{"attributes"=>{}, "description"=>"", "disks"=>[{"deviceName"=>"srvpup01", "index"=>0, "mode"=>"READ_WRITE", "type"=>"PERSISTENT"}, {"deviceName"=>"srvpup01-storage01", "index"=>1, "mode"=>"READ_WRITE", "type"=>"PERSISTENT"}], "hostname"=>"srvpup01.c.example.internal", "id"=>12345, "image"=>nil, "licenses"=>[{"id"=>"1000010"}], "machineType"=>"n1-standard-1", "maintenanceEvent"=>"NONE", "networkInterfaces"=>[{"accessConfigs"=>[{"externalIp"=>"", "type"=>"ONE_TO_ONE_NAT"}], "forwardedIps"=>[], "ip"=>"123.456.789.123", "ipAliases"=>[], "mac"=>"00:11:22:33:44:55", "network"=>"example"}], "scheduling"=>{"automaticRestart"=>"TRUE", "onHostMaintenance"=>"MIGRATE", "preemptible"=>"FALSE"}, "serviceAccounts"=>{"[email protected]"=>{"aliases"=>["default"], "email"=>"[email protected]", "scopes"=>["xxx"]}, "default"=>{"aliases"=>["default"], "email"=>"[email protected]", "scopes"=>["xxx"]}}, "tags"=>["no-public-ip"], "zone"=>"europe-west1-d"}, "project"=>{"attributes"=>{"google-compute-default-region"=>"europe-west1", "google-compute-default-zone"=>"europe-west1-d", "sshKeys"=>["... 

有没有什么简单的方法像puppet模块中的“zone”属性那样访问,还是我必须自己parsing这个string?

像哈希访问它失败:

 gce is not a hash or array 

错误gce is not a hash or array暗示你在Puppet 3.x(而不是4.x),它将所有的事实作为string处理,所以要访问散列内的值,您将需要closures stringify_facts设置 。

这可以在所有代理的puppet.conf中完成:

 stringify_facts = false 

您应该可以使用以下方式访问该值:

 $gce["zone"] 

我不认为facter命令行可以打印出像gce.zone这样的嵌套事实的值,所以你可能需要parsing它。

请注意几件事情:

  1. 您可以在命令行上传递顶级事实的名称,以便仅打印出来: facter gce将只打印没有“gce =>”前缀的哈希,或者需要grep。
  2. 您可以使用JSON或YAML格式输出事实,以便于parsing。

使用jgrep你可以这样做:

 facter --json gce | jgrep -s gce.zone 

或者使用YAML和Ruby,你可以这样做:

 facter --yaml gce | ruby -ryaml -e 'p YAML.load(STDIN)["gce"]["zone"]' 

或者使用YAML和awk:

 facter --yaml gce | awk '/zone:/ { print $2 }'