#!/bin/bash
# Update the system
apt update && apt upgrade -y
# Install Apache and PHP
apt install -y apache2 php libapache2-mod-php
# Enable and start Apache service
systemctl enable apache2
systemctl start apache2
cat <<EOF > /var/www/html/index.php
<?php
$token_url = 'http://169.254.169.254/latest/api/token';
$internal_ip_url = 'http://169.254.169.254/latest/meta-data/local-ipv4';
$public_ip_url = 'http://169.254.169.254/latest/meta-data/public-ipv4';
// Create a stream for token
$opts = [
"http" => [
"method" => "PUT",
"header" => "X-aws-ec2-metadata-token-ttl-seconds: 21600",
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);
$token = file_get_contents($token_url, false, $context);
// Create a stream for internal and public IP
$opts_ip = [
"http" => [
"method" => "GET",
"header" => "X-aws-ec2-metadata-token: $token",
]
];
$context_ip = stream_context_create($opts_ip);
$internal_ip = file_get_contents($internal_ip_url, false, $context_ip);
$public_ip = file_get_contents($public_ip_url, false, $context_ip);
echo "<h1>EC2 Instance IP Addresses</h1>";
echo "<p>Internal IP: " . $internal_ip . "</p>";
echo "<p>Public IP: " . $public_ip . "</p>";
?>
EOF
# Set proper permissions
chown apache:apache /var/www/html/index.php