Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Openstack JQ交叉引用或如何用输入的另一部分替换一个值_Openstack_Jq_Terraform - Fatal编程技术网

Openstack JQ交叉引用或如何用输入的另一部分替换一个值

Openstack JQ交叉引用或如何用输入的另一部分替换一个值,openstack,jq,terraform,Openstack,Jq,Terraform,我想解析terraform.tfstate(使用openstack提供程序的地方),以返回实例名及其内部+浮动IP(如果已分配) 首先选择我们感兴趣的内容: jq -r '.modules?[]|.resources[]?|select(.type == "openstack_compute_floatingip_v2", .type == "openstack_compute_instance_v2")' < terraform.tfstate 需要从“type”中获取:“openst

我想解析terraform.tfstate(使用openstack提供程序的地方),以返回实例名及其内部+浮动IP(如果已分配)

首先选择我们感兴趣的内容:

jq -r '.modules?[]|.resources[]?|select(.type == "openstack_compute_floatingip_v2", .type == "openstack_compute_instance_v2")' < terraform.tfstate
需要从
“type”中获取:“openstack\u compute\u floatingip\u v2”
替换
.primary.attributes.address
.fixed\u ip
以及相应的
.instance\u id
中的
.name

比如说:

{"address": "209.66.89.143",
"fixed_ip": "10.10.10.5",
"name": "ctl01"}
好吧,我在使用walk时想到了一个主意,但却错过了如何从相应的实例id中实际分配适当的值:

jq -r "$(cat floating.jq)" terraform.tfstate
floating.jq:

def walk(f):
      . as $in
      | if type == "object" then
          reduce keys[] as $key
            ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
      elif type == "array" then map( walk(f) ) | f
      else f
      end;
.modules?[]|.resources[]?|select(.type == 
    "openstack_compute_floatingip_v2", .type == 
    "openstack_compute_instance_v2")|
    .primary|walk( if  type == "object" and .attributes.address then 
    .attributes.instance_id |= "REFERRED VALUE HERE") else . end)

假设这两个相关对象位于名为two.json的文件中。然后,合并来自两个对象的信息的一种方法是使用
-s
命令行选项,例如

jq -s '
  (.[0].primary.attributes | {address, fixed_ip})
  + {name: .[1].primary.attributes.name}' two.json
输出 使用示例输入,输出将是:

{
  "address": "209.66.89.143",
  "fixed_ip": "10.10.10.5",
  "name": "ctl01"
}

为什么不使用Terraform输出而不是解析JSON状态文件呢?您可以使用获取一个资源的所有相关信息的列表。这可能更容易解析。tf输出很好,但也需要正确的格式,我正在编写一个模块将.tfstate数据转换为另一个配置,因此IP只是我希望从中获取的一个子集。terraform state show主要提供我已经拥有的数据,我可以进入该级别并使用它,但问题是如何在一个查询中用“记录”的内容替换
instance\u id
,其中
id=instance\u id
。很好,可用,但假设这样:
{“id”:“nic\u记录”,“attributes”:{“address”:“111”,“name\u id”:“bbb”}
,并且您想从
{“id”:“aaa”替换/reference name id,“attributes”:{“name”aaa“}}},{“id”:“aaa”,“attributes”:{“name”bbb“}}}}}}
但是select应该可以解决这个问题。原始问题和注释都不是很清楚(至少对我而言)。我建议您尽可能地遵循指导原则,可能问一个新的SO问题。
{
  "address": "209.66.89.143",
  "fixed_ip": "10.10.10.5",
  "name": "ctl01"
}