Skip to content

Instantly share code, notes, and snippets.

@bowbowbow
Created November 10, 2016 04:41
Show Gist options
  • Save bowbowbow/e0f4b13bd2359693c9a777852eb68844 to your computer and use it in GitHub Desktop.
Save bowbowbow/e0f4b13bd2359693c9a777852eb68844 to your computer and use it in GitHub Desktop.
import click
import boto3
#aws access key should be in ~/.aws/credentials
@click.group()
def cli():
pass
@cli.command()
@click.option('--count', default=1, help='Number of creating')
@click.option('--image', help='aws ami image id')
@click.option('--key', help='aws ami image id')
@click.option('--itype', help='aws instance type')
@click.option('--tags', multiple=True, help='aws tags')
def create(count, image, key, itype, tags):
imageID = "ami-8ce236e2"
instanceType = "t2.nano"
#keyName = "openbaas-aws"
if image is None:
print(imageID)
image = imageID
#if key is None:
# print(keyName)
# key = keyName
if itype is None:
print(instanceType)
itype = instanceType
ec2 = boto3.resource('ec2', region_name='ap-northeast-2')
response = ec2.create_instances(DryRun=False,
ImageId=image,
MinCount=count,
MaxCount=count,
InstanceType=itype,
)
iid = response[0].id
if len(tags) > 0:
tag_pair = []
for t in tags:
k, v = t.split(':')
tag_pair.append({'Key': k, 'Value': v})
ec2.create_tags(
Resources = [iid],
Tags = tag_pair
)
click.echo(response)
@cli.command()
@click.option('--key', default='instance-state-name', help='aws state')
@click.option('--value', default='running', help='aws state')
def ls(key, value):
ec2 = boto3.resource('ec2', region_name='ap-northeast-2')
instances = ec2.instances.filter(
Filters=[{'Name': key, 'Values': [value]}])
for instance in instances:
click.echo("%s : %s : %s"%(instance.id, instance.instance_type,
instance.state['Name']))
@cli.command()
@click.option('--iid', help='aws id')
@click.option('--tags', multiple=True, help='aws tags')
def settags(iid, tags):
ec2 = boto3.resource('ec2', region_name='ap-northeast-2')
if len(tags) > 0:
tag_pair = []
for t in tags:
k, v = t.split(':')
tag_pair.append({'Key': k, 'Value': v})
print(tag_pair)
ec2.create_tags(
Resources = [iid],
Tags = tag_pair
)
@cli.command()
@click.option('--iid', help='aws id')
def destroy(iid):
ec2 = boto3.resource('ec2', region_name='ap-northeast-2')
iids = iid.split(',')
ec2.instances.filter(InstanceIds=iids).stop()
ec2.instances.filter(InstanceIds=iids).terminate()
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment