-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-ec2.sh
More file actions
109 lines (77 loc) · 2.54 KB
/
create-ec2.sh
File metadata and controls
109 lines (77 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/bash
# this is called shibang
#if handle the errors then it shows beautifully
set -euo pipefail
check_awscli(){
if ! command -v aws &> /dev/null; then
echo "AWS CLI is not installed. Please install it first." >&2
return 1
fi
}
install_awscli(){
echo "Installing AWS CLI v2 on Linux..."
# Download and install AWS CLI v2
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
sudo apt-get install -y unzip &> /dev/null
unzip -q awscliv2.zip
sudo ./aws/install
# Verify installation
aws --version
# Clean up
rm -rf awscliv2.zip ./aws
}
wait_for_instance() {
local instance_id="$1"
echo "Waiting for instance $instance_id to be in running state..."
while true; do
state=$(aws ec2 describe-instances --instance-ids "$instance_id" --query 'Reservations[0].Instances[0].State.Name' --output text)
if [[ "$state" == "running" ]]; then # Fixed spacing and condition syntax
echo "Instance $instance_id is now running."
break
fi # Fixed incorrect "if" closing
sleep 10 # Moved outside the if condition to avoid logic errors
done
}
create_ec2_instance(){
local ami_id="$1"
local instance_type="$2"
local key_name="$3"
local subnet_id="$4"
local security_group_ids="$5"
local instance_name="$6"
# Run AWS CLI command to create EC2 instance
instance_id=$(aws ec2 run-instances \
--image-id "$ami_id" \
--instance-type "$instance_type" \
--key-name "$key_name" \
--subnet-id "$subnet_id" \
--security-group-ids "$security_group_ids" \
--tag-specifications "ResourceType=instance, Tags=[{Key=Name, Value=$instance_name}]" \
--query 'Instances[0].InstanceId' \
--output text
)
if [[ -z "$instance_id" ]]; then
echo "Failed to create EC2 instance." >&2
exit 1
if
echo "Instance $instance_id created successfully."
#Wait for the instance to be in running state
wait_for_instance "instance_id"
}
main(){
if ! check_awscli; then
cd install_awscli || exit 1
fi
echo "Creating EC2 instance..."
# Specify the parameters for creating the EC2 instance
AMT_ID=""
INSTANCE_TYPE="t2.micro"
KEY_NAME=""
SUBNET_ID=""
SECCURITY_GROUP_IDS="" # Add your security group IDs separated by space
INSTANCE_NAME="Shell-Script-EC2-Demo"
#Call the function to create the EC2 instance
create_ec2_instance "$AMT_ID" "$INSTANCE_TYPE" "$KEY_NAME" "$SUBNET_ID" "$SECURITY_GROUP_IDS" "$INSTANCE_NAME"
echo "EC2 instance creation completed."
}
main "@"