Documentation

1.2.2 Loops

Loops

With loops, you can execute an Action or set of Actions repeatedly until certain conditions are met. To create a loop, start by dragging a line from the exit point of any Action to the entry point of either the Action itself or another Action that appears earlier in the Pipeline.

When configuring an Action’s coordination flow to “Run once for first”, this would result in the Action looping back to execute itself infinitely. It would also trigger the following action(s) to pass through the loop. To prevent this, we must use code and conditions to make the loop behave according to our design.

Loop Example: Creating Subnets from Configuration

In this example, there are JSON configurations that contain some number of subnets, ranging from one to a dozen, depending on the configuration. The Action must create one virtual subnet for each subnet listed in the configuration.

Kaholo exposes configuration in the JavaScript context, so the total number of subnets in the configuration is simply:

 kaholo.execution.configuration.Subnets.length

In the Code page, we create a looping variable to represent the index in the array of subnets:

 var subnetLoopVar = 0

In order to make the looping variable increment with each pass through the loop, we use a post-execution function. Later in the Pipeline, we’ll need the “subnetId” of the subnets created, so in the same function we stash that information in an array.

 function subnetPostExe() {
     stashedSubnetIds[subnetLoopVar] = kaholo.actions.createSubnet.result.createSubnet.Subnet.SubnetId;
     subnetLoopVar++;
 }

Next, in the Advanced configuration tab of the Action, you can configure it as follows:

Conditional Code:

 subnetLoopVar < kaholo.execution.configuration.Subnets.length

Post-Execution Function:

 subnetPostExe()

Action Coordination:

And then, to make the following Action trigger only when the loop is finished, you can do the following:

Conditional Code (for the following Action):

 subnetLoopVar == kaholo.execution.configuration.Subnets.length

Finally, in the Action that creates subnets, the Parameters use the looping variable with the Configuration. For parameter “CIDR Block” you can use this:

 kaholo.execution.configuration.Subnets[subnetLoopVar].CIDR

Loop Results

The Pipeline is now ready for execution. The results (see below) show that the flow control works as designed. This configuration has four subnets. The first three actions trigger the next action (Create Route Table). However, the Conditional Code is not satisfied, so the Action is skipped, as indicated by the white dots.

The route table got created only after the fourth pass of the loop. The Create Subnets Action is finally skipped on the fifth attempt because the looping is finished – the Configuration has only four subnets. Associate Route is then the final Action of the Pipeline.

Page Contents