O Operation Orchestration Service (OOS) oferece a propriedade Loop especial para tarefas. Essa propriedade permite executar uma única tarefa em loop.
Tarefas de ações da classe API e de ações de product aceitam loops. No entanto, tarefas de ações funcionais, como Trigger e Sleep, não oferecem suporte a loops.
Os loops de tarefas permitem execução simultânea. Contudo, no modo de etapa única, as tarefas em loop são executadas sequencialmente, e não simultaneamente.
Limitações
A lista Items em um Loop pode conter no máximo 1.000 itens.
Sintaxe
Estrutura YAML
---
Tasks:
- Name: TaskName1 # Required. The name of the task. Valid characters are letters, digits, underscores (_), and hyphens (-). The name can be up to 200 characters long. Use camel case, such as StartInstance.
Action: TaskType # Required. The task type, also called an action. For more information, see the documentation about actions.
Description: description # Optional. A description of the task.
Properties: # The property list varies based on the action used. For more information, see the documentation about actions.
Property1: Value1 # The properties and values required by the action.
Outputs: # The response parameters of the current task. They can be used as inputs for subsequent tasks or as outputs for the template.
OutputParameterName1:
Type: TypeName # Optional. The type of the response parameter. The default is String.
ValueSelector: "jq selector" # If the task is an OpenAPI call, the result of the call is treated as a JSON input. Use a jq expression to extract the required value from the JSON. For more information, see examples in cloud product actions and public templates.
Loop:
Items: [i-id1,i-id2,i-id3,i-id4] # Required. The loop elements. Accepts a list of items. Each item is used as a parameter for an execution of the loop task. You can also use a parameter name that resolves to a list, such as {{describeInstance.InstanceIds}}.
RateControl:
MaxErrors: 0 # Optional. The maximum number of errors allowed. You can specify a number or a percentage, such as 10 or 10%. The default is 0.
Mode: "Batch/Concurrency" # Required. The mode for controlling the loop execution rate. Options are Concurrency or Batch. Concurrency means concurrent execution. Batch means batch execution.
Batch: [1, 2, 3] # Optional. This parameter takes effect when Mode is set to Batch. It specifies the batch control. For information about how to define batches, see the batch control section below.
ConcurrencyInBatches: [1, 1, 1] # Optional. This parameter takes effect when Mode is set to Batch. It controls the concurrency for each batch. The default is 20. To define it, enter the concurrency for each batch in [].
Concurrency: 1 # Optional. This parameter takes effect when Mode is set to Concurrency. It controls the concurrency for all executions. You can specify a number or a percentage. The default is 1.
BatchPauseOption: "FirstBatchPause/Automatic/EveryBatchPause" # Optional. This parameter takes effect when Mode is set to Batch. It specifies the pause option after each batch completes. Options are FirstBatchPause, Automatic, and EveryBatchPause. FirstBatchPause pauses after the first batch. Automatic runs without pausing. EveryBatchPause pauses after every batch.
Outputs:
FinalOutputParameterName1: # The name of the parameter that is output after the loop task is processed by a function.
AggregateType: BuiltInFunctionName1 # Select a built-in function to aggregate the outputs, such as Fn::Sum, Fn::Max, or Fn::ListJoin.
AggregateField: OutputParameterName1 # The name of the response parameter from the execution of a loop element.
Estrutura JSON (veja os comentários no exemplo YAML para obter detalhes)
{
"Tasks": [
{
"Name": "TaskName1",
"Action": "TaskType",
"Description": "description",
"Properties": {
"Property1": "Value1"
},
"Outputs": {
"OutputParameterName1": {
"Type": "TypeName",
"ValueSelector": "jq selector"
}
},
"Loop": {
"Items": [
"i-id1",
"i-id2",
"i-id3",
"i-id4"
],
"RateControl": {
"MaxErrors": 0,
"Mode": "Concurrency/Batch",
"Batch": [
1,
2,
3
],
"ConcurrencyInBatches": [
1,
1,
1
],
"Concurrency": 1,
"BatchPauseOption": "FirstBatchPause/Automatic/EveryBatchPause"
},
"Outputs": {
"FinalOutputParameterName1": {
"AggregateType": "BuiltInFunctionName1",
"AggregateField": "OutputParameterName1"
}
}
}
}
]
}
A lista Items
A propriedade Items aceita uma lista, como uma lista literal: [item1, item2, item3].
Alternativamente, a propriedade Items pode referenciar o nome de um parâmetro do tipo lista, como os Outputs de uma tarefa anterior.
-
Items como lista.
YAML
Loop: Items: [item1,item2,item3,item4] # A list of items, such as [i-id1,i-id2,i-id3,i-id4]. Each item is used as a parameter for an execution of the task that contains the Loop.JSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Items": [ "item1", "item2", "item3", "item4" ] } -
Items como nome de parâmetro do tipo lista.
YAML
Items: '{{ParameterName1}}' # A parameter name that can be resolved to a list, such as describeInstance.InstanceIds. Each item is used as a parameter for an execution of the task that contains the Loop.JSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Items": "{{ParameterName1}}" }
Controle de taxa de execução do loop
Há dois modos disponíveis:
Controle de simultaneidade: executa os itens simultaneamente a uma taxa especificada até que todos sejam processados.
Controle de lote: divide os itens em lotes de tamanho definido. O próximo lote só inicia após a conclusão do anterior.
Controle de simultaneidade (Concurrency)
-
Por exemplo, se Items contiver 10 itens e Concurrency for 3, o sistema executa três itens simultaneamente até que todos sejam processados.
YAML
Concurrency: 3 # Allows a number or percentage for concurrency control, such as 3. Mode: ConcurrencyJSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Concurrency": 3, "Mode": "Concurrency" } -
Como outro exemplo, se Items contiver 10 itens e Concurrency for 20%, a simultaneidade será 2 (20% de 10). O sistema executa dois itens simultaneamente até que todos sejam processados.
YAML
Concurrency: 20% # Optional. You can specify a number or a percentage, such as 20%. Mode: ConcurrencyJSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Concurrency": "20%", "Mode": "Concurrency" }
Controle de lote (Batch)
-
Suponha que Items contenha 10 itens e Batch seja [3]. Nesse caso, os itens são divididos em lotes de 3. Isso resulta em quatro lotes com tamanhos de 3, 3, 3 e 1, considerando que todas as execuções dos itens tenham sucesso.
YAML
Batch: [1, 2, 3] # Optional. You can define batch control using a list of numbers or percentages, such as [3]. Mode: BatchJSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Batch": [ 1, 2, 3 ], "Mode": "Batch" } -
Se Items contiver 10 itens e Batch for [30%], o tamanho do lote será 3 (30% de 10). Isso gera quatro lotes com tamanhos de 3, 3, 3 e 1, assumindo que todas as execuções dos itens tenham sucesso:
YAML
Batch: [30%] # Optional. You can define batch control using a list of numbers or percentages, such as [30%]. Mode: BatchJSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Batch": [ "30%" ], "Mode": "Batch" } -
Quando Items contém 10 itens e Batch é [3, 10%, 30%], o primeiro lote tem tamanho 3, o segundo tem 1 (10% de 10) e o terceiro e subsequentes têm 3 (30% de 10). Isso resulta em quatro lotes com tamanhos de 3, 1, 3 e 3, desde que todas as execuções dos itens tenham sucesso.
YAML
Mode: Batch Batch: [3, 10%,30%] # Optional. You can define batch control using a list that contains multiple numbers or percentages, such as [3, 10%, 30%].JSON (veja os comentários no exemplo YAML para obter detalhes)
{ "Mode": "Batch", "Batch": [ 3, "10%", "30%" ] }
Controle de erros com MaxErrors
É possível definir a propriedade MaxErrors em um Loop. Essa propriedade funciona da seguinte maneira:
Especifique um número ou uma porcentagem do total de itens. Por exemplo, 10 ou 10%. O valor padrão é 0, o que significa que, se qualquer item falhar, toda a tarefa em loop será marcada como falha.
O primeiro item do loop é sempre executado.
-
A execução dos itens subsequentes depende de o número de erros (ErrorCount) exceder ou não o valor de MaxErrors.
Caso o número de erros ultrapasse o valor de MaxErrors, o loop interrompe a execução dos itens seguintes e a tarefa em loop é marcada como falha.
Se o número de erros for menor ou igual ao valor de MaxErrors, o loop continua a execução.
O status final da tarefa em loop é determinado pela comparação entre o ErrorCount total e MaxErrors. Se ErrorCount for maior que MaxErrors, a tarefa é marcada como Failed. Caso contrário, é marcada como Success.
-
Defina como número.
-
YAML
MaxErrors: 2 # Optional. You can specify a number or a percentage. For example, 2 means the maximum allowed ErrorCount is 2. -
JSON (veja os comentários no exemplo YAML para obter detalhes)
{ "MaxErrors": 2 }
-
-
Defina como porcentagem.
-
YAML
MaxErrors: 25% # Optional. You can specify a number or a percentage. For example, for 4 items, 25% means the maximum allowed ErrorCount is 25% × 4 = 1. -
JSON (veja os comentários no exemplo YAML para obter detalhes)
{ "MaxErrors": "25%" }
-
Saídas do loop
Um Loop em uma tarefa ou modelo pode gerar saídas. A saída final de um Loop é uma agregação das saídas da execução de cada item. Defina a propriedade AggregateType para selecionar uma função integrada responsável por essa agregação.
Configure a propriedade AggregateType.
YAML
AggregateType: Fn::Max # Select a built-in function to aggregate the Loop outputs, such as Fn::Max. This means the largest value of the Number-type OutputParameterName1 from all sub-task outputs is used as the Loop's output value.
JSON (veja os comentários no exemplo YAML para obter detalhes)
{
"AggregateType": "Fn::Max"
}
Exemplos
Modo simultâneo
Formato YAML
FormatVersion: OOS-2019-06-01
Description: Creates one or more ECS instances.
Parameters:
regionId:
Description: The ID of region.
Type: String
Default: '{{ ACS::RegionId }}'
imageId:
Description: The ID of the image resource that you specify when you create the
instance.
Type: String
AllowedPattern: '[A-Za-z0-9_\-\.]*'
MinLength: 1
MaxLength: 100
instanceType:
Description: The type of the instance.
Type: String
AllowedPattern: ecs\.[A-Za-z0-9\.\-]*
MaxLength: 30
MinLength: 1
securityGroupId:
Description: The ID of the security group to which the instance belongs.
Type: String
AllowedPattern: sg-[A-Za-z0-9]*
MaxLength: 30
MinLength: 1
vSwitchId:
Description: The ID of the VSwitch.
Type: String
AllowedPattern: vsw-[A-Za-z0-9]*
MaxLength: 30
MinLength: 1
amount:
Description: The specified number of instances you want to create.
Type: Number
Default: 1
internetMaxBandwidthIn:
Description: The maximum inbound public bandwidth.
Type: Number
Default: 200
internetMaxBandwidthOut:
Description: The maximum outbound public bandwidth.
Type: Number
Default: 0
Tasks:
- Name: runInstances
Action: ACS::ExecuteAPI
Description: Creates one or more instances.
Properties:
Service: ECS
API: RunInstances
Parameters:
RegionId: '{{ regionId }}'
Amount: '{{ amount }}'
ImageId: '{{ imageId }}'
InstanceType: '{{ instanceType }}'
SecurityGroupId: '{{ securityGroupId }}'
VSwitchId: '{{ vSwitchId }}'
InternetMaxBandwidthIn: '{{ internetMaxBandwidthIn }}'
InternetMaxBandwidthOut: '{{ internetMaxBandwidthOut }}'
Outputs:
instanceIds:
Type: List
ValueSelector: InstanceIdSets.InstanceIdSet[]
- Name: untilInstanceReady
Action: ACS::WaitFor
Description: Waits for the created instances to be Running.
Properties:
Service: ECS
API: DescribeInstances
Parameters:
RegionId: '{{ regionId }}'
InstanceIds:
- '{{ ACS::TaskLoopItem }}'
DesiredValues:
- Running
PropertySelector: Instances.Instance[].Status
Loop:
RateControl:
Mode: Concurrency
MaxErrors: 0
Concurrency: 1
Items: '{{ runInstances.instanceIds }}'
Outputs:
instanceIds:
Type: List
Value: '{{ runInstances.instanceIds }}'
Formato JSON
{
"FormatVersion": "OOS-2019-06-01",
"Description": "Creates one or more ECS instances.",
"Parameters": {
"regionId": {
"Description": "The ID of region.",
"Type": "String",
"Default": "{{ ACS::RegionId }}"
},
"imageId": {
"Description": "The ID of the image resource that you specify when you create the instance.",
"Type": "String",
"AllowedPattern": "[A-Za-z0-9_\\-\\.]*",
"MinLength": 1,
"MaxLength": 100
},
"instanceType": {
"Description": "The type of the instance.",
"Type": "String",
"AllowedPattern": "ecs\\.[A-Za-z0-9\\.\\-]*",
"MaxLength": 30,
"MinLength": 1
},
"securityGroupId": {
"Description": "The ID of the security group to which the instance belongs.",
"Type": "String",
"AllowedPattern": "sg-[A-Za-z0-9]*",
"MaxLength": 30,
"MinLength": 1
},
"vSwitchId": {
"Description": "The ID of the VSwitch.",
"Type": "String",
"AllowedPattern": "vsw-[A-Za-z0-9]*",
"MaxLength": 30,
"MinLength": 1
},
"amount": {
"Description": "The specified number of instances you want to create.",
"Type": "Number",
"Default": 1
},
"internetMaxBandwidthIn": {
"Description": "The maximum inbound public bandwidth.",
"Type": "Number",
"Default": 200
},
"internetMaxBandwidthOut": {
"Description": "The maximum outbound public bandwidth.",
"Type": "Number",
"Default": 0
}
},
"Tasks": [
{
"Name": "runInstances",
"Action": "ACS::ExecuteAPI",
"Description": "Creates one or more instances.",
"Properties": {
"Service": "ECS",
"API": "RunInstances",
"Parameters": {
"RegionId": "{{ regionId }}",
"Amount": "{{ amount }}",
"ImageId": "{{ imageId }}",
"InstanceType": "{{ instanceType }}",
"SecurityGroupId": "{{ securityGroupId }}",
"VSwitchId": "{{ vSwitchId }}",
"InternetMaxBandwidthIn": "{{ internetMaxBandwidthIn }}",
"InternetMaxBandwidthOut": "{{ internetMaxBandwidthOut }}"
}
},
"Outputs": {
"instanceIds": {
"Type": "List",
"ValueSelector": "InstanceIdSets.InstanceIdSet[]"
}
}
},
{
"Name": "untilInstanceReady",
"Action": "ACS::WaitFor",
"Description": "Waits for the created instances to be Running.",
"Properties": {
"Service": "ECS",
"API": "DescribeInstances",
"Parameters": {
"RegionId": "{{ regionId }}",
"InstanceIds": [
"{{ ACS::TaskLoopItem }}"
]
},
"DesiredValues": [
"Running"
],
"PropertySelector": "Instances.Instance[].Status"
},
"Loop": {
"RateControl": {
"Mode": "Concurrency",
"MaxErrors": 0,
"Concurrency": 1
},
"Items": "{{ runInstances.instanceIds }}"
}
}
],
"Outputs": {
"instanceIds": {
"Type": "List",
"Value": "{{ runInstances.instanceIds }}"
}
}
}
Modo em lote
Formato YAML
FormatVersion: OOS-2019-06-01
Description: Creates one or more ECS instances.
Parameters:
regionId:
Description: The ID of region.
Type: String
Default: '{{ ACS::RegionId }}'
imageId:
Description: The ID of the image resource that you specify when you create the
instance.
Type: String
AllowedPattern: '[A-Za-z0-9_\-\.]*'
MinLength: 1
MaxLength: 100
instanceType:
Description: The type of the instance.
Type: String
AllowedPattern: ecs\.[A-Za-z0-9\.\-]*
MaxLength: 30
MinLength: 1
securityGroupId:
Description: The ID of the security group to which the instance belongs.
Type: String
AllowedPattern: sg-[A-Za-z0-9]*
MaxLength: 30
MinLength: 1
vSwitchId:
Description: The ID of the VSwitch.
Type: String
AllowedPattern: vsw-[A-Za-z0-9]*
MaxLength: 30
MinLength: 1
amount:
Description: The specified number of instances you want to create.
Type: Number
Default: 1
internetMaxBandwidthIn:
Description: The maximum inbound public bandwidth.
Type: Number
Default: 200
internetMaxBandwidthOut:
Description: The maximum outbound public bandwidth.
Type: Number
Default: 0
Tasks:
- Name: runInstances
Action: ACS::ExecuteAPI
Description: Creates one or more instances.
Properties:
Service: ECS
API: RunInstances
Parameters:
RegionId: '{{ regionId }}'
Amount: '{{ amount }}'
ImageId: '{{ imageId }}'
InstanceType: '{{ instanceType }}'
SecurityGroupId: '{{ securityGroupId }}'
VSwitchId: '{{ vSwitchId }}'
InternetMaxBandwidthIn: '{{ internetMaxBandwidthIn }}'
InternetMaxBandwidthOut: '{{ internetMaxBandwidthOut }}'
Outputs:
instanceIds:
Type: List
ValueSelector: InstanceIdSets.InstanceIdSet[]
- Name: untilInstanceReady
Action: ACS::WaitFor
Description: Waits for the created instances to be Running.
Properties:
Service: ECS
API: DescribeInstances
Parameters:
RegionId: '{{ regionId }}'
InstanceIds:
- '{{ ACS::TaskLoopItem }}'
DesiredValues:
- Running
PropertySelector: Instances.Instance[].Status
Loop:
RateControl:
Mode: Concurrency
MaxErrors: 0
Concurrency: 1
Items: '{{ runInstances.instanceIds }}'
Outputs:
instanceIds:
Type: List
Value: '{{ runInstances.instanceIds }}'
Formato JSON
{
"FormatVersion": "OOS-2019-06-01",
"Description": "Creates one or more ECS instances.",
"Parameters": {
"regionId": {
"Description": "The ID of region.",
"Type": "String",
"Default": "{{ ACS::RegionId }}"
},
"imageId": {
"Description": "The ID of the image resource that you specify when you create the instance.",
"Type": "String",
"AllowedPattern": "[A-Za-z0-9_\\-\\.]*",
"MinLength": 1,
"MaxLength": 100
},
"instanceType": {
"Description": "The type of the instance.",
"Type": "String",
"AllowedPattern": "ecs\\.[A-Za-z0-9\\.\\-]*",
"MaxLength": 30,
"MinLength": 1
},
"securityGroupId": {
"Description": "The ID of the security group to which the instance belongs.",
"Type": "String",
"AllowedPattern": "sg-[A-Za-z0-9]*",
"MaxLength": 30,
"MinLength": 1
},
"vSwitchId": {
"Description": "The ID of the VSwitch.",
"Type": "String",
"AllowedPattern": "vsw-[A-Za-z0-9]*",
"MaxLength": 30,
"MinLength": 1
},
"amount": {
"Description": "The specified number of instances you want to create.",
"Type": "Number",
"Default": 1
},
"internetMaxBandwidthIn": {
"Description": "The maximum inbound public bandwidth.",
"Type": "Number",
"Default": 200
},
"internetMaxBandwidthOut": {
"Description": "The maximum outbound public bandwidth.",
"Type": "Number",
"Default": 0
}
},
"Tasks": [
{
"Name": "runInstances",
"Action": "ACS::ExecuteAPI",
"Description": "Creates one or more instances.",
"Properties": {
"Service": "ECS",
"API": "RunInstances",
"Parameters": {
"RegionId": "{{ regionId }}",
"Amount": "{{ amount }}",
"ImageId": "{{ imageId }}",
"InstanceType": "{{ instanceType }}",
"SecurityGroupId": "{{ securityGroupId }}",
"VSwitchId": "{{ vSwitchId }}",
"InternetMaxBandwidthIn": "{{ internetMaxBandwidthIn }}",
"InternetMaxBandwidthOut": "{{ internetMaxBandwidthOut }}"
}
},
"Outputs": {
"instanceIds": {
"Type": "List",
"ValueSelector": "InstanceIdSets.InstanceIdSet[]"
}
}
},
{
"Name": "untilInstanceReady",
"Action": "ACS::WaitFor",
"Description": "Waits for the created instances to be Running.",
"Properties": {
"Service": "ECS",
"API": "DescribeInstances",
"Parameters": {
"RegionId": "{{ regionId }}",
"InstanceIds": [
"{{ ACS::TaskLoopItem }}"
]
},
"DesiredValues": [
"Running"
],
"PropertySelector": "Instances.Instance[].Status"
},
"Loop": {
"RateControl": {
"Mode": "Concurrency",
"MaxErrors": 0,
"Concurrency": 1
},
"Items": "{{ runInstances.instanceIds }}"
}
}
],
"Outputs": {
"instanceIds": {
"Type": "List",
"Value": "{{ runInstances.instanceIds }}"
}
}
}