Executando verificação de segurança...
4

💡 [GITHUB]

Fala pessoal beleza

Recentemente, desenvolvi um script para facilitar e agilizar a adição de variáveis de ambiente no GitHub. No início, enfrentei algumas dificuldades, mas sou grato ao thayto por me ajudar me mostrando o erro na chamada de endpoint da API. Após as correções, consegui aprimorar o código. Embora não esteja perfeito, está funcional, e acredito que possa ser útil para quem também precise dessa funcionalidade. Portanto, compartilho o código aqui para possíveis melhorias.

#!/bin/bash

# Definição das variáveis
REPO_OWNER="EU"
REPO_NAME="repositorio"
TOKEN="token_git"

base64_encode() {
    echo -n "$1" | base64
}

print_progress_bar() {
    local width=50
    local current=$1
    local total=$2
    local progress=$((current * width / total))
    printf "["
    for ((i = 0; i < width; i++)); do
        if ((i <= progress)); then
            printf "="
        else
            printf " "
        fi
    done
    printf "] %d%%\r" $((current * 100 / total))
}

create_environment_if_not_exists() {
    local environments_url="https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/environments"
    local response=$(curl -s -H "Authorization: token $TOKEN" "$environments_url")
    
    # Verificar se o ambiente 'prod' existe na resposta
    if [[ "$response" == *"\"name\": \"prod\""* ]]; then
        echo "Ambiente 'prod' já existe para este repositório."
    else
        echo "O ambiente 'prod' não existe. Criando o ambiente..."
       response=$(curl -s -w "%{http_code}" -X PUT \
        -H "Authorization: token $TOKEN" \
        -H "Accept: application/vnd.github.antiope-preview+json" \
        -H "Content-Type: application/json" \
        "$environments_url/prod")
        local status=${response: -3}
        echo "Status: $status"
        if [ "$status" != "200" ]; then
            echo "Erro ao criar o ambiente 'prod'. Status: $status"
            exit 1
        fi
        echo "Ambiente 'prod' criado com sucesso."
    fi
}


add_secret_to_environment() {
    local name=$1
    local value=$2

    local encoded_value=$(base64_encode "$value")

    local key_id=$(curl -s -X GET \
        -H "Authorization: token $TOKEN" \
        -H "Accept: application/vnd.github.v3+json" \
        "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/actions/secrets/public-key" | jq -r '.key_id')

    local response=$(curl -s -w "%{http_code}" -o /dev/null -X PUT \
        -H "Authorization: token $TOKEN" \
        -H "Accept: application/vnd.github.v3+json" \
        -d "{\"encrypted_value\": \"$encoded_value\", \"key_id\": \"$key_id\"}" \
        "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/environments/prod/secrets/$name")

    local status=${response: -3}

    if [ "$status" != "204" ] && [ "$status" != "200" ] && [ "$status" != "201" ]; then
        echo "Erro ao adicionar a secret '$name'. Status: $status"
    fi

    local progress=$((current_secret * 100 / total_secrets))
    echo -ne "Adicionando secrets: $progress%\r"
}

add_variable_to_environment() {
    local name=$1
    local value=$2

    local existing_var=$(curl -s -X GET \
        -H "Authorization: token $TOKEN" \
        -H "Accept: application/vnd.github.v3+json" \
        "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/environments/prod/variables/$name")

    if [[ "$existing_var" == *"Not Found"* ]]; then
        local add_response=$(curl -s -w "%{http_code}" -o /dev/null -X POST \
            -H "Authorization: token $TOKEN" \
            -H "Accept: application/vnd.github.v3+json" \
            -d "{\"name\": \"$name\", \"value\": \"$value\"}" \
            "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/environments/prod/variables")

        local status=${add_response: -3}

        if [ "$status" != "204" ] && [ "$status" != "200" ] && [ "$status" != "201" ]; then
            echo "Erro ao adicionar a variável '$name'. Status: $status"
        fi
    else
        local update_response=$(curl -s -w "%{http_code}" -o /dev/null -X PATCH \
            -H "Authorization: token $TOKEN" \
            -H "Accept: application/vnd.github.v3+json" \
            -d "{\"value\": \"$value\"}" \
            "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/environments/prod/variables/$name")

        local status=${update_response: -3}

        if [ "$status" != "204" ]; then
            echo "Erro ao atualizar a variável '$name'. Status: $status"
        fi
    fi

    if [ "$status" == "204" ] || [ "$status" == "200" ] || [ "$status" == "201" ]; then
        local progress=$((current_variable * 100 / total_variables))
        echo -ne "Adicionando variáveis: $progress%\r"
    else
        echo -ne "\r\033[K"
    fi

    if [ "$current_variable" -eq "$total_variables" ]; then
        echo "Adição de variáveis concluída."
    fi
}

secrets=(
"SECRET_1:SECRET_1_VALUE"
"SECRET_2:SECRET_2_VALUE"
"SECRET_3:SECRET_3_VALUE"
)


total_secrets=${#secrets[@]}
current_secret=0

echo "Criando ambiente 'prod'..."

create_environment_if_not_exists

echo "Adicionando secrets..."

for secret in "${secrets[@]}"; do
    ((current_secret++))
    IFS=':' read -r name value <<< "$secret"

    add_secret_to_environment "$name" "$value"

    print_progress_bar $current_secret $total_secrets
done

echo "Adição de secrets concluída."

variables=(
"VARIABLE_1:VARIABLE_1_VALUE"
"VARIABLE_2:VARIABLE_2_VALUE"
"VARIABLE_3:VARIABLE_3_VALUE"
)

total_variables=${#variables[@]}
current_variable=0

echo "Adicionando variáveis..."

for variable in "${variables[@]}"; do
    IFS=':' read -r name value <<< "$variable"

    add_variable_to_environment "$name" "$value"

    print_progress_bar $((++current_variable)) $total_variables
done
echo "Adição de variáveis concluída."