AWS Code Sample

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above. demonstrates how to create an Amazon EC2 instance.

# Copyright 2010-2019, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import logging import boto3 from botocore.exceptions import ClientError def create_ec2_instance(image_id, instance_type, keypair_name): """Provision and launch an EC2 instance The method returns without waiting for the instance to reach a running state. :param image_id: ID of AMI to launch, such as 'ami-XXXX' :param instance_type: string, such as 't2.micro' :param keypair_name: string, name of the key pair :return Dictionary containing information about the instance. If error, returns None. """ # Provision and launch the EC2 instance ec2_client = boto3.client('ec2') try: response = ec2_client.run_instances(ImageId=image_id, InstanceType=instance_type, KeyName=keypair_name, MinCount=1, MaxCount=1) except ClientError as e: logging.error(e) return None return response['Instances'][0] def main(): """Exercise create_ec2_instance()""" # Assign these values before running the program image_id = 'AMI_IMAGE_ID' instance_type = 'INSTANCE_TYPE' keypair_name = 'KEYPAIR_NAME' # Set up logging logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(asctime)s: %(message)s') # Provision and launch the EC2 instance instance_info = create_ec2_instance(image_id, instance_type, keypair_name) if instance_info is not None:'Launched EC2 Instance {instance_info["InstanceId"]}')' VPC ID: {instance_info["VpcId"]}')' Private IP Address: {instance_info["PrivateIpAddress"]}')' Current State: {instance_info["State"]["Name"]}') if __name__ == '__main__': main()

Sample Details

Service: ec2

Last tested: 2019-2-18

Author: AWS

Type: full-example

On this page: