How to use the aegea.util.aws.resources.ec2.Instance function in aegea

To help you get started, we’ve selected a few aegea examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kislyuk / aegea / aegea / launch.py View on Github external
def launch(args):
    if args.spot_price or args.duration_hours or args.cores or args.min_mem_per_core_gb:
        args.spot = True
    if args.use_dns:
        dns_zone = DNSZone()
    ssh_key_name = ensure_ssh_key(name=args.ssh_key_name, base_name=__name__,
                                  verify_pem_file=args.verify_ssh_key_pem_file)
    # TODO: move all account init checks into init helper with region-specific semaphore on s3
    try:
        ensure_log_group("syslog")
    except ClientError:
        logger.warn("Unable to query or create cloudwatch syslog group. Logs may be undeliverable")
    try:
        i = resolve_instance_id(args.hostname)
        msg = "The hostname {} is being used by {} (state: {})"
        raise Exception(msg.format(args.hostname, i, resources.ec2.Instance(i).state["Name"]))
    except AegeaException:
        validate_hostname(args.hostname)
        assert not args.hostname.startswith("i-")
    ami_tags = dict(tag.split("=", 1) for tag in args.ami_tags or [])
    args.ami = resolve_ami(args.ami, **ami_tags)
    if args.subnet:
        subnet = resources.ec2.Subnet(args.subnet)
        vpc = resources.ec2.Vpc(subnet.vpc_id)
    else:
        vpc = ensure_vpc()
        subnet = ensure_subnet(vpc, availability_zone=args.availability_zone)
    if not subnet.map_public_ip_on_launch:
        raise AegeaException("Subnets without public IP mapping are not supported")

    if args.security_groups:
        security_groups = [resolve_security_group(sg, vpc) for sg in args.security_groups]
github kislyuk / aegea / aegea / launch.py View on Github external
DryRun=args.dry_run, **launch_spec)
            instance = instances[0]
    except ClientError as e:
        expect_error_codes(e, "DryRunOperation")
        logger.info("Dry run succeeded")
        exit()
    instance.wait_until_running()
    hkl = hostkey_line(hostnames=[], key=ssh_host_key).strip()
    tags = dict(tag.split("=", 1) for tag in args.tags)
    add_tags(instance, Name=args.hostname, Owner=ARN.get_iam_username(),
             SSHHostPublicKeyPart1=hkl[:255], SSHHostPublicKeyPart2=hkl[255:],
             OwnerSSHKeyName=ssh_key_name, **tags)
    if args.use_dns:
        dns_zone.update(args.hostname, instance.private_dns_name)
    while not instance.public_dns_name:
        instance = resources.ec2.Instance(instance.id)
        time.sleep(1)
    add_ssh_host_key_to_known_hosts(hostkey_line([instance.public_dns_name], ssh_host_key))
    if args.wait_for_ssh:
        wait_for_port(instance.public_dns_name, 22)
    logger.info("Launched %s in %s using %s", instance, subnet, args.ami)
    return dict(instance_id=instance.id)
github kislyuk / aegea / aegea / util / aws / __init__.py View on Github external
def get_iam_role_for_instance(instance):
    instance = resources.ec2.Instance(resolve_instance_id(instance))
    profile = resources.iam.InstanceProfile(ARN(instance.iam_instance_profile["Arn"]).resource.split("/")[1])
    assert len(profile.roles) <= 1
    return profile.roles[0] if profile.roles else None
github kislyuk / aegea / aegea / ssh.py View on Github external
def get_instance(name):
    return resources.ec2.Instance(resolve_instance_id(name))
github kislyuk / aegea / aegea / build_ami.py View on Github external
ssh_key_name = ensure_ssh_key(name=args.ssh_key_name, base_name=__name__,
                                  verify_pem_file=args.verify_ssh_key_pem_file)
    if args.snapshot_existing_host:
        instance = resources.ec2.Instance(resolve_instance_id(args.snapshot_existing_host))
        args.ami = instance.image_id
    else:
        if args.base_ami == "auto":
            args.ami = locate_ami(product=args.base_ami_product)
        else:
            args.ami = args.base_ami
        hostname = "{}-{}-{}".format(__name__, args.name, int(time.time())).replace(".", "-").replace("_", "-")
        launch_args = launch_parser.parse_args(args=[hostname], namespace=args)
        launch_args.wait_for_ssh = True
        launch_args.iam_role = args.iam_role
        launch_args.cloud_config_data.update(rootfs_skel_dirs=args.rootfs_skel_dirs)
        instance = resources.ec2.Instance(launch(launch_args)["instance_id"])
    ci_timeout = args.cloud_init_timeout
    if ci_timeout <= 0:
        ci_timeout = 3660 * 24
    ssh_client = AegeaSSHClient()
    ssh_client.load_system_host_keys()
    ssh_client.connect(instance.public_dns_name, username="ubuntu", key_filename=get_ssh_key_path(ssh_key_name))
    sys.stderr.write("Waiting {} seconds for cloud-init ...".format(ci_timeout))
    sys.stderr.flush()
    devnull = open(os.devnull, "w")
    for i in range(ci_timeout):
        try:
            ssh_client.check_output("ls /var/lib/cloud/data/result.json", stderr=devnull)
            res = ssh_client.check_output("sudo jq .v1.errors /var/lib/cloud/data/result.json", stderr=devnull)
            if res.strip() != "[]":
                raise Exception("cloud-init encountered errors")
            break
github kislyuk / aegea / aegea / instance_ctl.py View on Github external
def rename(args):
    """Supply two names: Existing instance name or ID, and new name to assign to the instance."""
    old_name, new_name = args.names
    add_tags(resources.ec2.Instance(resolve_instance_id(old_name)), Name=new_name, dry_run=args.dry_run)
github kislyuk / aegea / aegea / ls.py View on Github external
def console(args):
    instance_id = resolve_instance_id(args.instance)
    err = "[No console output received for {}. Console output may lag by several minutes.]".format(instance_id)
    page_output(resources.ec2.Instance(instance_id).console_output().get("Output", err))
github kislyuk / aegea / aegea / build_ami.py View on Github external
def build_ami(args):
    for key, value in config.build_image.items():
        getattr(args, key).extend(value)
    from .util.ssh import AegeaSSHClient
    ssh_key_name = ensure_ssh_key(name=args.ssh_key_name, base_name=__name__,
                                  verify_pem_file=args.verify_ssh_key_pem_file)
    if args.snapshot_existing_host:
        instance = resources.ec2.Instance(resolve_instance_id(args.snapshot_existing_host))
        args.ami = instance.image_id
    else:
        if args.base_ami == "auto":
            args.ami = locate_ami(product=args.base_ami_product)
        else:
            args.ami = args.base_ami
        hostname = "{}-{}-{}".format(__name__, args.name, int(time.time())).replace(".", "-").replace("_", "-")
        launch_args = launch_parser.parse_args(args=[hostname], namespace=args)
        launch_args.wait_for_ssh = True
        launch_args.iam_role = args.iam_role
        launch_args.cloud_config_data.update(rootfs_skel_dirs=args.rootfs_skel_dirs)
        instance = resources.ec2.Instance(launch(launch_args)["instance_id"])
    ci_timeout = args.cloud_init_timeout
    if ci_timeout <= 0:
        ci_timeout = 3660 * 24
    ssh_client = AegeaSSHClient()