Learn to run Python code in an AWS Cloud9 IDE
Objectives:
Learn AWS Cloud9 console to create and then open an AWS Cloud9 development environment.
Learn to Install and configure the AWS SDK for Python
Learn to create an S3 bucket using Python SDK.
Prerequisites:
You must have an existing AWS Cloud9 EC2 development environment.
You have the AWS Cloud9 IDE for the existing environment already open.
Click to know how to create Cloud9 IDE
Step 1: Install Python
In a terminal session in the AWS Cloud9 IDE, confirm whether Python is already installed by running the python3 --version command. (To start a new terminal session, on the menu bar choose Window, New Terminal.) If Python is installed, skip ahead to Step 2: Add code.
Run the yum update (for Amazon Linux) or apt update (for Ubuntu Server) command to help ensure the latest security updates and bug fixes are installed.
For Amazon Linux:
sudo yum -y update
For Ubuntu Server:
sudo apt update
3. Install Python by running the install command.
For Amazon Linux:
sudo yum -y install python3
For Ubuntu Server:
sudo apt-get install python3
Step 2: Add code
In the AWS Cloud9 IDE, create a file with the following content and save the file with the name hello.py. (To create a file, on the menu bar choose File, New File. To save the file, choose File, Save.)
import sys
print('Hello, World!')
print('The sum of 2 and 3 is 5.')
sum = int(sys.argv[1]) + int(sys.argv[2])
print('The sum of {0} and {1} is {2}.'.format(sys.argv[1], sys.argv[2], sum))
Step 3: Run the code
In the AWS Cloud9 IDE, on the menu bar choose Run, Run Configurations, New Run Configuration.
On the [New] - Stopped tab, enter hello.py 5 9 for Command. In the code, 5 represents sys.argv[1], and 9 represents sys.argv[2].
Choose Run and compare your output.
By default, AWS Cloud9 automatically selects a runner for your code. To change the runner, choose Runner, and then choose Python 2 or Python 3.
Step 4: Install and configure the AWS SDK for Python (Boto3)
The AWS SDK for Python (Boto3) enables you to use Python code to interact with AWS services like Amazon S3. For example, you can use the SDK to create an Amazon S3 bucket, list your available buckets, and then delete the bucket you just created.
Install pip
In the AWS Cloud9 IDE, confirm whether pip is already installed for the active version of Python by running the python -m pip --version command. If pip is installed, skip to the next section.
To install pip, run the following commands. Because sudo is in a different environment from your user, you must specify the version of Python to use if it differs from the current aliased version
curl -O https://bootstrap.pypa.io/get-pip.py # Get the install script.
sudo python36 get-pip.py # Install pip for Python 3.6.
python -m pip --version # Verify pip is installed.
rm get-pip.py # Delete the install script.
Install the AWS SDK for Python (Boto3)
After you install pip, install the AWS SDK for Python (Boto3) by running the pip install command.
Type the following command to install AWS SDK for Python (Boto3).
sudo python3 -m pip install boto3
It will give the python installed version.
Type the following command to check if Boto3 is installed.
python3 -m pip show boto3
Set up credentials in your environment
Each time you use the AWS SDK for Python (Boto3) to call an AWS service, you must provide a set of credentials with the call. These credentials determine whether the SDK has the necessary permissions to make the call. If the credentials don't cover the necessary permissions, the call fails.
Ignore this step if you are using Cloud 9 IDE with EC2 environment
To store your credentials within the environment, follow the instructions in Calling AWS services from an environment in AWS Cloud9, and then return to this topic.
Step 5: Add AWS SDK code
Add code that uses Amazon S3 to create a bucket, list your available buckets, and optionally delete the bucket you just created.
In the AWS Cloud9 IDE, create a file with the following content and save the file with the name s3.py.
import sys
import boto3
from botocore.exceptions import ClientError
def list_my_buckets(s3_resource):
print('Buckets:\n\t', *[b.name for b in s3_resource.buckets.all()], sep="\n\t")
def create_and_delete_my_bucket(s3_resource, bucket_name, keep_bucket):
list_my_buckets(s3_resource)
try:
print('\nCreating new bucket:', bucket_name)
bucket = s3_resource.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={
'LocationConstraint': s3_resource.meta.client.meta.region_name
}
)
except ClientError as e:
print(f"Couldn't create a bucket for the demo. Here's why: "
f"{e.response['Error']['Message']}")
raise
bucket.wait_until_exists()
list_my_buckets(s3_resource)
if not keep_bucket:
print('\nDeleting bucket:', bucket.name)
bucket.delete()
bucket.wait_until_not_exists()
list_my_buckets(s3_resource)
else:
print('\nKeeping bucket:', bucket.name)
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('bucket_name', help='The name of the bucket to create.')
parser.add_argument('region', help='The region in which to create your bucket.')
parser.add_argument('--keep_bucket', help='Keeps the created bucket. When not '
'specified, the bucket is deleted '
'at the end of the demo.',
action='store_true')
args = parser.parse_args()
s3_resource = (
boto3.resource('s3', region_name=args.region) if args.region
else boto3.resource('s3'))
try:
create_and_delete_my_bucket(s3_resource, args.bucket_name, args.keep_bucket)
except ClientError:
print('Exiting the demo.')
if __name__ == '__main__':
main()
Step 6: Run the AWS SDK code
On the menu bar, choose Run, Run Configurations, New Run Configuration.
For Command, enter s3.py my-test-bucket us-west-2, where my-test-bucket is the name of the bucket to create, and us-west-2 is the ID of the AWS Region where your bucket is created. By default, your bucket is deleted before the script exits. To keep your bucket, add --keep_bucket to your command. For a list of AWS Region IDs, see Amazon Simple Storage Service Endpoints and Quotas in the AWS General Reference.
3. Choose Run, and compare your output.
Step 7: Clean up
To prevent ongoing charges to your AWS account after you're done with this tutorial, delete the AWS Cloud9 environment.
Was this document helpful? How can we make this document better? Please provide your insights. You can download PDF version for reference.
easy to understand
easy to understand
Helpful blog sir.
Understandable
Easy to understand sir