Created
June 9, 2015 12:06
-
-
Save holysugar/190cbbe99658805f1a53 to your computer and use it in GitHub Desktop.
GCE 用の ansible dynamic inventory 手抜き版
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
class GCE | |
def initialize(project_id, env) | |
@project_id = project_id | |
@env = env | |
end | |
def instance_list | |
@instances ||= JSON.parse(`gcloud compute instances list --format json --project #{@project_id}`) | |
end | |
def parse | |
target_instances = instance_list.select{|i| metadata(i, "environment") == @env } | |
result = target_instances.map{|i| [role(i), name(i), zone(i)] } | |
result.each_with_object({}) do |(role, name, zone), result| | |
result[role] ||= { "hosts" => [], "vars" => { "stage" => @env } } | |
result[role]["hosts"] << "#{name}.#{zone}.#{@project_id}" | |
end | |
end | |
def result | |
parse.to_json | |
end | |
private | |
def metadata(instance, key) | |
return unless instance["metadata"]["items"] | |
(instance["metadata"]["items"].find{|meta| meta["key"] == key } || {})["value"] | |
end | |
def role(instance) | |
metadata(instance, "role") | |
end | |
def name(instance) | |
instance["name"] | |
end | |
def zone(instance) | |
instance["zone"] | |
end | |
end | |
# GCE.new('your-project-id', 'production').result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment