Automatizar tarefas de integração de funcionários antes do primeiro dia de trabalho usando APIs de fluxos de trabalho do ciclo de vida
Artigo
Este tutorial fornece diretrizes passo a passo para automatizar tarefas de pré-venda com APIs de fluxos de trabalho do ciclo de vida.
Neste tutorial, você aprende a:
Configure um fluxo de trabalho de ciclo de vida para marcar para novos funcionários em um departamento específico, dois dias antes da data de contratação.
Configure uma tarefa para gerar um TAP (passe de acesso temporário) para o novo funcionário e envie-a para o novo gerente do funcionário.
Monitore o status do fluxo de trabalho e suas tarefas associadas.
Pré-requisitos
Para concluir este tutorial, você precisa dos seguintes recursos e privilégios:
Entre em um cliente de API, como o Graph Explorer chamar o Microsoft Graph com uma conta que tenha pelo menos a função administrador do ciclo de vida Microsoft Entra.
Conceda a si mesmo a permissão delegada LifecycleWorkflows.ReadWrite.All Microsoft Graph.
Crie duas contas de usuário a serem usadas neste tutorial: uma para a nova contratação e outra para seu gerente e tenha as seguintes configurações configuradas conforme aplicável.
Propriedade user
Descrição
Definido como
Email
Usado para notificar o gerente do TAP (passe de acesso temporário) do novo funcionário. O gerente e o funcionário devem ter caixas de correio ativas para receber emails.
Funcionário, Gerente
manager
Esse atributo usado pelo fluxo de trabalho do ciclo de vida.
Funcionário
employeeHireDate
Usado para disparar o fluxo de trabalho. Defina como a data de hoje.
Funcionário
department
Usado para fornecer o escopo do fluxo de trabalho. Definido como Sales
A solicitação a seguir cria um fluxo de trabalho de pré-venda com as seguintes configurações:
Ele pode ser executado sob demanda, mas não agendado.
O fluxo de trabalho é executado dois dias antes da data de contratação do funcionário e se ele estiver no departamento "Vendas".
Apenas uma tarefa interna é executada neste fluxo de trabalho: gerar o TAP e enviá-lo para o gerente do novo contratado. Essa tarefa é identificada nos fluxos de trabalho do ciclo de vida pela tarefaDefinitionId1b555e50-7f65-41d5-b514-5894a026d10d.
POST https://graph.microsoft.com/v1.0/identityGovernance/lifecycleWorkflows/workflows
Content-type: application/json
{
"displayName":"Onboard pre-hire employee",
"description":"Configure pre-hire tasks for onboarding employees before their first day",
"isEnabled":true,
"isSchedulingEnabled": false,
"executionConditions": {
"@odata.type": "microsoft.graph.identityGovernance.triggerAndScopeBasedConditions",
"scope": {
"@odata.type": "microsoft.graph.identityGovernance.ruleBasedSubjectSet",
"rule": "(department eq 'Sales')"
},
"trigger": {
"@odata.type": "microsoft.graph.identityGovernance.timeBasedAttributeTrigger",
"timeBasedAttribute": "employeeHireDate",
"offsetInDays": -2
}
},
"tasks":[
{
"isEnabled":true,
"category": "Joiner",
"taskDefinitionId":"1b555e50-7f65-41d5-b514-5894a026d10d",
"displayName":"Generate TAP And Send Email",
"description":"Generate Temporary Access Pass and send via email to user's manager",
"arguments":[
{
"name": "tapLifetimeMinutes",
"value": "480"
},
{
"name": "tapIsUsableOnce",
"value": "true"
}
]
}
]
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models.IdentityGovernance;
using Microsoft.Graph.Models;
var requestBody = new Workflow
{
DisplayName = "Onboard pre-hire employee",
Description = "Configure pre-hire tasks for onboarding employees before their first day",
IsEnabled = true,
IsSchedulingEnabled = false,
ExecutionConditions = new TriggerAndScopeBasedConditions
{
OdataType = "microsoft.graph.identityGovernance.triggerAndScopeBasedConditions",
Scope = new RuleBasedSubjectSet
{
OdataType = "microsoft.graph.identityGovernance.ruleBasedSubjectSet",
Rule = "(department eq 'Sales')",
},
Trigger = new TimeBasedAttributeTrigger
{
OdataType = "microsoft.graph.identityGovernance.timeBasedAttributeTrigger",
TimeBasedAttribute = WorkflowTriggerTimeBasedAttribute.EmployeeHireDate,
OffsetInDays = -2,
},
},
Tasks = new List<TaskObject>
{
new TaskObject
{
IsEnabled = true,
Category = LifecycleTaskCategory.Joiner,
TaskDefinitionId = "1b555e50-7f65-41d5-b514-5894a026d10d",
DisplayName = "Generate TAP And Send Email",
Description = "Generate Temporary Access Pass and send via email to user's manager",
Arguments = new List<KeyValuePair>
{
new KeyValuePair
{
Name = "tapLifetimeMinutes",
Value = "480",
},
new KeyValuePair
{
Name = "tapIsUsableOnce",
Value = "true",
},
},
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.models.identitygovernance.Workflow workflow = new com.microsoft.graph.models.identitygovernance.Workflow();
workflow.setDisplayName("Onboard pre-hire employee");
workflow.setDescription("Configure pre-hire tasks for onboarding employees before their first day");
workflow.setIsEnabled(true);
workflow.setIsSchedulingEnabled(false);
com.microsoft.graph.models.identitygovernance.TriggerAndScopeBasedConditions executionConditions = new com.microsoft.graph.models.identitygovernance.TriggerAndScopeBasedConditions();
executionConditions.setOdataType("microsoft.graph.identityGovernance.triggerAndScopeBasedConditions");
com.microsoft.graph.models.identitygovernance.RuleBasedSubjectSet scope = new com.microsoft.graph.models.identitygovernance.RuleBasedSubjectSet();
scope.setOdataType("microsoft.graph.identityGovernance.ruleBasedSubjectSet");
scope.setRule("(department eq 'Sales')");
executionConditions.setScope(scope);
com.microsoft.graph.models.identitygovernance.TimeBasedAttributeTrigger trigger = new com.microsoft.graph.models.identitygovernance.TimeBasedAttributeTrigger();
trigger.setOdataType("microsoft.graph.identityGovernance.timeBasedAttributeTrigger");
trigger.setTimeBasedAttribute(com.microsoft.graph.models.identitygovernance.WorkflowTriggerTimeBasedAttribute.EmployeeHireDate);
trigger.setOffsetInDays(-2);
executionConditions.setTrigger(trigger);
workflow.setExecutionConditions(executionConditions);
LinkedList<com.microsoft.graph.models.identitygovernance.Task> tasks = new LinkedList<com.microsoft.graph.models.identitygovernance.Task>();
com.microsoft.graph.models.identitygovernance.Task task = new com.microsoft.graph.models.identitygovernance.Task();
task.setIsEnabled(true);
task.setCategory(EnumSet.of(com.microsoft.graph.models.identitygovernance.LifecycleTaskCategory.Joiner));
task.setTaskDefinitionId("1b555e50-7f65-41d5-b514-5894a026d10d");
task.setDisplayName("Generate TAP And Send Email");
task.setDescription("Generate Temporary Access Pass and send via email to user's manager");
LinkedList<KeyValuePair> arguments = new LinkedList<KeyValuePair>();
KeyValuePair keyValuePair = new KeyValuePair();
keyValuePair.setName("tapLifetimeMinutes");
keyValuePair.setValue("480");
arguments.add(keyValuePair);
KeyValuePair keyValuePair1 = new KeyValuePair();
keyValuePair1.setName("tapIsUsableOnce");
keyValuePair1.setValue("true");
arguments.add(keyValuePair1);
task.setArguments(arguments);
tasks.add(task);
workflow.setTasks(tasks);
com.microsoft.graph.models.identitygovernance.Workflow result = graphClient.identityGovernance().lifecycleWorkflows().workflows().post(workflow);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\Workflow;
use Microsoft\Graph\Generated\Models\TriggerAndScopeBasedConditions;
use Microsoft\Graph\Generated\Models\RuleBasedSubjectSet;
use Microsoft\Graph\Generated\Models\TimeBasedAttributeTrigger;
use Microsoft\Graph\Generated\Models\Task;
use Microsoft\Graph\Generated\Models\KeyValuePair;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Workflow();
$requestBody->setDisplayName('Onboard pre-hire employee');
$requestBody->setDescription('Configure pre-hire tasks for onboarding employees before their first day');
$requestBody->setIsEnabled(true);
$requestBody->setIsSchedulingEnabled(false);
$executionConditions = new TriggerAndScopeBasedConditions();
$executionConditions->setOdataType('microsoft.graph.identityGovernance.triggerAndScopeBasedConditions');
$executionConditionsScope = new RuleBasedSubjectSet();
$executionConditionsScope->setOdataType('microsoft.graph.identityGovernance.ruleBasedSubjectSet');
$executionConditionsScope->setRule('(department eq \'Sales\')');
$executionConditions->setScope($executionConditionsScope);
$executionConditionsTrigger = new TimeBasedAttributeTrigger();
$executionConditionsTrigger->setOdataType('microsoft.graph.identityGovernance.timeBasedAttributeTrigger');
$executionConditionsTrigger->setTimeBasedAttribute(new WorkflowTriggerTimeBasedAttribute('employeeHireDate'));
$executionConditionsTrigger->setOffsetInDays(-2);
$executionConditions->setTrigger($executionConditionsTrigger);
$requestBody->setExecutionConditions($executionConditions);
$tasksTask1 = new Task();
$tasksTask1->setIsEnabled(true);
$tasksTask1->setCategory(new LifecycleTaskCategory('joiner'));
$tasksTask1->setTaskDefinitionId('1b555e50-7f65-41d5-b514-5894a026d10d');
$tasksTask1->setDisplayName('Generate TAP And Send Email');
$tasksTask1->setDescription('Generate Temporary Access Pass and send via email to user\'s manager');
$argumentsKeyValuePair1 = new KeyValuePair();
$argumentsKeyValuePair1->setName('tapLifetimeMinutes');
$argumentsKeyValuePair1->setValue('480');
$argumentsArray []= $argumentsKeyValuePair1;
$argumentsKeyValuePair2 = new KeyValuePair();
$argumentsKeyValuePair2->setName('tapIsUsableOnce');
$argumentsKeyValuePair2->setValue('true');
$argumentsArray []= $argumentsKeyValuePair2;
$tasksTask1->setArguments($argumentsArray);
$tasksArray []= $tasksTask1;
$requestBody->setTasks($tasksArray);
$result = $graphServiceClient->identityGovernance()->lifecycleWorkflows()->workflows()->post($requestBody)->wait();
Como o fluxo de trabalho não está agendado para ser executado, ele deve ser executado manualmente. Na solicitação a seguir, o usuário que é o destino do fluxo de trabalho é identificado pela ID 8930f0c7-cdd7-4885-9260-3b4a8111de5c. A solicitação retorna uma 204 No Content resposta.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.IdentityGovernance.LifecycleWorkflows.Workflows.Item.MicrosoftGraphIdentityGovernanceActivate;
using Microsoft.Graph.Models;
var requestBody = new ActivatePostRequestBody
{
Subjects = new List<User>
{
new User
{
Id = "8930f0c7-cdd7-4885-9260-3b4a8111de5c",
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows["{workflow-id}"].MicrosoftGraphIdentityGovernanceActivate.PostAsync(requestBody);
// THE CLI IS IN PREVIEW. NON-PRODUCTION USE ONLY
mgc identity-governance lifecycle-workflows workflows microsoft-graph-identity-governance-activate post --workflow-id {workflow-id}
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.identitygovernance.lifecycleworkflows.workflows.item.microsoftgraphidentitygovernanceactivate.ActivatePostRequestBody activatePostRequestBody = new com.microsoft.graph.identitygovernance.lifecycleworkflows.workflows.item.microsoftgraphidentitygovernanceactivate.ActivatePostRequestBody();
LinkedList<User> subjects = new LinkedList<User>();
User user = new User();
user.setId("8930f0c7-cdd7-4885-9260-3b4a8111de5c");
subjects.add(user);
activatePostRequestBody.setSubjects(subjects);
graphClient.identityGovernance().lifecycleWorkflows().workflows().byWorkflowId("{workflow-id}").microsoftGraphIdentityGovernanceActivate().post(activatePostRequestBody);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ActivatePostRequestBody;
use Microsoft\Graph\Generated\Models\User;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ActivatePostRequestBody();
$subjectsUser1 = new User();
$subjectsUser1->setId('8930f0c7-cdd7-4885-9260-3b4a8111de5c');
$subjectsArray []= $subjectsUser1;
$requestBody->setSubjects($subjectsArray);
$graphServiceClient->identityGovernance()->lifecycleWorkflows()->workflows()->byWorkflowId('workflow-id')->microsoftGraphIdentityGovernanceActivate()->post($requestBody)->wait();
GET https://graph.microsoft.com/v1.0/identityGovernance/lifecycleWorkflows/workflows/ea71190c-075a-4ae7-9bca-34abf3b7b056/userProcessingResults
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows["{workflow-id}"].UserProcessingResults.GetAsync();
// THE CLI IS IN PREVIEW. NON-PRODUCTION USE ONLY
mgc identity-governance lifecycle-workflows workflows user-processing-results list --workflow-id {workflow-id}
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.models.identitygovernance.UserProcessingResultCollectionResponse result = graphClient.identityGovernance().lifecycleWorkflows().workflows().byWorkflowId("{workflow-id}").userProcessingResults().get();
GET https://graph.microsoft.com/v1.0/identityGovernance/lifecycleWorkflows/workflows/ea71190c-075a-4ae7-9bca-34abf3b7b056/userProcessingResults/summary(startDateTime=2024-03-01T00:00:00Z,endDateTime=2024-03-30T00:00:00Z)
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows["{workflow-id}"].UserProcessingResults.MicrosoftGraphIdentityGovernanceSummaryWithStartDateTimeWithEndDateTime(DateTimeOffset.Parse("{endDateTime}"),DateTimeOffset.Parse("{startDateTime}")).GetAsync();
// THE CLI IS IN PREVIEW. NON-PRODUCTION USE ONLY
mgc identity-governance lifecycle-workflows workflows user-processing-results microsoft-graph-identity-governance-summary-with-start-date-time-with-end-date-time get --start-date-time {start-date-time-id} --end-date-time {end-date-time-id} --workflow-id {workflow-id}
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
var result = graphClient.identityGovernance().lifecycleWorkflows().workflows().byWorkflowId("{workflow-id}").userProcessingResults().microsoftGraphIdentityGovernanceSummaryWithStartDateTimeWithEndDateTime(OffsetDateTime.parse("{endDateTime}"), OffsetDateTime.parse("{startDateTime}")).get();
GET https://graph.microsoft.com/v1.0/identityGovernance/lifecycleWorkflows/workflows/ea71190c-075a-4ae7-9bca-34abf3b7b056/userProcessingResults/5772d894-3bcf-4d1c-9cfc-8c182331215b/taskProcessingResults
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows["{workflow-id}"].UserProcessingResults["{userProcessingResult-id}"].TaskProcessingResults.GetAsync();
// THE CLI IS IN PREVIEW. NON-PRODUCTION USE ONLY
mgc identity-governance lifecycle-workflows workflows user-processing-results task-processing-results list --workflow-id {workflow-id} --user-processing-result-id {userProcessingResult-id}
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.models.identitygovernance.TaskProcessingResultCollectionResponse result = graphClient.identityGovernance().lifecycleWorkflows().workflows().byWorkflowId("{workflow-id}").userProcessingResults().byUserProcessingResultId("{userProcessingResult-id}").taskProcessingResults().get();
[Opcional] Agendar o fluxo de trabalho a ser executado automaticamente
Depois de executar seu fluxo de trabalho sob demanda e verificar se tudo está funcionando bem, talvez você queira habilitar o fluxo de trabalho para que ele possa ser executado automaticamente em uma agenda definida pelo locatário. Execute a solicitação a seguir.
A solicitação retorna uma 204 No Content resposta. Quando um fluxo de trabalho é agendado, o mecanismo de fluxos de trabalho do ciclo de vida verifica a cada três horas objetos de usuário que correspondem à condição de execução associada e executa as tarefas configuradas para esses usuários. Você pode personalizar essa recorrência entre uma hora e 24 horas.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models.IdentityGovernance;
var requestBody = new Workflow
{
IsEnabled = true,
IsSchedulingEnabled = true,
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.IdentityGovernance.LifecycleWorkflows.Workflows["{workflow-id}"].PatchAsync(requestBody);
// THE CLI IS IN PREVIEW. NON-PRODUCTION USE ONLY
mgc identity-governance lifecycle-workflows workflows patch --workflow-id {workflow-id} --body '{\
"isEnabled": true,\
"isSchedulingEnabled": true\
}\
'
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.models.identitygovernance.Workflow workflow = new com.microsoft.graph.models.identitygovernance.Workflow();
workflow.setIsEnabled(true);
workflow.setIsSchedulingEnabled(true);
com.microsoft.graph.models.identitygovernance.Workflow result = graphClient.identityGovernance().lifecycleWorkflows().workflows().byWorkflowId("{workflow-id}").patch(workflow);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\Workflow;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Workflow();
$requestBody->setIsEnabled(true);
$requestBody->setIsSchedulingEnabled(true);
$result = $graphServiceClient->identityGovernance()->lifecycleWorkflows()->workflows()->byWorkflowId('workflow-id')->patch($requestBody)->wait();
Brevemente: Ao longo de 2024, vamos descontinuar progressivamente o GitHub Issues como mecanismo de feedback para conteúdos e substituí-lo por um novo sistema de feedback. Para obter mais informações, veja: https://aka.ms/ContentUserFeedback.