【发布时间】:2020-03-18 14:36:58
【问题描述】:
我在网上找到了一个脚本来提取 JSON terraform 状态文件并将其转换为 HCL 文件。我在脚本的 attributes 定义行上收到此错误:
in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
我试图在网上找到解决方案,但我不知道 Ruby。
这是脚本:
resource_key = ARGV.shift || usage
resource_type, resource_name = resource_key.split('.')
resource_id = ARGV.shift || usage
require 'justrun'
status = JustRun.command "terraform import #{resource_type}.#{resource_name} #{resource_id}" do |line, type|
out = type == 'stdout' ? $stdout : $stderr
out.puts line
end
require 'json'
state = JSON.load File.read 'terraform.tfstate'
attributes = state['modules'][0]['resources'][resource_key]['primary']['attributes']
resource = {}
attributes.each do |attr, value|
if attr.include? '.#'
attr_array, _ = attr.split '.#'
resource[attr_array] = []
attributes.keys.select { |e| e.start_with? "#{attr_array}." }.each do |key|
next if key == attr
resource[attr_array] << attributes[key]
end
elsif attr.include? '.%'
attr_array, _ = attr.split '.%'
resource[attr_array] = {}
attributes.keys.select { |e| e.start_with? "#{attr_array}." }.each do |key|
next if key == attr
new_key = key[attr_array.size + 1 .. -1]
resource[attr_array][new_key] = attributes[key]
end
elsif attr.include? '.'
next
# elsif attr == 'id'
# next
else
resource[attr] = value
end
end
【问题讨论】:
-
正如您在第一行中看到的,它从先前定义的
state变量中收集数据。但是,如果您只是将此脚本复制粘贴到一个空的 .rb 文件中,state变量将不会被填充,因此将为空(resource_key也将是nil)。在使用它之前,您必须用一些数据初始化这个变量。请描述您想要实现的目标以及获取此脚本的位置。 -
state中有什么内容?添加puts state作为脚本的第一行并共享输出 -
我在代码中添加了状态行。 State 是一个 JSON terraform 状态文件
-
您正在加载的文件中有什么内容?
-
一个 JSON terraform 状态文件