#!/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 set -euo pipefail # Check if instance name is provided if [ "$#" -ne 1 ]; then echo "Usage: $0 " >&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 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" # 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 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"