0

I would like to create 20 droplets in DigitalOcean, and would like to do it from either Bash or Ruby. Bash seemed at first to be the easiest, but then I turned out JSON is super picky about quotes and demands the -d argument to have single quotes.

So my script below doesn't expand the $line variable =(

Question

So now I am thinking, would it at all help if I used Ruby? Wouldn't I end up in the same problem again, just in another language?

token=123

while read line; do
  curl -qq -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $token" -d '{"name":"02267-$line","region":"fra1","size":"s-2vcpu-4gb","image":"ubuntu-18-04-x64","ssh_keys":["14063864","22056139","23743266"],"backups":false,"ipv6":false,"user_data":null,"private_networking":null,"volumes": null,"tags":["02267-$line"]}' "https://api.digitalocean.com/v2/droplets"
done < list.txt

list.txt

tokyo
seoul
osaka
kobe
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
  • Maybe just properly quote/concatenate your JSON? `echo '{"foo":"'$MYVAR'", "bar": "baz"}''` ? In your concrete example `-d '{ ..."tags":["02267-'$line'"]}'` – Corion Jan 03 '19 at 14:35
  • Possible duplicate of [How to concatenate string variables in Bash](https://stackoverflow.com/questions/4181703/how-to-concatenate-string-variables-in-bash) – Corion Jan 03 '19 at 14:55
  • 1
    Not directly related to the question, but to your stated goal: Since ruby is an option I suggest using the [dropletkit](https://github.com/digitalocean/droplet_kit) gem, which makes droplet creation super easy. See also the [DO api](https://developers.digitalocean.com/documentation/v2/#droplets) – su_li Jan 03 '19 at 16:44

1 Answers1

1

Use a tool like jq to generate correct JSON for you.

# Note: $x here is *not* a shell variable, but a jq variable
# that jq will expand, ensuring the value is correctly quoted.
filter='{name: "02267-\($x)",
         region: "fra1",
         size: "s-2vcpu-4gb",
         image: "ubuntu-18-04-x64",
         ssh_keys ["14063864","22056139","23743266"],
         backups: false,
         ipv6: false,
         user_data: null,
         private_networking: null,
         volumes: null,
         tags: ["02267-\($x)"]
       }'

jq -n --argjson x "$line" "$filter" |
  curl -qq -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $token" \
     -d @- \
     "https://api.digitalocean.com/v2/droplets"
chepner
  • 497,756
  • 71
  • 530
  • 681