Ruby Method for Fetching Private Instance IP Address from Terraform State

From Bonus Bits
Jump to: navigation, search

Description

This article gives an example of Ruby method to fetch an EC2 Instance IP address.


Tested Environment

  1. S3 backend state
  2. Terraform 0.12.24
  3. AWS_REGION + AWS_DEFAULT_REGION + AWS_PROFILE and TF_WORKSPACE Environment Variables Set


Prerequisites

Terraform Root Output:

output instances {
  value       = {
    api = aws_instance.api,
    batch = aws_instance.batch,
    ui = aws_instance.ui
  }
  // map(object)
}


Shell Command with Open3

def shell_command_strout(shell_command, sensitive = false)
  # This does not show output until the command is completed.
  require 'open3'
  out, err, status = Open3.capture3(shell_command)
  successful = status.success?
  unless successful
    puts('ERROR: Unsuccessful Command')
    puts("Open3: Shell Command (#{shell_command})") unless sensitive
    puts("Open3: Status (#{status})")
    puts("Open3: Standard Out (#{out})")
    puts("Open3: Successful? (#{successful})")
    puts("Open3: Error Out (#{err})")
  end
  out
end

Fetch Bastion State

This pulls the state file outputs and returns a hash map. This is assuming the role or module for the instances Terraform init is in its own directory. Otherwise we could just put ./.

def fetch_instance_ip(tf_path, instance_name)
  require 'colorize'
  require 'json'

  puts 'INFO: Fetching Terraform State Outputs for (' + instance_name.to_s.colorize(:cyan) + ')'
  Dir.chdir(tf_path) do
    @instance_state_json = shell_command_strout("terraform output -json")
  end
  JSON.parse(@instance_state_json)['instances']['value'][instance_name]['private_ip']
end

Usage (Ruby)

fetch_bastion_ip('terraform/app/services/blue', 'ui')


Related Articles