EC2 - User data

User data


Functionality in EC2 service is important and very handy tool. This allows us to execute script right after EC2 instance creation phase. By that we can execute,install any program we want or update, upgrade operating system on that virtual machine. User data functionality will run once just after completion of the instance creation sequence.

  1.  First we need to create an EC2 instance with extra steps. Choose Amazon Linux OS so we don't have to install aws-cli tool which we will need in the next steps.





      
  2. Click to advanced options and add script below also tick the metadata options as well. With new metadata service it is not possible to send request to metadata service without secret key. That is why we need to use old metadata service for the demonstration purposes.
    Script is at the end of the page !!!







  3. We need one more thing to do, since by default all the ports are closed state. We need to add firewall allow line to open port 80 to serve our page to the public web.
    Click to the security tab of the EC2 instance you just created. 






  4. Add port 80 open to anywhere line like the below.






  5. And that is it. Navigate to the public IP address like this  http://PUBLIC_IP



    Bash script  used to create this page :



    #!/bin/bash

    # Update the package index
    sudo yum update -y

    # Install Apache HTTP server
    sudo yum install -y httpd

    # Start the Apache service
    sudo systemctl start httpd

    # Enable Apache to start on boot
    sudo systemctl enable httpd

    # Retrieve the instance's availability zone
    AVAILABILITY_ZONE=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)

    # Retrieve the instance's public IP address
    PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)

    # Create a simple HTML webpage
    cat <<EOL > /var/www/html/index.html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Instance Metadata</title>
    </head>
    <body>
        <h1>Instance Metadata</h1>
        <p><strong>Availability Zone:</strong> $AVAILABILITY_ZONE</p>
        <p><strong>Public IP Address:</strong> $PUBLIC_IP</p>
    </body>
    </html>
    EOL

    # Restart the Apache service to apply changes
    sudo systemctl restart httpd







Comments

Popular posts from this blog

Identity Access Management - How to create user in IAM ?!

AWS pricing fundamentals

IAM - Roles