Skip to content

Instantly share code, notes, and snippets.

@moqada
Last active August 29, 2015 14:02
Show Gist options
  • Save moqada/e6b605ba61e4a1d36b8c to your computer and use it in GitHub Desktop.
Save moqada/e6b605ba61e4a1d36b8c to your computer and use it in GitHub Desktop.
Elastic Beanstalk 内の EC2 インスタンス一覧を生成する fabfile
# -*- coding: utf-8 -*-
import json
import boto
import boto.beanstalk
import boto.ec2
from fabric.api import task, puts
# Elastic Beanstalk の Applicaton 名
EB_APP_NAME = 'example-app'
# Elastic Beanstalk の リージョン名
EB_REGION = 'ap-northeast-1'
def _get_eb_conn():
""" Beanstalk の conn オブジェクトを取得する
"""
region = [r for r in boto.beanstalk.regions() if r.name == EB_REGION][0]
return boto.connect_beanstalk(region=region)
def _get_ec2_conn():
""" EC2 の conn オブジェクトを取得する
"""
region = [r for r in boto.ec2.regions() if r.name == EB_REGION][0]
return boto.connect_ec2(region=region)
def _get_eb_environments():
""" Application 内の Environment 一覧を返す
"""
conn = _get_eb_conn()
res = conn.describe_environments(application_name=EB_APP_NAME)
return res['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
@task
def generate_spec_servers():
""" Application 内の EC2 で severs.json を生成する
"""
puts('Start generate spec/env/servers.json for serverspec')
envs = _get_eb_environments()
eb_conn = _get_eb_conn()
ec2_conn = _get_ec2_conn()
servers = []
for e in envs:
env_name = e['EnvironmentName']
if 'production' in env_name:
host = 'foo-production'
elif 'staging' in env_name:
host = 'foo-staging'
res = eb_conn.describe_environment_resources(environment_id=e['EnvironmentId'])
instances = res['DescribeEnvironmentResourcesResponse']['DescribeEnvironmentResourcesResult']['EnvironmentResources']['Instances']
for ins in ec2_conn.get_only_instances(instance_ids=[i['Id'] for i in instances]):
servers.append({
'name': '{}-{}'.format(env_name, ins.private_ip_address),
'host': host,
'hostname': ins.private_ip_address,
'roles': ['base']
})
with open('spec/env/hosts2.json', 'w') as f:
f.write(json.dumps(servers, indent=2))
puts('Completed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment