Ruby Method for Fetching a Bastion EIP IP Address from Terraform State File

From Bonus Bits
Jump to: navigation, search

Description

This article gives an example of Ruby methods to fetch a Bastion host IP address.


Tested Environment

  1. S3 backend state
  2. Bastion state only includes the bastion
  3. Bastion role calls a bastion module
  4. Bastion has a EIP
  5. Terraform 0.12.24
  6. AWS_REGION + AWS_DEFAULT_REGION + AWS_PROFILE and TF_WORKSPACE Environment Variables Set


Prerequisites

Bastion Role Output (This is what is in State Outputs):

output "eip_public_ip_bastion" {
  value       = module.bastion.eip_public_ip
  // string
}

Bastion Module Output:

output "eip_public_ip" {
  value       = aws_eip.bastion.public_ip
  // string
}


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 bastion Terraform init is in its own directory. Otherwise we could just put ./.

def fetch_bastion_ip(path)
  require 'colorize'
  require 'json'
  
  puts 'INFO: Fetching Terraform State Outputs for (' + 'bastion'.colorize(:cyan) + ')'
  Dir.chdir(path) do
    @bastion_state_json = shell_command_strout("terraform output -json")
  end
  JSON.parse(@bastion_state_json)['eip_public_ip_bastion']['value']
end

Usage (Ruby)

fetch_bastion_ip('terraform/app/bastion')


Related Articles