bezpieczenstwo-w-chmurze/skrypty/create-ec2-with-http.sh

46 lines
1.9 KiB
Bash
Raw Normal View History

2024-10-22 15:35:30 +02:00
#!/bin/bash
# Variables
KEY_NAME="uam-bwc-key"
INSTANCE_TYPE="t2.micro"
SECURITY_GROUP_NAME="uam-bwc-sg"
AMI_ID="ami-005fc0f236362e99f"
REGION="us-east-1"
# Generate SSH key pair
aws ec2 create-key-pair --key-name $KEY_NAME --query 'KeyMaterial' --output text --region $REGION > ${KEY_NAME}.pem
chmod 400 ${KEY_NAME}.pem
# Create security group
SECURITY_GROUP_ID=$(aws ec2 create-security-group --group-name $SECURITY_GROUP_NAME --description "Security group for uam-bwc EC2 instance" --query 'GroupId' --output text --region $REGION)
# Add rules to security group
aws ec2 authorize-security-group-ingress --group-id $SECURITY_GROUP_ID --protocol tcp --port 22 --cidr 0.0.0.0/0 --region $REGION
aws ec2 authorize-security-group-ingress --group-id $SECURITY_GROUP_ID --protocol tcp --port 80 --cidr 0.0.0.0/0 --region $REGION
aws ec2 authorize-security-group-ingress --group-id $SECURITY_GROUP_ID --protocol tcp --port 443 --cidr 0.0.0.0/0 --region $REGION
# User data script
USER_DATA_SCRIPT=$(cat <<EOF
#!/bin/bash
apt-get update -y
apt-get install -y apache2
apt-get install -y openssl
a2enmod ssl
a2ensite default-ssl
systemctl start apache2
systemctl enable apache2
echo "Hello World!" > /var/www/html/index.html
2024-10-28 11:05:28 +01:00
systemctl restart apache2
2024-10-22 15:35:30 +02:00
EOF
)
# Provision EC2 instance
INSTANCE_ID=$(aws ec2 run-instances --image-id $AMI_ID --count 1 --instance-type $INSTANCE_TYPE --key-name $KEY_NAME --security-group-ids $SECURITY_GROUP_ID --user-data "$USER_DATA_SCRIPT" --query 'Instances[0].InstanceId' --output text --region $REGION)
# Wait for the instance to be in running state
aws ec2 wait instance-running --instance-ids $INSTANCE_ID --region $REGION
# Get the public IP of the instance
INSTANCE_PUBLIC_IP=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].PublicIpAddress' --output text --region $REGION)
echo "EC2 instance is running. Public IP: $INSTANCE_PUBLIC_IP"