Class: TerraformInventory::TerraformState
- Inherits:
-
Object
- Object
- TerraformInventory::TerraformState
- Defined in:
- lib/terraform_inventory/terraform_state.rb
Instance Attribute Summary collapse
-
#state ⇒ Object
(also: #resources)
readonly
Returns the value of attribute state.
Instance Method Summary collapse
-
#find_resources(resource_selector) ⇒ Object
Find resources given a resource selector.
- #group_by_host(resource_host_group_mapping) ⇒ Object
-
#initialize(stateText) ⇒ TerraformState
constructor
A new instance of TerraformState.
Constructor Details
#initialize(stateText) ⇒ TerraformState
Returns a new instance of TerraformState.
47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/terraform_inventory/terraform_state.rb', line 47 def initialize(stateText) @state = split_state( YAML.load( stateText .gsub(/\e\[(\d+)m/, "") # Hack to get rid of ASCII color codes in Terraform output .gsub(/\s=\s/, ": ") # Use colons so we can parse as YAML .gsub(/: \n/, ": ''\n") # Need to have quotes in order to parse as YAML .split(/\n\n/) # Grab only text that is related to resource state (exclude outputs) .first # We only want the first match ) ) end |
Instance Attribute Details
#state ⇒ Object (readonly) Also known as: resources
Returns the value of attribute state.
6 7 8 |
# File 'lib/terraform_inventory/terraform_state.rb', line 6 def state @state end |
Instance Method Details
#find_resources(resource_selector) ⇒ Object
Find resources given a resource selector.
A resource selector is composed of the following:
resource_type (ex. aws_instance)
resource_name (ex. web)
resource_number (ex. 1)
Here are a few examples of resource selectors:
aws_instance.web.1 - selects a specific aws_instance resource named web
aws_instance.web - selects all aws_instance resources named web
Returns:
[ resource_data ]
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/terraform_inventory/terraform_state.rb', line 23 def find_resources(resource_selector) resource_type, resource_name, resource_number = parse_resource_selector(resource_selector) if @state[resource_type].nil? || @state[resource_type][resource_name].nil? [] elsif resource_number [@state[resource_type][resource_name][resource_number]] else @state[resource_type][resource_name] end end |
#group_by_host(resource_host_group_mapping) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/terraform_inventory/terraform_state.rb', line 35 def group_by_host(resource_host_group_mapping) resource_host_group_mapping.reduce({}) do |data, (resource_selector, host_group)| # rubocop:disable Style/EachWithObject data[host_group.to_sym] ||= [] resources = find_resources(resource_selector) raise Exception::ResourceNotFoundException, resource_selector if resources.empty? data[host_group.to_sym].concat resources data end end |