Json 在“”中:nil的未定义方法“[]”:NilClass(NoMethodError)
我在网上找到了一个脚本,用于提取JSON terraform状态文件并将其转换为HCL文件。我在脚本的属性定义行中遇到此错误:Json 在“”中:nil的未定义方法“[]”:NilClass(NoMethodError),json,ruby,terraform,Json,Ruby,Terraform,我在网上找到了一个脚本,用于提取JSON terraform状态文件并将其转换为HCL文件。我在脚本的属性定义行中遇到此错误: in `<main>': undefined method `[]' for nil:NilClass (NoMethodError) 我试图在网上找到解决方案,但我不知道Ruby 以下是脚本: resource_key = ARGV.shift || usage resource_type, resource_name = resource_key.sp
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['modules']
如果这是脚本的第一行,Ruby不知道状态变量是什么,并且在尝试从中获取任何值时引发错误
看起来你希望它是一个散列,但它是空的。。。此脚本之前可能缺少某些内容。如第一行所示,它从先前定义的状态变量收集数据。但是,如果您只是将这个脚本复制粘贴到一个空的.rb文件中,状态变量将不会被填充,因此将为空,并且资源密钥也将为零。在使用该变量之前,必须使用一些数据初始化该变量。请描述您想要实现的目标以及获取此脚本的位置。状态是什么?Add puts state作为脚本的第一行并共享输出。我在代码中添加了state行。State是一个JSON terraform状态文件您正在加载的文件中有什么?一个JSON terraform状态文件