In the previous articles in the Getting Started with iControl series, we covered the history of iControl, taxonomy, and introduced the languages most common to our community. In this article, we'll start looking at some code samples. With each task we cover, we'll show an example for a few languages for both the soap and rest interface. The sheer amount of space in this article required to show full samples of each language for both soap and rest would be overwhelming in line, so for the sample code, we have pulled out the appropriate sections of the code for you to study. Understand that based on the libraries used, if at all, some of the work may be abstracted. Full scripts for each language and portal preference are linked at the bottom of this article. If you click each of the iControl REST and iControl SOAP tabs, you'll see a language listing for the sample code provided. Joe Pruitt is the super hero providing everything not python here, so give him a shout out next time you see him in these parts.

Note: This article published by Jason Rahm but co-authored with Joe Pruitt.

With all the disclaimers out of the way, let's get down to business! The first thing you have to do to talk to the BIG-IP is know where to connect. Some prerequisites:

  • BIG-IP Hostname
  • Username
  • Password
  • Portal URL
    • rest: https://host/mgmt/<tm> (most calls are for /tm, though there are others)
    • soap: https://host/iControl/iControlPortal.cgi

There are dozens of articles and codeshare samples on DevCentral on creating/modifying objects both in rest and soap, so we're not going to cover all the details ad nauseam here. But we do want to introduce the basic concepts of retrieving, creating, and modifying a couple simple objects in this article. The first one we'll tackle is one of the most important building blocks of the BIG-IP configuration: the pool.


Working with the Pool Object

The pool has many attributes that can be set, but not all are required. In this exercise however, we're going to simply demonstrate the creation of a pool and a pool listing. The pool object can be created via rest with a simple name, and with soap with the name, the lb method, and the members attribute (it can be empty, but the attribute needs to be present.)

Java SOAP Example

	public void displayAllPools() throws Exception
	{
		String [] pool_list = m_interfaces.getLocalLBPool().get_list();
		System.out.println("Pools\n");
		System.out.println("-----------\n");
		for(int i=0; i<pool_list.length; i++)
		{
			System.out.println(pool_list[i]);
		}
	}

	public void createPool(String poolname, String partition) throws Exception
	{
		String [] pool_list = new String[] {"/" + partition + "/" + poolname};
		iControl.LocalLBLBMethod [] lb_methods = new iControl.LocalLBLBMethod[] { iControl.LocalLBLBMethod.LB_METHOD_ROUND_ROBIN };
		iControl.CommonIPPortDefinition[][] membersAofA = new iControl.CommonIPPortDefinition[1][];
		membersAofA[0] = new iControl.CommonIPPortDefinition[1];
		membersAofA[0][0] = new iControl.CommonIPPortDefinition();
		membersAofA[0][0].setAddress("10.10.10.10");
		membersAofA[0][0].setPort(80);
		
		m_interfaces.getLocalLBPool().create(
			pool_list,
			lb_methods,
			membersAofA
		);

		System.out.println("Pool " + poolname + " created in partition " + partition);
	}

Perl SOAP Example

#----------------------------------------------------------------------------
# getPoolList
#----------------------------------------------------------------------------
sub getPoolList()
{
	$soapResponse = $Pool->get_list();
	&checkResponse($soapResponse);
	my @pool_list = @{$soapResponse->result};
	print "POOL LIST\n";
	print "---------\n";
	foreach $pool (@pool_list) {
		print "  ${pool}\n";
	}
}
#----------------------------------------------------------------------------
# createPool()
#----------------------------------------------------------------------------
sub createPool()
{
	my ($partition, $pool) = @_;

	print "CREATING POOL $pool\n";

	my @pool_names = [$pool];
	my @lb_methods = ["LB_METHOD_ROUND_ROBIN"]; 
  $member = 
  {
    address => "10.10.10.10",
    port => 80
  };
  
  # memberA is the 1st dimension of the array, we need one for each pool
  push @memberA, $member;
  # memberAofA is the 2nd dimension. push pool members for each pool here.
  push @memberAofA, [@memberA];

	$soapResponse = $Pool->create(
		SOAP::Data->name( pool_names => ["/$partition/$pool"]),
		SOAP::Data->name( lb_methods => ["LB_METHOD_ROUND_ROBIN"]),
    SOAP::Data->name(members => [@memberAofA])
	);
	&checkResponse($soapResponse);

	print "POOL ${pool} created in partition ${partition}...\n";
}

Powershell SOAP Example

#----------------------------------------------------------------------------
function Get-PoolList()
#----------------------------------------------------------------------------
{
  $pool_list = $(Get-F5.iControl).LocalLBPool.get_list();
	Write-Host "POOL LIST";
	Write-Host "---------";
  foreach($pool in $pool_list)
  {
		Write-Host "  $pool";
	}
}
#----------------------------------------------------------------------------
function Create-Pool()
#
#  Description:
#    This function creates a new pool if the given pool name doesn't
#    already exist.
#
#  Parameters:
#    Name       - The Name of the pool you wish to create.
#    MemberList - A string list of pool member addresses.
#    MemberPort - The port the pool members will be configured with.
#----------------------------------------------------------------------------
{
  param(
    [string]$Name,
    [string[]]$MemberList,
    [int]$MemberPort
  );
  
  $IPPortDefList = New-Object -TypeName iControl.CommonIPPortDefinition[] $MemberList.Length;
  for($i=0; $i-lt$MemberList.Length; $i++)
  {
    $IPPortDefList[$i] = New-Object -TypeName iControl.CommonIPPortDefinition;
    $IPPortDefList[$i].address = $MemberList[$i];
    $IPPortDefList[$i].port = $MemberPort;
  }
    
  Write-Host "Creating Pool $Name";
  $(Get-F5.iControl).LocalLBPool.create(
    (,$Name),
    (,"LB_METHOD_ROUND_ROBIN"),
    (,$IPPortDefList)
  );
  Write-Host "Pool '$Name' Successfully Created";
}

Python SOAP Example

def get_pool_list(bigip):
    try:
        poollist = bigip.LocalLB.Pool.get_list()
        print "POOL LIST"
        print " ---------"
        for pool in poollist:
            print "   %s" % pool

    except Exception, e:
        print e


def create_pool(bigip, pool):
    try:
        bigip.LocalLB.Pool.create_v2([pool], ['LB_METHOD_ROUND_ROBIN'], [[]])
    except Exception, e:
        print e

Node.js REST Example

//--------------------------------------------------------
function handleVERB(verb, resource, body, callback) {
//--------------------------------------------------------
	getAuthToken( function(token) {
		httpRequest(verb, resource, body, null, null, token, function(json) {
			callback(json);
		});
	});
}

//--------------------------------------------------------
function handleGetPoolList(callback) {
//--------------------------------------------------------
	var uri = "/mgmt/tm/ltm/pool";
	handleVERB("GET", uri, null, function(json) {
		callback(json);
	});
}
//--------------------------------------------------------
function handleCreatePool(pool, partition, callback) {
//--------------------------------------------------------	
	var uri = "/mgmt/tm/ltm/pool";
	var body = '{"name":"' + pool + '", "partition":"' + partition + '"}';

	console.log("BODY: " + body);
	handleVERB("POST", uri, body, function(json) {
		callback(json);
	});
}

Perl REST Example

#---------------------------------------------------
sub getPoolList() {
#---------------------------------------------------
	$resp_json = &handleGET("/mgmt/tm/ltm/pool");
	$resp = decode_json($resp_json);
	@items = @{$resp->{"items"}};

	print "POOL NAMES\n";
	print "----------\n";
	foreach $item (@items) {
		$fullPath = $item->{"fullPath"};
		print "  $fullPath\n";
		print Dumper($item);
	}
}
#---------------------------------------------------
sub handleGET() {
#---------------------------------------------------
	my ($resource) = @_;

	$url = &buildURL($resource);

	$resp = &getHttpRequest($url);

	return $resp;
}
#---------------------------------------------------
sub createPool() {
#---------------------------------------------------
	my ($pool, $partition) = @_;

	my $poolObj;
	$poolObj->{"name"} = $pool;
	$poolObj->{"partition"} = $partition;

	my $json = encode_json($poolObj);

print "JSON: $json\n";
exit();

	$resp = &handlePOST("/mgmt/tm/ltm/pool", $json);

	print Dumper($resp);
}
#---------------------------------------------------
sub handlePOST() {
#---------------------------------------------------
	my ($resource, $body) = @_;

	if ( $body eq "" ) { &usage(); }

	$url = &buildURL($resource);

	$resp = &postHttpRequest($url, $body);

	return $resp;
}

Powershell REST Example

#----------------------------------------------------------------------------
function Get-PoolList()
#----------------------------------------------------------------------------
{
	$uri = "/mgmt/tm/ltm/pool";
	$link = "https://$Bigip$uri";
	$headers = @{};
	$headers.Add("ServerHost", $Bigip);

	$secpasswd = ConvertTo-SecureString $Pass -AsPlainText -Force
	$mycreds = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)

	$obj = Invoke-RestMethod -Method GET -Headers $headers -Uri $link -Credential $mycreds
	$items = $obj.items;
	Write-Host "POOL NAMES";
	Write-Host "----------";
	for($i=0; $i -lt $items.length; $i++) {
		$name = $items[$i].fullPath;
		Write-Host "  $name";
	}
}
#----------------------------------------------------------------------------
function Create-Pool()
#
#  Description:
#    This function creates a new pool if the given pool name doesn't
#    already exist.
#
#  Parameters:
#    Name       - The Name of the pool you wish to create.
#    Partition  - The name of the partition to place the pool in.
#----------------------------------------------------------------------------
{
  param(
    [string]$Name,
		[string]$Partition
  );

	$uri = "/mgmt/tm/ltm/pool";
	$link = "https://$Bigip$uri";
	$headers = @{};
	$headers.Add("ServerHost", $Bigip);
	$headers.Add("Content-Type", "application/json");
	$obj = @{
		name=$Name
		partition=$Partition
	};
	$body = $obj | ConvertTo-Json

	$secpasswd = ConvertTo-SecureString $Pass -AsPlainText -Force
	$mycreds = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)

	$obj = Invoke-RestMethod -Method POST -Uri $link -Headers $headers -Credential $mycreds -Body $body;

	Write-Host "Pool ${Name} created in partition ${Partition}"
}

Python REST Example

def get_pool_list(bigip, url):
    try:
        pools = bigip.get("%s/ltm/pool" % url).json()
        print "POOL LIST"
        print " ---------"
        for pool in pools['items']:
            print "   /%s/%s" % (pool['partition'], pool['name'])
    except Exception, e:
        print e


def create_pool(bigip, url, pool, part=None):
    try:
        payload = {}
        payload['name'] = pool
        if part is not None:
            payload['partition'] = part

        pool_config = bigip.post("%s/ltm/pool" % url, json.dumps(payload)).json()
        print pool_config
    except Exception, e:
        print e

Working with the Data-Group Object

Data-groups are interesting objects with which to work, primarily because you can have internal data-groups, which are wholly contained within bigip.conf, and external data-groups, which has it's definition in bigip.conf but the records are kept in an external file. Also interesting is that this particular object has different attributes via soap than it does in rest. In soap, all the records can be individually managed, so you can add, find, and delete on a record by record basis. Not so with rest. In rest we have the concepts of collections and a subcollections. A collection is like a list of pools. A sub-collection would be the members of a pool. Ideally, a data-group itself would be part of a collection, and it's records would be a subcollection, but that is not the case today. This has major implications if you want to update a data-group. Say you have a data-group with 10,000 records. You want add a record, so you issue an HTTP PUT method with your payload of one record. Instead of the desired outcome of a modified data-group with 10,001 records, you now have a much smaller data-group of exactly one record. Not good! So make sure if you are using the rest interface with data-groups, you store all the existing records, make all your adds/changes/deletes, then PUT the entire record collection. But where the soap interface has the upper hand with being able to update individual records, rest punches back with the ability to list out all data-group at once, whereas with soap, you have to query each type of data-group among string, integer, and address. So there are some pros and cons to both approaches to weigh as you dig in.

Java SOAP Example

	public void createDataGroup(String datagroup) throws Exception
	{
		// Create String Class
		iControl.LocalLBClassStringClass [] StringClassA = new iControl.LocalLBClassStringClass[1];
		StringClassA[0] = new iControl.LocalLBClassStringClass();
		StringClassA[0].setName(datagroup);
		StringClassA[0].setMembers(new String [] { "a", "b", "c" });

		m_interfaces.getLocalLBClass().create_string_class(StringClassA);

		// Set Values
		String [][] valuesAofA = new String[1][];
		valuesAofA[0] = new String[] { "data 1", "data 2", "data 3" };

		m_interfaces.getLocalLBClass().set_string_class_member_data_value(
			StringClassA,
			valuesAofA
		);

		getDataGroup(datagroup);
	}
	public void removeFromDataGroup(String datagroup) throws Exception
	{
		String [] names = new String[] {"c"};

		iControl.LocalLBClassStringClass [] StringClassA = new iControl.LocalLBClassStringClass[1];
		StringClassA[0] = new iControl.LocalLBClassStringClass();
		StringClassA[0].setName(datagroup);
		StringClassA[0].setMembers(new String [] { "c" });

		m_interfaces.getLocalLBClass().delete_string_class_member(StringClassA);

		getDataGroup(datagroup);
	}

	//--------------------------------------------------------------------------
	//
	//--------------------------------------------------------------------------
	public void addToDataGroup(String datagroup) throws Exception
	{
		// Create String Class
		iControl.LocalLBClassStringClass [] StringClassA = new iControl.LocalLBClassStringClass[1];
		StringClassA[0] = new iControl.LocalLBClassStringClass();
		StringClassA[0].setName(datagroup);
		StringClassA[0].setMembers(new String [] { "d", "e" });

		m_interfaces.getLocalLBClass().add_string_class_member(StringClassA);

		// Set Values
		String [][] valuesAofA = new String[1][];
		valuesAofA[0] = new String[] { "data 4", "data 5" };

		m_interfaces.getLocalLBClass().set_string_class_member_data_value(
			StringClassA,
			valuesAofA
		);

		getDataGroup(datagroup);
	}

Perl SOAP Example

#----------------------------------------------------------------------------
sub createDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("a", "b", "c");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->create_string_class(
		SOAP::Data->name(classes => [$StringClass])
	);
	&checkResponse($soapResponse);

	# Set values
  # Build Values 2-D Array for values parameter
  my @valuesA = ("data 1", "data 2", "data 3");
  my @valuesAofA;
  push @valuesAofA, [@valuesA];
  $soapResponse = $Class->set_string_class_member_data_value
  (
    SOAP::Data->name(class_members => [$StringClass]),
    SOAP::Data->name(values => [@valuesAofA])
  );
  &checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

#----------------------------------------------------------------------------
sub removeFromDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("c");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->delete_string_class_member(
		SOAP::Data->name(class_members => [$StringClass])
	);
	&checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

#----------------------------------------------------------------------------
sub addToDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("d", "e");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->add_string_class_member(
		SOAP::Data->name(class_members => [$StringClass])
	);
	&checkResponse($soapResponse);

	# Set values
  # Build Values 2-D Array for values parameter
  my @valuesA = ("data 4", "data 5");
  my @valuesAofA;
  push @valuesAofA, [@valuesA];
  $soapResponse = $Class->set_string_class_member_data_value
  (
    SOAP::Data->name(class_members => [$StringClass]),
    SOAP::Data->name(values => [@valuesAofA])
  );
  &checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

Powershell SOAP Example

#-------------------------------------------------------------------------
function Create-DataGroup()
#-------------------------------------------------------------------------
{
	param(
		[string]$Name
	);

	$StringClassA = New-Object -TypeName iControl.LocalLBClassStringClass[] 1;
	$StringClassA[0] = New-Object -TypeName iControl.LocalLBClassStringClass;
	$StringClassA[0].name = $Name;
	$StringClassA[0].members = ("a", "b", "c");

	$(Get-F5.iControl).LocalLBClass.create_string_class(
		$StringClassA
	);

	$DataValueA = ("data 1", "data 2", "data 3");
	$DataValuesAofA = 
	$(Get-F5.iControl).LocalLBClass.set_string_class_member_data_value(
		$StringClassA,
		(, $DataValueA)
	)
		
	Get-DataGroup -Name $Name;
}

#-------------------------------------------------------------------------
function RemoveFrom-DataGroup()
#-------------------------------------------------------------------------
{
	param(
		[string]$Name
	);

	$StringClassA = New-Object -TypeName iControl.LocalLBClassStringClass[] 1;
	$StringClassA[0] = New-Object -TypeName iControl.LocalLBClassStringClass;
	$StringClassA[0].name = $Name;
	$StringClassA[0].members = ("c");

	$(Get-F5.iControl).LocalLBClass.delete_string_class_member(
		$StringClassA
	);
		
	Get-DataGroup -Name $Name;
}

#-------------------------------------------------------------------------
function AddTo-DataGroup()
#-------------------------------------------------------------------------
{
	param(
		[string]$Name
	);

	$StringClassA = New-Object -TypeName iControl.LocalLBClassStringClass[] 1;
	$StringClassA[0] = New-Object -TypeName iControl.LocalLBClassStringClass;
	$StringClassA[0].name = $Name;
	$StringClassA[0].members = ("d", "e");

	$(Get-F5.iControl).LocalLBClass.add_string_class_member(
		$StringClassA
	);

	$DataValueA = ("data 4", "data 5");
	$DataValuesAofA = 
	$(Get-F5.iControl).LocalLBClass.set_string_class_member_data_value(
		$StringClassA,
		(, $DataValueA)
	)
		
	Get-DataGroup -Name $Name;
}

Python SOAP Example

def get_dg_list(bigip):
    try:
        dg_str_list = bigip.LocalLB.Class.get_string_class_list()
        dg_str_names = bigip.LocalLB.Class.get_string_class(dg_str_list)


        for dg in dg_str_names:
            print dg
            print '   Data Group: %s' % dg['name']
            for x in dg['members']:
                print '       %s' % x

    except Exception, e:
        print e


def extend_dg(bigip, dgname, keys, values):
    try:
        bigip.LocalLB.Class.add_string_class_member([{'name': dgname, 'members': keys}])
        bigip.LocalLB.Class.set_string_class_member_data_value([{'name': dgname, 'members': keys}], [[values]])
    except Exception, e:
        print e


def contract_dg(bigip, dgname, keys):
    try:
        bigip.LocalLB.Class.delete_string_class_member([{'name': dgname, 'members': keys}])
    except Exception, e:
        print e


def create_dg(bigip, dgname, keys, values):
    try:
        bigip.LocalLB.Class.create_string_class([{'name': dgname, 'members': keys}])
        bigip.LocalLB.Class.set_string_class_member_data_value([{'name': dgname, 'members': keys}], [[values]])
    except Exception, e:
        print e

Node.js REST Example

//--------------------------------------------------------
function createDataGroup(datagroup) {
//--------------------------------------------------------

	datagroup = datagroup.replace(/\//g, "~");
	var uri = "/mgmt/tm/ltm/data-group/internal";

	var dgObj = {};
	dgObj.name = datagroup;
	dgObj.type = "string";
	dgObj.records = [
		{name: "a", data: "data 1"},
		{name: "b", data: "data 2"},
		{name: "c", data: "data 3"},
	];

	var body = JSON.stringify(dgObj);

	handleVERB("POST", uri, body, function(json) {
		console.log(json);
	});
}

//--------------------------------------------------------
function removeFromDataGroup(datagroup) {
//--------------------------------------------------------
	dg_uri = datagroup.replace(/\//g, "~");
	var uri = "/mgmt/tm/ltm/data-group/internal/" + dg_uri;

	var dgObj = {};
	dgObj.name = datagroup;
	dgObj.records = [
		{name: "a", data: "data 1"},
		{name: "b", data: "data 2"}
	];

	var body = JSON.stringify(dgObj);

	handleVERB("PATCH", uri, body, function(json) {
		console.log(json);
	});
}

//--------------------------------------------------------
function addToDataGroup(datagroup) {
//--------------------------------------------------------
	dg_uri = datagroup.replace(/\//g, "~");
	var uri = "/mgmt/tm/ltm/data-group/internal/" + dg_uri;

	var dgObj = {};
	dgObj.name = datagroup;
	dgObj.records = [
		{name: "a", data: "data 1"},
		{name: "b", data: "data 2"},
		{name: "d", data: "data 4"},
		{name: "e", data: "data 5"}
	];

	var body = JSON.stringify(dgObj);

	handleVERB("PATCH", uri, body, function(json) {
		console.log(json);
	});
}

Perl REST Example

#----------------------------------------------------------------------------
sub createDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("a", "b", "c");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->create_string_class(
		SOAP::Data->name(classes => [$StringClass])
	);
	&checkResponse($soapResponse);

	# Set values
  # Build Values 2-D Array for values parameter
  my @valuesA = ("data 1", "data 2", "data 3");
  my @valuesAofA;
  push @valuesAofA, [@valuesA];
  $soapResponse = $Class->set_string_class_member_data_value
  (
    SOAP::Data->name(class_members => [$StringClass]),
    SOAP::Data->name(values => [@valuesAofA])
  );
  &checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

#----------------------------------------------------------------------------
sub removeFromDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("c");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->delete_string_class_member(
		SOAP::Data->name(class_members => [$StringClass])
	);
	&checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

#----------------------------------------------------------------------------
sub addToDataGroup()
#----------------------------------------------------------------------------
{
	my ($datagroup) = @_;

  my @names = ("d", "e");

  my $StringClass =
  {
    name => $datagroup,
    members => [@names]
  };

	# Create Data group with names
	$soapResponse = $Class->add_string_class_member(
		SOAP::Data->name(class_members => [$StringClass])
	);
	&checkResponse($soapResponse);

	# Set values
  # Build Values 2-D Array for values parameter
  my @valuesA = ("data 4", "data 5");
  my @valuesAofA;
  push @valuesAofA, [@valuesA];
  $soapResponse = $Class->set_string_class_member_data_value
  (
    SOAP::Data->name(class_members => [$StringClass]),
    SOAP::Data->name(values => [@valuesAofA])
  );
  &checkResponse($soapResponse);

	&getDataGroup($datagroup);
}

Powershell REST Example

#----------------------------------------------------------------------------
function Create-DataGroup()
#
#  Description:
#    This function creates a new internal data group
#
#  Parameters:
#    Name       - The Name of the data group
#----------------------------------------------------------------------------
{
  param(
    [string]$Name
  );

	$uri = "/mgmt/tm/ltm/data-group/internal";
	$link = "https://$Bigip$uri";
	$headers = @{};
	$headers.Add("ServerHost", $Bigip);
	$headers.Add("Content-Type", "application/json");
	$obj = @{
		name=$Name
		type="string"
		records= (
			@{ name="a"
				data="data 1"
			},
			@{ name="b"
				data="data 2"
			},
			@{ name="c"
				data="data 3"
			}
		)
	};
	$body = $obj | ConvertTo-Json

	$secpasswd = ConvertTo-SecureString $Pass -AsPlainText -Force
	$mycreds = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)

	$obj = Invoke-RestMethod -Method POST -Uri $link -Headers $headers -Credential $mycreds -Body $body;

	Write-Host "Pool ${Name} created in partition ${Partition}"
}

#----------------------------------------------------------------------------
function RemoveFrom-DataGroup()
#
#  Description:
#    This function removes an entry from a data group
#
#  Parameters:
#    Name       - The Name of the data group
#----------------------------------------------------------------------------
{
  param(
    [string]$Name
  );

	$uri = "/mgmt/tm/ltm/data-group/internal/${Name}";
	$link = "https://$Bigip$uri";
	$headers = @{};
	$headers.Add("ServerHost", $Bigip);
	$headers.Add("Content-Type", "application/json");
	$obj = @{
		name=$Name
		records= (
			@{ name="a"
				data="data 1"
			},
			@{ name="b"
				data="data 2"
			}
		)
	};
	$body = $obj | ConvertTo-Json

	$secpasswd = ConvertTo-SecureString $Pass -AsPlainText -Force
	$mycreds = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)

	$obj = Invoke-RestMethod -Method PATCH -Uri $link -Headers $headers -Credential $mycreds -Body $body;

	$obj | Format-List
}

#----------------------------------------------------------------------------
function AddTo-DataGroup()
#
#  Description:
#    This function adds records to an existing data group
#
#  Parameters:
#    Name       - The Name of the data group
#----------------------------------------------------------------------------
{
  param(
    [string]$Name
  );

	$uri = "/mgmt/tm/ltm/data-group/internal/${Name}";
	$link = "https://$Bigip$uri";
	$headers = @{};
	$headers.Add("ServerHost", $Bigip);
	$headers.Add("Content-Type", "application/json");
	$obj = @{
		name=$Name
		records= (
			@{ name="a"
				data="data 1"
			},
			@{ name="b"
				data="data 2"
			},
			@{ name="d"
				data="data 4"
			},
			@{ name="e"
				data="data 5"
			}
		)
	};
	$body = $obj | ConvertTo-Json

	$secpasswd = ConvertTo-SecureString $Pass -AsPlainText -Force
	$mycreds = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)

	$obj = Invoke-RestMethod -Method PATCH -Uri $link -Headers $headers -Credential $mycreds -Body $body;

	$obj | Format-List
}

Python REST Example

def get_dg_list(rq, url):
    try:
        dg_list = rq.get('%s/ltm/data-group/internal' % url).json()
        for dg in dg_list['items']:
            print dg
            print '   Data Group: %s' % dg['name']
            print '   --------------'
            if 'records' in dg:
                for record in dg['records']:
                    if 'data' in record:
                        print '      %s: %s' % (record['name'], record['data'])
                    else:
                        print '      %s' % record['name']

    except Exception, e:
        print e


def extend_dg(rq, url, dgname, additional_records):
    dg = rq.get('%s/ltm/data-group/internal/%s' % (url, dgname)).json()

    current_records = dg['records']
    new_records = []
    for record in current_records:
        if 'data' in record:
            nr = [{'name': record['name'], 'data': record['data']}]
        else:
            nr = [{'name': record['name']}]
        new_records.extend(nr)
    for record in additional_records:
        if 'data' in record:
            nr = [{'name': record['name'], 'data': record['data']}]
        else:
            nr = [{'name': record['name']}]
        new_records.extend(nr)

    payload = {}
    payload['records'] = new_records
    rq.put('%s/ltm/data-group/internal/%s' % (url, dgname), json.dumps(payload))


def contract_dg(rq, url, dgname, removal_records):
    dg = rq.get('%s/ltm/data-group/internal/%s' % (url, dgname)).json()
    current_records = dg['records']

    new_records = []
    for record in removal_records:
        if 'data' in record:
            nr = [{'name': record['name'], 'data': record['data']}]
        else:
            nr = [{'name': record['name']}]
        new_records.extend(nr)

    new_records = [x for x in current_records if x not in new_records]

    payload = {}
    payload['records'] = new_records
    rq.put('%s/ltm/data-group/internal/%s' % (url, dgname), json.dumps(payload))


def create_dg(rq, url, dgname, records):
    new_records = []
    for record in records:
        if 'data' in record:
            nr = [{'name': record['name'], 'data': record['data']}]
        else:
            nr = [{'name': record['name']}]
        new_records.extend(nr)

    payload = {}
    payload['type'] = 'string'
    payload['name'] = dgname
    payload['records'] = new_records
    try:
        rq.post('%s/ltm/data-group/internal' % url, json.dumps(payload))
    except Exception, e:
        print e

Resources

All the scripts for this article are available in the codeshare under "Getting Started with iControl Code Samples."