Search code examples
jsonperlrestrest-client

Perl's REST Client error when trying to use Crontab


Script works well when run manually, but when I schdule it in cronjob it shows :

malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "<html>\r\n<head><tit...") at /usr/local/lib/perl5/site_perl/5.14.2/JSON.pm line 171.

script itself:

#rest config vaiables


$ENV{'PERL_LWP_SSL_VERIFY_NONE'} = 0;
print "test\n";
my $client = REST::Client->new();
$client->addHeader('Authorization', 'Basic YWRtaW46cmFyaXRhbg==');
$client->addHeader('content_type', 'application/json');
$client->addHeader('accept', 'application/json');
$client->setHost('http://10.10.10.10');
$client->setTimeout(1000);

$useragent = $client->getUseragent();

print "test\n";

#Getting racks by pod
                 $req = '/api/v2/racks?name_like=2t';
               #print " rekvest {$req}\n";
               $client->request('GET', qq($req));
               $racks = from_json($client->responseContent());
               $datadump = Dumper (from_json($client->responseContent()));

crontab -l

*/2 * * * *  /usr/local/bin/perl /folder/api/2t.pl > /dmitry/api/damnitout 2>&1

Appreciate any suggestion Thank you, Dmitry


Solution

  • It is difficult to say what is really happening, but in my experience 99% issues of running stuff in crontab stems from differences in environment variables.

    Typical way to debug this: in the beginning of your script add block like this:

    foreach my $key (keys %ENV) {
        print "$key = $ENV{$key}\n";
    }
    

    Run it in console, look at the output, save it in log file.

    Now, repeat the same in crontab and save it into log file (you have already done that - this is good).

    See if there is any difference in environment variables when trying to run it both ways and try to fix it. In Perl, probably easiest is to alter environment by changing %ENV. After all differences are sorted out, there is no reason for this to not work right.

    Good luck!