Listing Running Virtual Servers
In this example, we collect data on stored virtual servers by querying the “vservers” resource and identifying which ones are enabled (running).
The code structure is as follows:
•Instantiate a new REST Client object.
•Specify the hostname and port of the REST service to which all requests are to be directed.
•Add required HTTP headers for authentication and content type.
•Send a GET request for the “vservers” resource in order to return a list of all Virtual Servers on the system.
•Check the response body, and decode from JSON into a Perl structure. This value is a hash ref.
•Identify the “children” hash key, and iterate through the array to which it points.
•Each array item contains a hash of “name” and “href” associative values.
•Using the “name” value, perform a new GET request to return the full configuration for this named virtual server resource.
•Again, using the decoded JSON response body, identify the Boolean value of the “enabled” key in the “basic” configuration section. If it is “true”, this virtual server is running so print it’s name to STDOUT.
ATTENTION
This script does not contain any error checking in order to best demonstrate the basic functionality. It is strongly recommended you incorporate return value checking and other validation mechanisms as appropriate.
#!/usr/bin/perl
use REST::Client;
use JSON;
use strict;
# Set up the connection
my $client = REST::Client->new();
$client->setHost( 'https://myhost:9070' );
$client->addHeader( 'Authorization', 'Basic YWRtaW46am9iYmll' );
$client->addHeader( 'Content-Type', 'application/json' );
# Request a list of all virtual servers
client->GET( '/api/tm/8.3/config/active/vservers' );
# Decode response into a perl structure for easy parsing
my $response = decode_json( $client->responseContent() );
# Obtain a reference to the children array
my $vsArrayRef = $response->{children};
# For each VS, make a request for its configuration and
# check the Boolean value of the 'enabled' key
foreach my $vs ( @$vsArrayRef ) {
my $vsName = $vs->{name};
$client->GET( "/api/tm/8.3/config/active/vservers/$vsName" );
my $vsConfig = decode_json( $client->responseContent() );
if( $vsConfig->{properties}->{basic}->{enabled} eq "true" ) {
# Print the name of this matched VS
print "$vsn\n";
}
}
The expected output of a script such as this would be:
$ ./listVS.pl
Main Website
Intranet
Support Site