forgejo-ci-runners/.taskfiles/_scripts/push_token.sh

76 lines
2.3 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
# Prerequisites:
# 1password vault created with a single item in it with the property 'runner_token'.
# Define the vault and item used.
# Usage: ./push_token.sh <incus vm instance name>
set -euo pipefail
# Check if instance name is provided
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <instance-name>" >&2
exit 1
fi
INCUS_INSTANCE="$1" # Use the provided instance name
# Set variables
OP_ITEM_NAME="forgejo-runner" # Name of the 1Password item containing the runner token
OP_VAULT_NAME="forgejo-runner" # Name of the 1Password vault
TOKEN_FILE="tokenfile" # Name of the temporary file to store the token
2024-09-13 19:49:40 -05:00
INCUS_PATH="/var/lib/gitea-runner/default/$TOKEN_FILE"
# Check if OP_SESSION environment variable exists, if not, sign in
if [ -z "${OP_SESSION:-}" ]; then
echo "Not logged in to 1Password CLI. Attempting to sign in..."
if ! eval $(op signin); then
echo "Failed to sign in to 1Password CLI. Please sign in manually using 'op signin'" >&2
exit 1
fi
fi
# Retrieve the token from 1Password
TOKEN=$(op item get "$OP_ITEM_NAME" --vault "$OP_VAULT_NAME" --fields runner_token)
if [ -z "$TOKEN" ]; then
echo "Failed to retrieve token from 1Password" >&2
exit 1
fi
# Create the token file
echo "TOKEN=$TOKEN" > "$TOKEN_FILE"
2024-09-13 19:49:40 -05:00
# Function to push file and check existence with retries
push_and_check_file() {
local retries=5
local count=0
while [ $count -lt $retries ]; do
echo "Attempt $((count+1)) of $retries: Pushing file to Incus instance..."
if incus file push "$TOKEN_FILE" "$INCUS_INSTANCE$INCUS_PATH"; then
if incus exec "$INCUS_INSTANCE" -- test -f "$INCUS_PATH"; then
echo "File successfully verified in Incus instance."
return 0
fi
fi
((count++))
echo "File not found or push failed. Retrying in 5 seconds..."
sleep 5
done
echo "Failed to push and verify file after $retries attempts." >&2
return 1
}
# Push the file to Incus and verify its existence
if push_and_check_file; then
echo "Token file successfully pushed and verified in Incus instance $INCUS_INSTANCE"
else
2024-09-13 19:49:40 -05:00
echo "Failed to push or verify token file in Incus instance $INCUS_INSTANCE" >&2
rm "$TOKEN_FILE"
exit 1
fi
# Clean up the local token file
rm "$TOKEN_FILE"
echo "Operation completed successfully"