【问题标题】:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)在 `<main>' 中:nil:NilClass (NoMethodError) 的未定义方法 `[]'
【发布时间】: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 状态文件

标签: json ruby terraform


【解决方案1】:

问题出在这里:

state['modules']

如果这是脚本的第一行,Ruby 不知道state 变量是什么,并在尝试从中获取任何值时引发错误。

看起来您希望它是一个哈希,但它是空的...可能在此脚本之前缺少某些内容。

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2013-11-14
    • 2013-01-14
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多