2015-02-06 22:31:59 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2015-05-27 20:10:43 +02:00
|
|
|
"encoding/json"
|
2015-02-06 22:31:59 +01:00
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2015-06-05 04:43:56 +02:00
|
|
|
"regexp"
|
2015-02-06 22:31:59 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type state struct {
|
|
|
|
Modules []moduleState `json:"modules"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// read populates the state object from a statefile.
|
|
|
|
func (s *state) read(stateFile io.Reader) error {
|
|
|
|
|
|
|
|
// read statefile contents
|
|
|
|
b, err := ioutil.ReadAll(stateFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// parse into struct
|
|
|
|
err = json.Unmarshal(b, s)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-05 04:43:56 +02:00
|
|
|
// resources returns a map of name to resourceState, for any supported resources
|
|
|
|
// found in the statefile.
|
|
|
|
func (s *state) resources() map[string]resourceState {
|
|
|
|
typeRemover := regexp.MustCompile(`^[\w_]+\.`)
|
|
|
|
inst := make(map[string]resourceState)
|
2015-02-06 22:31:59 +01:00
|
|
|
|
|
|
|
for _, m := range s.Modules {
|
|
|
|
for k, r := range m.Resources {
|
2015-06-05 04:43:56 +02:00
|
|
|
if r.isSupported() {
|
|
|
|
name := typeRemover.ReplaceAllString(k, "")
|
|
|
|
inst[name] = r
|
2015-02-06 22:31:59 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return inst
|
|
|
|
}
|
|
|
|
|
|
|
|
type moduleState struct {
|
|
|
|
Resources map[string]resourceState `json:"resources"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type resourceState struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Primary instanceState `json:"primary"`
|
|
|
|
}
|
|
|
|
|
2015-06-05 04:43:56 +02:00
|
|
|
// isSupported returns true if terraform-inventory supports this resource.
|
|
|
|
func (s *resourceState) isSupported() bool {
|
|
|
|
return s.Address() != ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Address returns the IP address of this resource.
|
|
|
|
func (s *resourceState) Address() string {
|
|
|
|
switch s.Type {
|
|
|
|
case "aws_instance":
|
|
|
|
return s.Primary.Attributes["private_ip"]
|
|
|
|
|
|
|
|
case "digitalocean_droplet":
|
|
|
|
return s.Primary.Attributes["ipv4_address"]
|
|
|
|
|
|
|
|
default:
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attributes returns a map containing everything we know about this resource.
|
|
|
|
func (s *resourceState) Attributes() map[string]string {
|
|
|
|
return s.Primary.Attributes
|
|
|
|
}
|
|
|
|
|
2015-02-06 22:31:59 +01:00
|
|
|
type instanceState struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
Attributes map[string]string `json:"attributes,omitempty"`
|
|
|
|
}
|