Getting Started with AWS Cloud9: Launching an Amazon EC2 Instance and Running Python

Embarking on the journey of cloud-based development with Amazon Web Services (AWS) opens up a world of possibilities, and in this tutorial, we’ll guide you through the process of creating Amazon EC2 instances using AWS Cloud9. Whether you’re a seasoned developer seeking the flexibility of explicit credentials or a fan of streamlined workflows in Cloud9, this tutorial covers both scenarios to cater to your preferences.

As we dive into the intricacies of EC2 instance creation, we’ll unravel the significance of AWS Cloud9 as a web-based integrated development environment (IDE). Additionally, we’ll explore key AWS concepts such as Amazon Machine Images (AMI), key pairs for secure access, the role of security groups in managing traffic, and the importance of subnets for effective networking within the Amazon Virtual Private Cloud (VPC).

By the end of this tutorial, you’ll not only have a firm grasp on the technical aspects of launching EC2 instances but also an understanding of how these components come together to empower developers in the AWS ecosystem.

Let’s embark on this cloud development journey together!

Hands on

AWS Cloud9 is a cloud-based integrated development environment (IDE) provided by Amazon Web Services (AWS). It is designed to simplify the process of coding, building, and debugging applications by providing a collaborative and flexible development environment accessible from anywhere with an internet connection. With Cloud9 you create your instance and manipulate it with an online editor.

In our example, we will make an instance with Amazon linux. Our script will create an EC2 instance.
When making a cloud9 instance, by default we already have a security group and subnets created. For the new instances we will use this data, but feel free to use the ones you prefer and need.

Cloud9 is already integrated with amazon linux and you don’t need to enter your credentials for it to work. If you’re on a remote server or computer, you’ll need to enter your AWS account credentials.

For our script we used a ready-made image. You can create a new instance and make a new image in the EC2 panel. Then go to AMI and use the id of the machine you created.

AWS instances use a key for access. In the EC2 dashboard, go to security and click on key pairs. Create a new key and save it in a safe place or use an existing one. Keys are used to access machines by terminal. Keep it in a safe place, as anyone who has access to the key will have access to the machine.

import boto3

class EC2InstanceManager:
    def __init__(self, image_id, instance_type, key_name, security_group_ids, subnet_id):
        # Create an EC2 client using the default Cloud9 session
        self.ec2_client = boto3.client('ec2')

        # Define parameters for the new instance
        self.instance_params = {
            'ImageId': image_id,  # Replace with the desired AMI image ID
            'InstanceType': instance_type,  # Replace with the desired instance type
            'MinCount': 1,
            'MaxCount': 1,
            'KeyName': key_name,  # Replace with the existing key pair name in your AWS
            'SecurityGroupIds': security_group_ids,  # Replace with the desired security group ID
            'SubnetId': subnet_id,  # Replace with the desired subnet ID
        }

    def create_instance(self):
        # Create the instance
        response = self.ec2_client.run_instances(**self.instance_params)

        # Get the ID of the created instance
        instance_id = response['Instances'][0]['InstanceId']

        print(f'Successfully created instance. ID: {instance_id}')

# Example of how to use the class
if __name__ == "__main__":
    # Replace the placeholder values with your specific configuration
    manager = EC2InstanceManager(
        image_id='ami-XXXXXXXXXXXXXXXXX',
        instance_type='t2.micro',
        key_name='EXISTING_KEY_NAME',
        security_group_ids=['sg-XXXXXXXXXXXXXXXXX'],
        subnet_id='subnet-XXXXXXXXXXXXXXXXX'
    )

    # Create the instance using the defined parameters
    manager.create_instance()

This refactored code encapsulates the EC2 instance creation logic within a class (EC2InstanceManager). The class is instantiated with the necessary parameters, and the create_instance method is responsible for creating the EC2 instance. This approach provides better organization and reusability of the code.

Don’t forget to install the boto3 library. In the terminal type:

pip install boto3

Wait a few seconds and go to the EC2 panel. You will see a new instance created. By running our code you can check the id of the instance you have created. If you have several instances made, look for this identifier.

To avoid unnecessary costs when you finish the process and if you don’t need the instance, don’t forget to finalize the machines created.

If you are on a remote server or computer, you will need to enter your credentials in the code. Below is the adjusted code.

import boto3

class EC2InstanceCreator:
    def __init__(self, aws_access_key, aws_secret_key, region_name):
        # Create a Boto3 session with provided credentials and region
        self.session = boto3.Session(
            aws_access_key_id=aws_access_key,
            aws_secret_access_key=aws_secret_key,
            region_name=region_name
        )

        # Create an EC2 client using the session
        self.ec2_client = self.session.client('ec2')

    def create_instance(self, image_id, instance_type, key_name, security_group_ids, subnet_id):
        # Define parameters for the new instance
        instance_params = {
            'ImageId': image_id,
            'InstanceType': instance_type,
            'MinCount': 1,
            'MaxCount': 1,
            'KeyName': key_name,
            'SecurityGroupIds': security_group_ids,
            'SubnetId': subnet_id,
        }

        # Create the instance
        response = self.ec2_client.run_instances(**instance_params)

        # Get the ID of the created instance
        instance_id = response['Instances'][0]['InstanceId']

        print(f'Successfully created instance. ID: {instance_id}')

# Example of how to use the class
if __name__ == "__main__":
    # Replace the placeholder values with your specific configuration
    creator = EC2InstanceCreator(
        aws_access_key='YOUR_ACCESS_KEY',
        aws_secret_key='YOUR_SECRET_KEY',
        region_name='us-east-1'
    )

    # Replace the placeholder values with your specific configuration
    creator.create_instance(
        image_id='ami-XXXXXXXXXXXXXXXXX',
        instance_type='t2.micro',
        key_name='EXISTING_KEY_NAME',
        security_group_ids=['sg-XXXXXXXXXXXXXXXXX'],
        subnet_id='subnet-XXXXXXXXXXXXXXXXX'
    )

Conclusion

In this tutorial, we explored the seamless process of creating Amazon EC2 instances using AWS Cloud9, showcasing two classes to handle instance creation—one with explicit credentials and another leveraging Cloud9’s integrated credentials.

We delved into essential AWS concepts, including the significance of Cloud9 as a web-based IDE, the importance of Amazon Machine Images (AMI) in defining instance configurations, the role of key pairs in secure access to instances, the functionality of security groups in controlling inbound and outbound traffic, and the role of subnets in networking within the Amazon Virtual Private Cloud (VPC).

By understanding and mastering these elements, you are well-equipped to harness the power of AWS for your development needs. Whether you prefer fine-grained control over credentials or opt for the convenience of Cloud9’s integrated environment, the flexibility and scalability of AWS resources empower you to build, deploy, and manage your applications with ease.

Happy coding in the cloud!