shellelasticsearchelastic-stack

How do i use shell variables in .sh file for a elasticsearch curl POST


If i run this shell script i want it to simply add a entry into my elasticsearch index backup_timestamps.

In the field "timestamp" should be the current time varible. And in the field "system_name" should be the current hostname variable of the machine.

#!/bin/sh

timestamp=`date +"%Y-%m-%d %T"`
system_name=`hostname`


sudo curl -u elastic:PASSWORD -XPOST "https://localhost:9200/backup_timestamps/_doc" --cacert ./certs/ca/ca.crt -H 'Content-Type: application/json' -d '
{
    "timestamp": "$timestamp",
    "system_name": "$system_name"
}'

echo "("$timestamp" , "$system_name")"

After running this shell script what i get in the elasticsearch db is this:

{
    "_index" : "backup_timestamps",
    "_id" : "BybOdYABhPvBW1kMbwKh",
    "_score" : 1.0,
    "_source" : {
    "timestamp" : "$timestamp",
    "system_name" : "$system_name"
}

But what i want to get is this:

{
    "_index" : "backup_timestamps",
    "_id" : "BybOdYABhPvBW1kMbwKh",
    "_score" : 1.0,
    "_source" : {
    "timestamp" : "2022-01-01 12:00:00",
    "system_name" : "my-server-or-whatever"
}

Solution

  • You have your JSON packet inside single quotes.

    Single quotes don't allow variable substitution, double quotes do:

    $ THING=hello
    $ echo "$THING"
    hello
    $ echo '$THING'
    $THING
    

    Put your packet in double quotes, which would look something like this:

    sudo curl \
        -u elastic:PASSWORD -XPOST \
        "https://localhost:9200/backup_timestamps/_doc" \
        --cacert ./certs/ca/ca.crt \
        -H 'Content-Type: application/json' \
        -d "{\"timestamp\":\"$timestamp\",\"system_name\": \"$system_name\"}"