Skip to content

Commit

Permalink
updating scripts to be in multiple files
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardTMiles committed Jan 19, 2025
1 parent e0873b7 commit f6c7fe1
Show file tree
Hide file tree
Showing 8 changed files with 272 additions and 238 deletions.
17 changes: 17 additions & 0 deletions .github/assets/php/createMetadataJson.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

function fetch_metadata($p = '/'): ?array
{
$t = file_get_contents("http://169.254.169.254/latest/api/token", false, stream_context_create(['http' => ['method' => 'PUT', 'header' => "X-aws-ec2-metadata-token-ttl-seconds: 21600\r\n"]]));
$u = "http://169.254.169.254/latest/meta-data$p";
$o = stream_context_create(['http' => ['method' => 'GET', 'header' => "X-aws-ec2-metadata-token: $t\r\n"]]);
$r = file_get_contents($u, false, $o);
if ($r === false) return null;
$m = [];
foreach (explode("\n", trim($r)) as $l) {
$m[rtrim($l, '/')] = substr($l, -1) == '/' ? fetch_metadata("$p$l") : file_get_contents("$u/$l", false, $o);
}
return $m;
}

echo json_encode(fetch_metadata(), JSON_PRETTY_PRINT);
17 changes: 17 additions & 0 deletions .github/assets/service/aws_deployment_boot_scripts.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[Unit]
Description=Fedora boot script(s) invoked by cloud-init (web.yaml)
After=network.target
OnFailure=aws_deployment_failure.service

[Service]
Type=oneshot
KillMode=process
User=apache
ExecStartPre=/bin/ls --color=always -lah /var/aws-deployment/
ExecStartPre=/home/apache/setup_apache_sites.sh
ExecStartPre=/usr/bin/systemctl enable httpd
ExecStartPre=/usr/bin/systemctl start httpd
ExecStart=/var/aws-deployment/signalLifecycleAction.sh 0

[Install]
WantedBy=multi-user.target
11 changes: 11 additions & 0 deletions .github/assets/service/aws_deployment_failure.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[Unit]
Description=Failure script for aws_deployment_boot_scripts

[Service]
Type=oneshot
KillMode=process
User=root
ExecStart=/var/aws-deployment/signalLifecycleAction.sh 1

[Install]
WantedBy=multi-user.target
100 changes: 100 additions & 0 deletions .github/assets/shell/deployUserDataScript.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/bin/bash

SCRIPT_URL="https://raw.githubusercontent.com/MilesSystems/aws-deployment/${1}/.github/assets/php/createMetadataJson.php"

php <( curl -fsSL "$SCRIPT_URL" ) > /var/aws-deployment/aws.json

curl -o '/var/aws-deployment/signalLifecycleAction.sh' \
https://raw.githubusercontent.com/MilesSystems/aws-deployment/${1}/.github/assets/shell/signalLifecycleAction.sh

chmod +x /var/aws-deployment/signalLifecycleAction.sh
/var/aws-deployment/signalLifecycleAction.sh 0

err() {
IFS=' ' read line file <<< "$(caller)"
echo "Error ($2) on/near line $line in $file"
/var/aws-deployment/signalLifecycleAction.sh $2
}
trap 'err $LINENO $?' ERR

export COMPOSER_HOME=/home/apache/.composer
EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]
then
>&2 echo 'ERROR: Invalid installer checksum'
rm composer-setup.php
exit 1
fi

php composer-setup.php --quiet
rm composer-setup.php
mv composer.phar /usr/local/bin/composer

mkdir -p /var/aws-deployment

chmod -R +x /var/aws-deployment/
chown -R apache:apache /var/www/

curl -o /home/apache/setup_apache_sites.sh \
https://raw.githubusercontent.com/MilesSystems/aws-deployment/${1}/.github/assets/shell/setup_apache_sites.sh
chmod +x /home/apache/setup_apache_sites.sh

# Function to set up SSH keys for the apache user
setup_ssh_for_apache() {

cd /home/apache/ || exit 1

mkdir -p /home/apache/.ssh/

cat > /home/apache/.ssh/id_github_pull_key <<EOF
${2}
EOF

cat > /home/apache/.ssh/config <<EOF
Host github.com
HostName github.com
User git
IdentityFile /home/apache/.ssh/id_github_pull_key
IdentitiesOnly yes
EOF

chmod g+rwX /home/apache/.ssh/ -R
chmod 600 /home/apache/.ssh/id_github_pull_key
chmod 600 /home/apache/.ssh/config

eval $(ssh-agent)
ssh-add /home/apache/.ssh/id_github_pull_key
ssh-keyscan -H github.com >> /home/apache/.ssh/known_hosts
# Test SSH connection to GitHub

set +e
SSH_OUTPUT=$(ssh -T [email protected] 2>&1)
set -e

# Check if the response contains "successfully authenticated"
if echo "$SSH_OUTPUT" | grep -q "successfully authenticated"; then
echo "SSH authentication to GitHub successful!"
else
echo "SSH authentication to GitHub failed: $SSH_OUTPUT"
exit 1
fi
}

# Run the SSH setup function as the apache user
echo "Setting up SSH for apache user..."
chmod 777 /etc/httpd/conf.d/
sudo -u apache bash -c "$(declare -f setup_ssh_for_apache); setup_ssh_for_apache"
chmod 755 /etc/httpd/conf.d/

curl -o /etc/systemd/system/aws_deployment_failure.service \
https://raw.githubusercontent.com/MilesSystems/aws-deployment/${1}/.github/assets/system/aws_deployment_failure.service

curl -o /etc/systemd/system/aws_deployment_boot_scripts.service \
https://raw.githubusercontent.com/MilesSystems/aws-deployment/${1}/.github/assets/system/aws_deployment_boot_scripts.service

systemctl enable "aws_deployment_boot_scripts"
systemctl start "aws_deployment_boot_scripts"

97 changes: 97 additions & 0 deletions .github/assets/shell/setupApacheSites.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/bin/bash

# Enable debugging and error handling
set -eEBx

# List of repositories from GitHub
repositories=(
"[email protected]:nicoledodge/NikkiDodgePhotography.com.git"
"[email protected]:MilesSystems/chylle.miles.systems.git"
"[email protected]:MilesSystems/bnb-studios.com.git"
"[email protected]:MilesSystems/renovate.company.git"
"[email protected]:MilesSystems/eatery.restaurant.git"
"[email protected]:RichardTMiles/Stats.Coach.git"
)

# Define the Apache config template
config_template=$(cat <<'TEMPLATE'
<VirtualHost *:80>
ServerAdmin webmaster@$domain
ServerName $domain
ServerAlias www.$domain # Handle both domain and www prefix
DocumentRoot $target_dir
ErrorLog /var/log/httpd/$domain-error_log
CustomLog /var/log/httpd/$domain-access_log combined
<Directory $target_dir>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
TEMPLATE
)

# Loop through each repository and extract the domain name dynamically
for repo in "${repositories[@]}"; do

# Extract the domain name from the repository URL
domain=$(echo "$repo" | sed -E 's/.*github\.com[:\/]([^\/]+\/)?([^\/]+)\.git/\2/' | tr '[:upper:]' '[:lower:]')

# Define the target directory for the clone
target_dir="/var/www/$domain"

# Clone the repository into the appropriate folder if it doesn't already exist or is empty
if [ -d "$target_dir" ] && [ "$(ls -A "$target_dir")" ]; then
echo "Skipping $domain: Target directory '$target_dir' exists and is not empty."
else
echo "Cloning $domain from $repo..."
git clone "$repo" "$target_dir"
fi

# Define the Apache config file location (in /etc/httpd/conf.d/)
config_file="/etc/httpd/conf.d/$domain.conf"

# Export variables so envsubst can substitute them in the config_template
export domain
export target_dir

# Create the Apache config file for the domain
echo "Creating Apache config for $domain in /etc/httpd/conf.d/... ($config_file)"
echo "$config_template" | envsubst > "$config_file"

# Check if the specified directory exists
if [ ! -d "$target_dir" ]; then
echo "Error: Directory '$target_dir' does not exist."
exit 1
fi

echo "Post-clone setup started for directory: $target_dir"
cd "$target_dir" || exit 1

set +e

# For a Node.js project:
if [ -f "package.json" ]; then
echo "Installing npm dependencies..."
npm install
fi

# For a Python project:
if [ -f "requirements.txt" ]; then
echo "Installing Python dependencies..."
pip install -r requirements.txt
fi

# For a Composer-based PHP project:
if [ -f "composer.json" ]; then
echo "Installing PHP dependencies..."
composer install
fi

set -e

echo "Post-clone setup completed for directory: $target_dir"

done

echo "All sites are configured."
24 changes: 24 additions & 0 deletions .github/assets/shell/signalLifecycleAction.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/bash

set -x

EC2_INSTANCE_ID=$(jq -r '.["instance-id"]' /var/aws-deployment/aws.json)
EC2_REGION=$(jq -r '.placement.region' /var/aws-deployment/aws.json)
AutoScalingGroup=$(aws autoscaling describe-auto-scaling-instances --instance-ids "$EC2_INSTANCE_ID" --query "AutoScalingInstances[0].AutoScalingGroupName" --output text)
AWS_STACK_NAME=$(aws cloudformation describe-stack-resources --physical-resource-id "$EC2_INSTANCE_ID" --query "StackResources[0].StackName" --output text)

sleep 80

if [ "$1" = "0" ] || [ -z "$1" ]; then
ACTION_RESULT='CONTINUE'
EXIT_CODE=0
else
ACTION_RESULT='ABANDON'
EXIT_CODE=1
fi

aws autoscaling complete-lifecycle-action --instance-id "$EC2_INSTANCE_ID" --lifecycle-hook-name "ready-hook" --auto-scaling-group-name "$AutoScalingGroup" --region "$EC2_REGION" --lifecycle-action-result "$ACTION_RESULT"

/opt/aws/bin/cfn-signal --stack "$AWS_STACK_NAME" --resource "AutoScalingGroup" --region "$EC2_REGION" --exit-code "$EXIT_CODE"

exit $1
Loading

0 comments on commit f6c7fe1

Please sign in to comment.