0

I'm trying to pass a variable into a curl command in a bash script. The data according to the Cloudflare API has to be surrounded in quotes.

I've tried using "'" around $accounts but no matter what I do the contents of the file is blank.

Appreciate any help.

#!/bin/bash

# Shell script to extract all DNS entries from Cloudflare zones (domains) in a Cloudflare compatible and BIND format

auth_email="REDACTED" #Cloudflare login
auth_key="REDACTED" # found in cloudflare account settings

# Step 1. Get all account names from Cloudflare

accounts=$(curl -sX GET "https://api.cloudflare.com/client/v4/accounts?page=1&per_page=50&direction=asc" -H "X-Auth-Email:$auth_email" -H "X-Auth-Key:$auth_key" -H "Content-Type: application/json" | jq -r '.result[] | .id')

echo "$accounts" > cf_all_accounts.txt # Write accounts to file

#echo "$accounts"

echo "Read all CF Accounts - completed"
echo

# Step 2. Get all zones (domains) per account

while IFS= read -r accounts; do #
        echo "Getting all zones from:" "$accounts"
        #for i in {1..2}; do
        for i in `seq 1 1 5`; do curl -sX GET "https://api.cloudflare.com/client/v4/zones?page=$i&per_page=50" -H "X-Auth-Email:$auth_email" -H "X-Auth-Key:$auth_key" -H "Content-Type: application/json" | jq -r '.result[] | select(.account.id == "$accounts") | .name'; done >> "$accounts".txt

        echo $all_zones
        echo $i
        #done
        #echo "$all_zones"
done < cf_all_accounts.txt

This is the line that is giving me the trouble (select(.account.id == "$accounts"):

for i in `seq 1 1 5`; do curl -sX GET "https://api.cloudflare.com/client/v4/zones?page=$i&per_page=50" -H "X-Auth-Email:$auth_email" -H "X-Auth-Key:$auth_key" -H "Content-Type: application/json" | jq -r '.result[] | select(.account.id == "$accounts") | .name'; done >> "$accounts".txt
user2193480
  • 81
  • 1
  • 6
  • 1
    `jq --arg accounts "$accounts"` will let you use `$accounts` (no quotes) inside your jq expression itself. – Charles Duffy Oct 11 '21 at 17:58
  • BTW, consider `for ((i=1; i<=5; i++))` instead of using `seq` -- the former is built into bash; the latter is not POSIX-standardized and also not part of bash, so not guaranteed to exist at all nor to have any particular behavior if it _does_ exist. – Charles Duffy Oct 11 '21 at 18:00
  • Anyhow -- if the above does not resolve your problem, please [edit] to provide a [mre] others (who don't have access to your particular cloudflare account) can use to reproduce the problem and test proposed answers. – Charles Duffy Oct 11 '21 at 18:01
  • The `all_zones` doesn't seem to be set anywhere, and the use of `accounts` seems confusing to me -- it's initially used for *all* accounts, then later in the loop it's used for one account at a time. – Gordon Davisson Oct 11 '21 at 18:06

0 Answers0