Skip to content

Lesson 5 of 5

Deploy a file upload web page using an IAM role

Attach an IAM role to your EC2 instance so it can write to the S3 bucket without storing passwords, then create a simple HTML page on the instance that uploads a file to the bucket, completing the secure web app.

10 minCloud

After this lesson you will be able to attach an IAM role to an EC2 instance, create a simple web page that uploads a file to S3, and run that page on your instance.

Create an IAM role for the EC2 instance

Your EC2 instance needs permission to write to the S3 bucket. You could store an access key on the instance, but that is a secret that can be copied. Instead, attach an IAM role to the instance. The role gives the instance temporary credentials that AWS rotates automatically.

In the AWS Management Console, search for IAM and open it. In the left menu, choose Roles, then Create role. Under Trusted entity type, choose AWS service. Under Use case, choose EC2, then Next.

In the permissions search box, type AmazonS3FullAccess, tick the policy, and choose Next. This policy allows all S3 actions. For a real app you would write a policy that allows only your bucket, but this is fine for learning.

For Role name, enter s3-upload-role. Choose Create role.

Now attach the role to your instance. In the EC2 console, select your instance, choose Actions, Security, Modify IAM role. Pick s3-upload-role from the list and choose Update IAM role.

The role is now attached. You do not need to restart the instance. The AWS CLI on the instance will use the role automatically.

Test the role from the instance

Connect to your instance with SSH as you did in lesson 2. Run this command to check which identity the CLI is using:

aws sts get-caller-identity

The output shows an ARN that ends with something like assumed-role/s3-upload-role/i-.... This means the CLI is using the role, not a stored access key.

Now try to list your bucket. Replace my-web-app-bucket-12345 with your bucket name from lesson 3:

aws s3 ls s3://my-web-app-bucket-12345/

You should see the files you uploaded earlier. The instance can now read and write to the bucket without any passwords stored on it.

Install a web server and Python

You will create a simple HTML page that lets you choose a file and upload it to S3. The page runs on the instance and uses a Python script to handle the upload.

First, install the Apache web server and Python. Run these commands on the instance:

sudo yum update -y
sudo yum install -y httpd python3
sudo systemctl start httpd
sudo systemctl enable httpd

The web server is now running. It serves files from /var/www/html.

Create the upload form

Create a new file in the web server root:

sudo nano /var/www/html/upload.html

Paste this HTML into the file:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h1>Upload a file to S3</h1>
    <form action="/cgi-bin/upload.py" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

Save and exit nano with Ctrl+O, Enter, Ctrl+X.

The form sends the file to a script at /cgi-bin/upload.py. You will create that script next.

Create the CGI upload script

First, make the CGI directory:

sudo mkdir /var/www/cgi-bin

Then create the script:

sudo nano /var/www/cgi-bin/upload.py

Paste this Python script:

#!/usr/bin/env python3
import cgi
import os
import subprocess

print("Content-type: text/plain\n")

bucket = 'my-web-app-bucket-12345'

form = cgi.FieldStorage()
fileitem = form['file']

if not fileitem or not fileitem.filename:
    print("No file selected.")
    raise SystemExit

filename = os.path.basename(fileitem.filename)
tmp_path = os.path.join('/tmp', filename)

with open(tmp_path, 'wb') as f:
    f.write(fileitem.file.read())

result = subprocess.run(
    ['aws', 's3', 'cp', tmp_path, f's3://{bucket}/uploaded_file.txt'],
    capture_output=True,
    text=True
)

os.remove(tmp_path)

if result.returncode == 0:
    print("File uploaded successfully.")
else:
    print("Upload failed:")
    print(result.stderr)

Replace my-web-app-bucket-12345 with your bucket name. Save and exit.

Make the script executable:

sudo chmod +x /var/www/cgi-bin/upload.py

This script uses the Python standard library cgi module to parse the multipart form data correctly. It saves the uploaded file to a temporary location, then uses the AWS CLI to copy it to S3. The instance role provides the necessary permissions.

Configure httpd to run CGI scripts

Edit the httpd configuration:

sudo nano /etc/httpd/conf/httpd.conf

Find the line that starts with # ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" and remove the # at the beginning to enable it.

Next, find the section that begins with <Directory "/var/www/cgi-bin">. Inside that section, change Options None to Options ExecCGI.

Save and exit. Restart the web server:

sudo systemctl restart httpd

Test the upload page

Open a web browser on your own computer and go to http://your-instance-public-ip/upload.html. Replace your-instance-public-ip with the public IPv4 address of your EC2 instance from the console.

You should see the upload form. Choose a small text file from your computer and click Upload. The page will show a message that the file was uploaded.

To check that the file is in the bucket, run this command on the instance:

aws s3 ls s3://my-web-app-bucket-12345/

You should see uploaded_file.txt in the list.

You have now built a secure web app: the web page runs on your EC2 instance, and the instance uses an IAM role to upload files to S3 without any stored passwords.

Key takeaways

  • An IAM role gives an EC2 instance temporary credentials to access AWS services, so you do not store access keys on the instance.
  • Attach a role to an instance from the EC2 console under Actions, Security, Modify IAM role.
  • The AWS CLI on the instance automatically uses the role when you run commands.
  • A secure upload page uses a Python CGI script that parses multipart form data and calls the AWS CLI to copy the file to S3.
  • The web server runs on the instance, and the instance's role controls what it can do in AWS.

Try it

Create a new HTML page on your EC2 instance called list.html that shows a pre-signed URL for the file uploaded_file.txt in your S3 bucket. On the instance, generate the URL with aws s3 presign s3://my-web-app-bucket-12345/uploaded_file.txt --expires-in 3600, replacing the bucket name. Put the output into an anchor tag in the page, for example <a href="the-generated-url">Download file</a>. Open the page in your browser and click the link. A good result is that the file downloads and its content matches what you uploaded.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.