<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://blog.awkward.industries/feed.xml" rel="self" type="application/atom+xml" /><link href="https://blog.awkward.industries/" rel="alternate" type="text/html" /><updated>2025-05-04T17:50:35+00:00</updated><id>https://blog.awkward.industries/feed.xml</id><title type="html">The Awkward Industries Blog</title><subtitle>Musings of a software developer just trying to figure things out.</subtitle><author><name>Megan K. Meyer</name><email>mkm@awkward.industries</email></author><entry><title type="html">Empower Your AI Agents: Harnessing Azure Functions with Azure AI Foundry</title><link href="https://blog.awkward.industries/2025/05/04/azure-agents-and-functions.html" rel="alternate" type="text/html" title="Empower Your AI Agents: Harnessing Azure Functions with Azure AI Foundry" /><published>2025-05-04T00:00:00+00:00</published><updated>2025-05-04T00:00:00+00:00</updated><id>https://blog.awkward.industries/2025/05/04/azure-agents-and-functions</id><content type="html" xml:base="https://blog.awkward.industries/2025/05/04/azure-agents-and-functions.html"><![CDATA[<div id="entry-table-of-contents" class="toc-wrapper">
  <h2 id="toc-toggle" class="no_toc">
  Table of Contents <i class="toc-toggle-icon fas fa-chevron-down"></i>
</h2>
<ol id="markdown-toc">
  <li><a href="#setting-things-up-in-your-azure-subscription" id="markdown-toc-setting-things-up-in-your-azure-subscription">Setting things up in your Azure Subscription</a>    <ol>
      <li><a href="#security-points" id="markdown-toc-security-points">Security points</a></li>
      <li><a href="#setup-your-tools-environment-variables-and-resource-group" id="markdown-toc-setup-your-tools-environment-variables-and-resource-group">Setup your tools, environment variables, and Resource Group</a></li>
      <li><a href="#ai-hub-and-project" id="markdown-toc-ai-hub-and-project">AI Hub and Project</a>        <ol>
          <li><a href="#create-the-required-dependencies" id="markdown-toc-create-the-required-dependencies">Create the required dependencies</a></li>
          <li><a href="#create-the-hub-and-connections" id="markdown-toc-create-the-hub-and-connections">Create the Hub and connections</a></li>
          <li><a href="#create-the-project" id="markdown-toc-create-the-project">Create the Project</a></li>
        </ol>
      </li>
      <li><a href="#azure-function" id="markdown-toc-azure-function">Azure Function</a></li>
      <li><a href="#azure-ai-standard-agent" id="markdown-toc-azure-ai-standard-agent">Azure AI Standard Agent</a></li>
    </ol>
  </li>
  <li><a href="#hows-this-working" id="markdown-toc-hows-this-working">How’s this working?</a>    <ol>
      <li><a href="#understanding-the-flow" id="markdown-toc-understanding-the-flow">Understanding the flow</a></li>
      <li><a href="#tying-together-the-ai-agent-and-azure-function" id="markdown-toc-tying-together-the-ai-agent-and-azure-function">Tying together the AI Agent and Azure Function</a></li>
    </ol>
  </li>
  <li><a href="#lets-see-it-in-action" id="markdown-toc-lets-see-it-in-action">Let’s see it in action</a></li>
  <li><a href="#closing-thoughts-and-azd-shortcut" id="markdown-toc-closing-thoughts-and-azd-shortcut">Closing thoughts (and <code class="language-plaintext highlighter-rouge">azd</code> shortcut)</a></li>
</ol>

</div>

<p>Are you looking for a fast and easy way to provide custom business logic to your Agents without having to couple the function call to the Agent code? The Azure AI Agent Service is here to help with its Azure Functions integration!</p>

<blockquote>
  <p>The Azure AI Agent Service integrates with Azure Functions, enabling you to create intelligent, event-driven applications with minimal overhead. This combination allows AI-driven workflows to leverage the scalability and flexibility of serverless computing, making it easier to build and deploy solutions that respond to real-time events or complex workflows.</p>

  <footer>Microsoft <a href="https://learn.microsoft.com/en-us/azure/ai-services/agents/how-to/tools/azure-functions?tabs=python&amp;pivots=overview">documentation</a> for AI Agent Service</footer>
</blockquote>

<p>Let’s assume you work for an organization that has lots of active projects, and you want to create an AI Agent who can answer questions about and act upon those projects. You probably have a project management system, but it’s custom and would require custom code to access project information. You could build an entirely new application just to support this, or you could create a few Azure Functions to expose access to your project management system and provide those to an AI Agent so that it can decide what information it needs when it needs it to fulfill its tasks.</p>

<p>In this walkthrough, we’ll show how easy it can be to setup Azure AI Foundry with AI Agent Service to leverage Azure Functions.</p>

<h2 id="setting-things-up-in-your-azure-subscription">Setting things up in your Azure Subscription</h2>

<p>First, you’ll need access to an Azure Subscription. We’ll use the <a href="https://learn.microsoft.com/en-us/cli/azure/get-started-with-azure-cli"><strong>Azure CLI</strong></a> to help us quickly provision resources needed. We’ll use the <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=linux%2Cisolated-process%2Cnode-v4%2Cpython-v2%2Chttp-trigger%2Ccontainer-apps&amp;pivots=programming-language-python#install-the-azure-functions-core-tools"><strong>Azure Functions Core Tools</strong></a> to deploy code to our provisioned Function App.</p>

<p>Let’s make sure we have all the pieces in place. At a high-level, we’ll need:</p>
<ul>
  <li>An <em>Azure AI Hub and Project</em> to manage the Agents</li>
  <li>An <em>Azure Function App</em> with our business logic implementation</li>
  <li>An <em>Azure Storage Account</em> for our Queues to manage triggering function code and responding to the agent</li>
  <li><em>Azure RBAC Role Assignments</em> for our resources to make sure the identities of our components have the right permissions</li>
</ul>

<h3 id="security-points">Security points</h3>

<p>Rather than passing around keys, we’ll use identities and role-based access control (RBAC) to ensure resources have the correct permissions to do what they need to do.</p>

<table>
  <thead>
    <tr>
      <th>Identity</th>
      <th>Target Resource</th>
      <th>Role Required</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Azure AI Project</td>
      <td>Storage Account</td>
      <td>Storage Queue Data Contributor</td>
    </tr>
    <tr>
      <td> </td>
      <td>AI Search Service</td>
      <td>Search Index Data Contributor</td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td>Search Service Contributor</td>
    </tr>
    <tr>
      <td> </td>
      <td>AI Services</td>
      <td>Cognitive Services Contributor</td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td>Cognitive Services OpenAI User</td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td>Cognitive Services User</td>
    </tr>
    <tr>
      <td>Azure Function App</td>
      <td>Storage Account</td>
      <td>Storage Blob Data Owner</td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td>Storage Queue Data Contributor</td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td>Storage Table Data Contributor</td>
    </tr>
  </tbody>
</table>

<p class="notice--info">You will need to be able to create these role assignments, so you will need to be an <strong>Owner</strong> of either the <em>subscription</em> or the <em>resource group</em> in which the resources are being created. Alternatively, you can request the role assignments be created by someone with permissions to create role assignments in your organization.</p>

<p>Next, we’ll setup a few things and make sure we have a spot to drop all of our resources.</p>

<h3 id="setup-your-tools-environment-variables-and-resource-group">Setup your tools, environment variables, and Resource Group</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="rouge-code"><pre><span class="c"># Install the `ml` extension for Azure CLI</span>

az extension add <span class="nt">-n</span> ml
az extension update <span class="nt">-n</span> ml

<span class="c"># Setup some variables</span>

<span class="nv">SUBSCRIPTION_ID</span><span class="o">=</span><span class="si">$(</span>az account show <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span>
<span class="nv">RESOURCE_GROUP</span><span class="o">=</span><span class="s2">"rg-agents-and-functions-demo"</span>
<span class="nv">LOCATION</span><span class="o">=</span><span class="s2">"eastus2"</span>
<span class="nv">SUFFIX</span><span class="o">=</span><span class="si">$(</span><span class="nb">cksum</span> <span class="o">&lt;&lt;&lt;</span> <span class="s2">"</span><span class="k">${</span><span class="nv">RESOURCE_GROUP</span><span class="k">}${</span><span class="nv">SUBSCRIPTION_ID</span><span class="k">}</span><span class="s2">"</span> | <span class="nb">cut</span> <span class="nt">-f</span> 1 <span class="nt">-d</span> <span class="s1">' '</span><span class="si">)</span>

<span class="nv">KEY_VAULT_NAME</span><span class="o">=</span><span class="s2">"kv-aaf-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">STORAGE_ACCOUNT_NAME</span><span class="o">=</span><span class="s2">"staaf</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">AI_SERVICES_NAME</span><span class="o">=</span><span class="s2">"ai-aaf-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">AI_SEARCH_NAME</span><span class="o">=</span><span class="s2">"search-aaf-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>

<span class="nv">HUB_NAME</span><span class="o">=</span><span class="s2">"aaf-demo-hub"</span>
<span class="nv">PROJECT_NAME</span><span class="o">=</span><span class="s2">"aaf-demo-project"</span>
<span class="nv">AI_SERVICES_CONNECTION_NAME</span><span class="o">=</span><span class="s2">"ai-services-connection"</span>
<span class="nv">AI_SEARCH_CONNECTION_NAME</span><span class="o">=</span><span class="s2">"ai-search-connection"</span>
<span class="nv">STORAGE_CONNECTION_NAME</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">PROJECT_NAME</span><span class="k">}</span><span class="s2">/workspaceblobstore"</span>
<span class="nv">CAPABILITY_HOST_NAME</span><span class="o">=</span><span class="s2">"ch-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>

<span class="nv">FUNCTION_APP_ID_NAME</span><span class="o">=</span><span class="s2">"id-func-aaf-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">FUNCTION_APP_NAME</span><span class="o">=</span><span class="s2">"func-aaf-</span><span class="k">${</span><span class="nv">SUFFIX</span><span class="k">}</span><span class="s2">"</span>

<span class="nv">INPUT_QUEUE_NAME</span><span class="o">=</span><span class="s2">"project-status-request"</span>
<span class="nv">OUTPUT_QUEUE_NAME</span><span class="o">=</span><span class="s2">"project-status-response"</span>

<span class="c">#</span>
<span class="c"># Create the resource group</span>
<span class="c">#</span>
<span class="c"># This will hold all of the resources used for this walkthrough. When</span>
<span class="c"># you want to clean up, just delete this and everything within it </span>
<span class="c"># will also be deleted.</span>

az group create <span class="nt">-n</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-l</span> <span class="nv">$LOCATION</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="ai-hub-and-project">AI Hub and Project</h3>

<p class="notice--info">You can use several methods to create an Azure AI Project. To see how to create projects using the Azure AI Foundry portal or Python SDK, please review <a href="https://learn.microsoft.com/en-us/azure/ai-foundry/how-to/create-projects?tabs=ai-studio">the docs</a>.</p>

<p>While our goal is to create the Hub/Project, they depend on several resources to be able to work as expected. Generally, an AI Hub requires an <em>Azure Storage Account</em> and an <em>Azure Key Vault</em>. You can also add an <em>Application Insights</em> reference if you’d like to enable some built-in logging and monitoring capabilities. If you create a Hub without specifying these, they will be created for you.</p>

<p>Because we’re building out all of these pieces in support of a demo, we’ll use a single Storage Account for all of our dependent resources – th AI Hub, Azure Function App, and integration will all share it.</p>

<p>The AI Agent service &amp; Function integration requires use of the <em>Standard Agent</em> type. To create a Standard Agent, the AI Project will need access to a Storage Account, Azure AI Services with OpenAI support (type <em>AIServices</em>), and an Azure AI Search service. You may also optionally bring an Azure Cosmos DB instance to store thread data. These connections need to be created at the AI Hub or Project level, and you then add a Capability Host to both the AI Hub and Project. The Capability Host at the Project requires references to the connection name for the three required components. Without a Capability Host, you cannot use the tools for the AI Agent service. While the Functions integration tool may not need all of these components, the Standard Agent type requires they be in place since it supports other tools that may need them.</p>

<h4 id="create-the-required-dependencies">Create the required dependencies</h4>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
</pre></td><td class="rouge-code"><pre><span class="c">#</span>
<span class="c"># Create the Key Vault</span>
<span class="c">#</span>

az keyvault create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--location</span> <span class="nv">$LOCATION</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$KEY_VAULT_NAME</span>

<span class="c">#</span>
<span class="c"># Create the Storage Account</span>
<span class="c">#</span>

az storage account create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--location</span> <span class="nv">$LOCATION</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="se">\</span>
<span class="nt">--sku</span> Standard_LRS

<span class="c">#</span>
<span class="c"># Create the AI Services resource</span>
<span class="c">#</span>
<span class="c"># This will be used by the Hub/Project to handle interactions with </span>
<span class="c"># OpenAI models and inferencing endpoints. The `custom-domain` </span>
<span class="c"># argument creates a resource-specific endpoint as opposed to a</span>
<span class="c"># general location-specific endpoint.</span>

az cognitiveservices account create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--location</span> <span class="nv">$LOCATION</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$AI_SERVICES_NAME</span> <span class="se">\</span>
<span class="nt">--kind</span> AIServices <span class="se">\</span>
<span class="nt">--custom-domain</span> <span class="nv">$AI_SERVICES_NAME</span> <span class="se">\</span>
<span class="nt">--sku</span> S0 <span class="se">\</span>
<span class="nt">--yes</span>

<span class="c"># Deploy an OpenAI model to your AI Services account</span>

az cognitiveservices account deployment create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$AI_SERVICES_NAME</span> <span class="se">\</span>
<span class="nt">--deployment-name</span> gpt-4o-mini <span class="se">\</span>
<span class="nt">--model-name</span> gpt-4o-mini <span class="se">\</span>
<span class="nt">--model-version</span> 2024-07-18 <span class="se">\</span>
<span class="nt">--model-format</span> OpenAI <span class="se">\</span>
<span class="nt">--sku-name</span> GlobalStandard <span class="se">\</span>
<span class="nt">--sku-capacity</span> 50

<span class="c">#</span>
<span class="c"># Create the AI Search resource</span>
<span class="c">#</span>
<span class="c"># While the Azure Functions tool doesn't require AI Search, the </span>
<span class="c"># capabilities host requires a vector store connection.</span>

az search service create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$AI_SEARCH_NAME</span> <span class="se">\</span>
<span class="nt">--sku</span> Standard
</pre></td></tr></tbody></table></code></pre></div></div>

<p class="notice--warning">Note: some of these commands can take a long time to complete. Comments have been added when longer execution times are expected, but some may have been missed. When possible, we store the output in a local variable to reduce additional calls back to the service.</p>

<h4 id="create-the-hub-and-connections">Create the Hub and connections</h4>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
</pre></td><td class="rouge-code"><pre><span class="c">#</span>
<span class="c"># Create the AI Hub</span>
<span class="c">#</span>
<span class="c"># Save the response because subsequent `az ml workspace show` calls </span>
<span class="c"># can be very slow.</span>
<span class="c"># Note: this may take up to 10 minutes.</span>

<span class="nv">STORAGE_ACCOUNT_RESOURCE_ID</span><span class="o">=</span><span class="si">$(</span>az storage account show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span>

<span class="nv">HUB_DETAILS</span><span class="o">=</span><span class="si">$(</span>az ml workspace create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$HUB_NAME</span> <span class="se">\</span>
<span class="nt">--kind</span> hub <span class="se">\</span>
<span class="nt">--key-vault</span> <span class="si">$(</span>az keyvault show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$KEY_VAULT_NAME</span> <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span> <span class="se">\</span>
<span class="nt">--storage-account</span> <span class="nv">$STORAGE_ACCOUNT_RESOURCE_ID</span><span class="si">)</span>

<span class="c">#</span>
<span class="c"># Create Connections for AI Hub</span>
<span class="c">#</span>
<span class="c"># The specification for the service connections does not explicitly </span>
<span class="c"># require all of the metadata to be set; however, this walkthrough </span>
<span class="c"># attempts to create a target state of the resources as close as </span>
<span class="c"># possible to the Standard Agent setup template which explicitly sets</span>
<span class="c"># the ApiType and location values in addition to the required settings.</span>
<span class="c"># While the metadata property is not documented in the Azure ML CLI </span>
<span class="c"># v2 docs for the YAML file inputs, it is supported.</span>
<span class="c"># Note: if the connections are not setup correctly, it will not</span>
<span class="c"># necessarily err out, but attempts to create the AI Project</span>
<span class="c"># Capability Host or Agent later will fail.</span>

<span class="c"># Connect AI Services to your Hub</span>

<span class="nv">AI_SERVICES_ENDPOINT</span><span class="o">=</span><span class="si">$(</span>az cognitiveservices account show <span class="nt">-n</span> <span class="nv">$AI_SERVICES_NAME</span> <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">--query</span> properties.endpoint <span class="nt">-o</span> tsv<span class="si">)</span>
<span class="nv">AI_SERVICES_RESOURCE_ID</span><span class="o">=</span><span class="si">$(</span>az cognitiveservices account show <span class="nt">-n</span> <span class="nv">$AI_SERVICES_NAME</span> <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span>


<span class="nb">cat</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh"> &gt; connection-spec-ai-services.yaml
name: </span><span class="k">${</span><span class="nv">AI_SERVICES_CONNECTION_NAME</span><span class="k">}</span><span class="sh">
type: azure_ai_services
endpoint: </span><span class="k">${</span><span class="nv">AI_SERVICES_ENDPOINT</span><span class="k">}</span><span class="sh">
ai_services_resource_id: </span><span class="k">${</span><span class="nv">AI_SERVICES_RESOURCE_ID</span><span class="k">}</span><span class="sh">
metadata:
  ApiType: Azure
  location: </span><span class="nv">$LOCATION</span><span class="sh">
</span><span class="no">EOF

</span>az ml connection create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--workspace-name</span> <span class="nv">$HUB_NAME</span> <span class="se">\</span>
<span class="nt">--file</span> connection-spec-ai-services.yaml

<span class="c"># Connect AI Search to your Hub</span>

<span class="nv">AI_SEARCH_RESOURCE_ID</span><span class="o">=</span><span class="si">$(</span>az search service show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$AI_SEARCH_NAME</span> <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span>

<span class="nb">cat</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh"> &gt; connection-spec-ai-search.yaml
name: </span><span class="k">${</span><span class="nv">AI_SEARCH_CONNECTION_NAME</span><span class="k">}</span><span class="sh">
type: azure_ai_search
endpoint: https://</span><span class="k">${</span><span class="nv">AI_SEARCH_NAME</span><span class="k">}</span><span class="sh">.search.windows.net/
metadata:
  ApiType: Azure
  ResourceId: </span><span class="k">${</span><span class="nv">AI_SEARCH_RESOURCE_ID</span><span class="k">}</span><span class="sh">
  location: </span><span class="k">${</span><span class="nv">LOCATION</span><span class="k">}</span><span class="sh">
</span><span class="no">EOF

</span>az ml connection create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--workspace-name</span> <span class="nv">$HUB_NAME</span> <span class="se">\</span>
<span class="nt">--file</span> connection-spec-ai-search.yaml

<span class="c">#</span>
<span class="c"># Add Capability Host to the Hub</span>
<span class="c">#</span>

az ml capability-host create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--workspace-name</span> <span class="nv">$HUB_NAME</span> <span class="se">\</span>
<span class="nt">--name</span> hub-<span class="nv">$CAPABILITY_HOST_NAME</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h4 id="create-the-project">Create the Project</h4>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
</pre></td><td class="rouge-code"><pre><span class="c">#</span>
<span class="c"># Create the AI Project</span>
<span class="c">#</span>
<span class="c"># Save the response because subsequent `az ml </span>
<span class="c"># workspace show` calls can be very slow.</span>
<span class="c"># Note: this may take up to 10 minutes.</span>

<span class="nv">HUB_RESOURCE_ID</span><span class="o">=</span><span class="si">$(</span><span class="nb">echo</span> <span class="nv">$HUB_DETAILS</span> | jq <span class="nt">-r</span> <span class="s1">'.id'</span><span class="si">)</span>

<span class="nv">PROJECT_DETAILS</span><span class="o">=</span><span class="si">$(</span>az ml workspace create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--hub-id</span> <span class="nv">$HUB_RESOURCE_ID</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$PROJECT_NAME</span> <span class="se">\</span>
<span class="nt">--kind</span> project<span class="si">)</span>

<span class="c">#</span>
<span class="c"># Add the Capability Host to the Project</span>
<span class="c">#</span>
<span class="c"># A couple of things happening here...</span>
<span class="c"># 1) Using a file because a single entry throws a list validation</span>
<span class="c">#    error when passing these arguments directly.</span>
<span class="c"># 2) When the AI Services Connection is added to the Hub, it creates </span>
<span class="c">#    two -- one for general AI Services, and a second specific to </span>
<span class="c">#    Azure OpenAI with the name '${AI_SERVICES_CONNECTION_NAME}_aoai'.</span>
<span class="c">#    The Project capability host requires the Azure OpenAI flavor of</span>
<span class="c">#    the connection, so we'll set it here to have the conventional </span>
<span class="c">#    postfix. (This secondary "aoai" AI Services connection is also</span>
<span class="c">#    visible in the portal or with `az ml connection list`. If it</span>
<span class="c">#    isn't available, there must have been an issue adding the AI</span>
<span class="c">#    services connection to the Hub.)</span>

<span class="nb">cat</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh"> &gt; capability-host-project-spec.yaml
name: project-</span><span class="nv">$CAPABILITY_HOST_NAME</span><span class="sh">
ai_services_connections: 
- </span><span class="k">${</span><span class="nv">AI_SERVICES_CONNECTION_NAME</span><span class="k">}</span><span class="sh">_aoai
vector_store_connections: 
- </span><span class="nv">$AI_SEARCH_CONNECTION_NAME</span><span class="sh">
storage_connections: 
- </span><span class="nv">$STORAGE_CONNECTION_NAME</span><span class="sh">
</span><span class="no">EOF

</span>az ml capability-host create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--workspace-name</span> <span class="nv">$PROJECT_NAME</span> <span class="se">\</span>
<span class="nt">--file</span> capability-host-project-spec.yaml

<span class="c">#</span>
<span class="c"># Assign roles to AI Project identity</span>
<span class="c">#</span>

<span class="nv">AI_PROJECT_PRINCIPAL_ID</span><span class="o">=</span><span class="si">$(</span><span class="nb">echo</span> <span class="nv">$PROJECT_DETAILS</span> | jq <span class="nt">-r</span> <span class="s1">'.identity.principal_id'</span><span class="si">)</span>

<span class="c"># Roles for AI Search</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Search Index Data Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$AI_SEARCH_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Search Service Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$AI_SEARCH_RESOURCE_ID</span>

<span class="c"># Roles for AI Services</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Cognitive Services Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$AI_SERVICES_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Cognitive Services OpenAI User"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$AI_SERVICES_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Cognitive Services User"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$AI_SERVICES_RESOURCE_ID</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>At this point, we’ve got a lot of resources to get everything up and running! Your resource group should include:</p>
<ul>
  <li>Dependencies:
    <ul>
      <li>Storage Account
        <ul>
          <li>auto-created Event Grid System Topic</li>
        </ul>
      </li>
      <li>Key Vault</li>
      <li>AI Services
        <ul>
          <li>gpt-4o-mini model deployment</li>
        </ul>
      </li>
      <li>AI Search</li>
    </ul>
  </li>
  <li>AI Hub</li>
  <li>AI Project</li>
</ul>

<p>You can check by running <code class="language-plaintext highlighter-rouge">az resource list -g $RESOURCE_GROUP -o table</code> or looking in the Azure Portal.</p>

<p>All that’s left is the Function App, code, and some more role assigments.</p>

<h3 id="azure-function">Azure Function</h3>

<p class="notice--info">For ease of deployment, a test function implementation has been provided in the Awkward Industries GitHub Repository <a href="https://github.com/awkwardindustries/agents-and-functions-blog">awkwardindustries/agents-and-functions-blog</a> under the Function app implementation (<a href="https://github.com/awkwardindustries/agents-and-functions-blog/tree/main/src/functions">src/functions</a>). If you have your own, feel free to use it!</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
</pre></td><td class="rouge-code"><pre><span class="c">#</span>
<span class="c"># Create the Storage Queues</span>
<span class="c">#</span>
<span class="c"># Using our shared Storage Account, we'll create an input and output </span>
<span class="c"># queue. The Function is triggered when the Agent drops a message on </span>
<span class="c"># the input queue, and the response is dropped by the Function onto </span>
<span class="c"># the output queue for the Agent to pick up.</span>

az storage queue create <span class="nt">--account-name</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="nt">-n</span> <span class="nv">$INPUT_QUEUE_NAME</span>
az storage queue create <span class="nt">--account-name</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="nt">-n</span> <span class="nv">$OUTPUT_QUEUE_NAME</span>

<span class="nv">QUEUE_SERVICE_ENDPOINT</span><span class="o">=</span><span class="si">$(</span>az storage account show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="nt">--query</span> primaryEndpoints.queue <span class="nt">-o</span> tsv<span class="si">)</span>

<span class="c">#</span>
<span class="c"># Create the Function App</span>
<span class="c">#</span>
<span class="c"># We'll specify the identity for the Function App. We'll also apply </span>
<span class="c"># known app settings required by the application after we create the </span>
<span class="c"># Function App.</span>

<span class="c"># Create a managed identity for the Function App</span>

az identity create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$FUNCTION_APP_ID_NAME</span>

<span class="c"># Create the Function App</span>

az functionapp create <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--flexconsumption-location</span> <span class="nv">$LOCATION</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$FUNCTION_APP_NAME</span> <span class="se">\</span>
<span class="nt">--runtime</span> python <span class="se">\</span>
<span class="nt">--runtime-version</span> 3.11 <span class="se">\</span>
<span class="nt">--storage-account</span> <span class="nv">$STORAGE_ACCOUNT_NAME</span> <span class="se">\</span>
<span class="nt">--assign-identity</span> <span class="s2">"</span><span class="si">$(</span>az identity show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$FUNCTION_APP_ID_NAME</span> <span class="nt">--query</span> <span class="nb">id</span> <span class="nt">-o</span> tsv<span class="si">)</span><span class="s2">"</span>

<span class="c"># Apply required application settings</span>

az functionapp config appsettings <span class="nb">set</span> <span class="se">\</span>
<span class="nt">--resource-group</span> <span class="nv">$RESOURCE_GROUP</span> <span class="se">\</span>
<span class="nt">--name</span> <span class="nv">$FUNCTION_APP_NAME</span> <span class="se">\</span>
<span class="nt">--settings</span> <span class="se">\</span>
<span class="nv">AzureWebJobsStorage__clientId</span><span class="o">=</span><span class="si">$(</span>az identity show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$FUNCTION_APP_ID_NAME</span> <span class="nt">--query</span> clientId <span class="nt">-o</span> tsv<span class="si">)</span> <span class="se">\</span>
<span class="nv">STORAGE_QUEUES_CONNECTION__clientId</span><span class="o">=</span><span class="si">$(</span>az identity show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$FUNCTION_APP_ID_NAME</span> <span class="nt">--query</span> clientId <span class="nt">-o</span> tsv<span class="si">)</span> <span class="se">\</span>
<span class="nv">STORAGE_QUEUES_CONNECTION__credential</span><span class="o">=</span>managedidentity <span class="se">\</span>
<span class="nv">STORAGE_QUEUES_CONNECTION__queueServiceUri</span><span class="o">=</span><span class="nv">$QUEUE_SERVICE_ENDPOINT</span> <span class="se">\</span>
<span class="nv">AZURE_CLIENT_ID</span><span class="o">=</span><span class="si">$(</span>az identity show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$FUNCTION_APP_ID_NAME</span> <span class="nt">--query</span> clientId <span class="nt">-o</span> tsv<span class="si">)</span> <span class="se">\</span>
<span class="nv">AZURE_AI_PROJECT_CONNECTION_STRING</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">LOCATION</span><span class="k">}</span><span class="s2">.api.azureml.us;</span><span class="k">${</span><span class="nv">SUBSCRIPTION_ID</span><span class="k">}</span><span class="s2">;</span><span class="k">${</span><span class="nv">RESOURCE_GROUP</span><span class="k">}</span><span class="s2">;</span><span class="k">${</span><span class="nv">PROJECT_NAME</span><span class="k">}</span><span class="s2">"</span>

<span class="c">#</span>
<span class="c"># Deploy the Function application to the Function App</span>
<span class="c">#</span>
<span class="c"># This step is easiest with the Azure Functions Core Tools. We'll </span>
<span class="c"># clone the code and directly push it to Azure using the tool.</span>

git clone https://github.com/awkwardindustries/agents-and-functions-blog.git
<span class="nb">cd </span>agents-and-functions-blog/src/functions

func azure functionapp publish <span class="nv">$FUNCTION_APP_NAME</span> <span class="nt">--python</span>

<span class="c">#</span>
<span class="c"># Assign roles to Function App identity and AI Project identity for </span>
<span class="c"># Storage Account access</span>
<span class="c">#</span>

<span class="nv">FUNCTION_APP_PRINCIPAL_ID</span><span class="o">=</span><span class="si">$(</span>az identity show <span class="nt">-g</span> <span class="nv">$RESOURCE_GROUP</span> <span class="nt">-n</span> <span class="nv">$FUNCTION_APP_ID_NAME</span> <span class="nt">--query</span> principalId <span class="nt">-o</span> tsv<span class="si">)</span>

<span class="c"># Roles for the Storage Account</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Storage Queue Data Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$AI_PROJECT_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$STORAGE_ACCOUNT_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Storage Blob Data Owner"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$FUNCTION_APP_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$STORAGE_ACCOUNT_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Storage Queue Data Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$FUNCTION_APP_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$STORAGE_ACCOUNT_RESOURCE_ID</span>

az role assignment create <span class="se">\</span>
<span class="nt">--role</span> <span class="s2">"Storage Table Data Contributor"</span> <span class="se">\</span>
<span class="nt">--assignee-object-id</span> <span class="nv">$FUNCTION_APP_PRINCIPAL_ID</span> <span class="se">\</span>
<span class="nt">--assignee-principal-type</span> ServicePrincipal <span class="se">\</span>
<span class="nt">--scope</span> <span class="nv">$STORAGE_ACCOUNT_RESOURCE_ID</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="azure-ai-standard-agent">Azure AI Standard Agent</h3>

<p>Azure Functions as a knowledge tool requires the [Standard Agent] setup. Unfortunately this is currently only fully supported in either the <em>REST SDK</em> or <em>Python SDK</em>. For ease of scripting, we’ll use the Azure CLI’s <code class="language-plaintext highlighter-rouge">az rest</code> commands to proxy requests for the <em>REST SDK</em> to ensure setup of the Standard Agent.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="rouge-code"><pre><span class="c">#</span>
<span class="c"># Setup required variables</span>
<span class="c">#</span>
<span class="c"># This is hardcoded convention from documentation to use the discovery_url for</span>
<span class="c"># the hostname, and then build out the full URL to get the URL for the AI Agent.</span>
<span class="nv">DISCOVERY_URL</span><span class="o">=</span><span class="si">$(</span><span class="nb">echo</span> <span class="nv">$PROJECT_DETAILS</span> | jq <span class="nt">-r</span> <span class="s1">'.discovery_url'</span><span class="si">)</span>
<span class="nv">AI_AGENT_ENDPOINT</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DISCOVERY_URL</span><span class="p">%/*</span><span class="k">}</span><span class="s2">/agents/v1.0/subscriptions/</span><span class="nv">$SUBSCRIPTION_ID</span><span class="s2">/resourceGroups/</span><span class="nv">$RESOURCE_GROUP</span><span class="s2">/providers/Microsoft.MachineLearningServices/workspaces/</span><span class="nv">$PROJECT_NAME</span><span class="s2">"</span>
<span class="nv">API_VERSION</span><span class="o">=</span>2024-12-01-preview

<span class="c">#</span>
<span class="c"># Create an Agent and save the ID</span>
<span class="c">#</span>
<span class="c"># Note: Although the sample includes two functions, we're only</span>
<span class="c"># integrating with one for this walkthrough.</span>

<span class="nb">cat</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh"> &gt; new-agent-body.json
{
  "name": "agents-and-functions-cli-agent",
  "model": "gpt-4o-mini",
  "instructions": "You are a helpful assistant that provides answers about company projects.",
  "tools": [
    {
      "type": "azure_function",
      "azure_function": {
        "function": {
          "name": "GetProjectStatus",
          "description": "Get the current project status for provided project.",
          "parameters": {
            "type": "object",
            "properties": {
              "Project": {"type": "string", "description": "The project whose status is requested."}
            },
            "required": ["Project"]
          }
        },
        "input_binding": {
          "type": "storage_queue",
          "storage_queue": {
            "queue_service_endpoint": "</span><span class="nv">$QUEUE_SERVICE_ENDPOINT</span><span class="sh">",
            "queue_name": "</span><span class="nv">$INPUT_QUEUE_NAME</span><span class="sh">"
          }
        },
        "output_binding": {
          "type": "storage_queue",
          "storage_queue": {
            "queue_service_endpoint": "</span><span class="nv">$QUEUE_SERVICE_ENDPOINT</span><span class="sh">",
            "queue_name": "</span><span class="nv">$OUTPUT_QUEUE_NAME</span><span class="sh">"
          }
        }
      }
    }
  ]
}
</span><span class="no">EOF

</span><span class="nv">AGENT_ID</span><span class="o">=</span><span class="si">$(</span>az rest <span class="nt">--method</span> post <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/assistants?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--body</span> @new-agent-body.json <span class="se">\</span>
<span class="nt">--query</span> <span class="nb">id</span> <span class="nt">--output</span> tsv<span class="si">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h2 id="hows-this-working">How’s this working?</h2>

<p>The request/response pattern between the Agent and Function is managed by Storage Account Queues. When an Agent determines it needs to invoke a Function to help do its job (based on the specification provided at tool definition), it places a message on the specified inbound queue to trigger the Function. When the function is finished, it drops a message on the specified outbound queue to notify the Agent its job is complete.</p>

<p>Agent threads continuously poll the outbound queue for responses. The <em>CorrelationId</em> is important because it ensures the correct Agent thread is processing the response intended for it and enables an asynchronous request-response pattern. If this isn’t included, the Agent thread will think it never received a response because it’s checking messages for that ID. If an Agent thread dequeues a messsage with an unexpected <em>CorrelationId</em>, it will release the lease for the message assuming a different Agent thread with matching <em>CorrelationId</em> will dequeue it.</p>

<h3 id="understanding-the-flow">Understanding the flow</h3>

<p>For the typical path, the experience should flow as follows:</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant Agent
    participant Inbound Queue
    participant Outbound Queue
    participant Function
    
    Function--&gt;&gt;Inbound Queue: Start polling for work
    Agent-&gt;&gt;Inbound Queue: Enqueue message with CorrelationId = `abc`
    Agent--&gt;&gt;Outbound Queue: Start polling for `abc` response
    Function-&gt;&gt;Inbound Queue: Work triggered for `abc`
    Function-&gt;&gt;Outbound Queue: Work finished for `abc`
    Agent-&gt;&gt;Outbound Queue: Checking for `abc`...matched. All done!
</code></pre>

<div class="notice--warning">
    
<h3 id="lets-take-a-minute">Let’s take a minute…</h3>
<p>and talk about how queue receive modes and delivery counts work and why that <em>might</em> be a problem in some cases.</p>

<p>It may be possible that your response doesn’t make it because too many other Agent threads have checked it before it was picked up by the correct Agent thread. Storage Account Queues use a Peek &amp; Lease receive mode with a default <em>DequeueCount</em> of five. This means that the first message in the queue will be delivered to a recipient with a lease, but it’s up to the recipient to tell the queue that it’s handled or needs to remain in the queue. If it remains, it may be delivered under a lease to a recipient <em>at most</em> five times.</p>

<p>Why would you possibly return it to the queue? Well, lots of reasons. You might have hit an unexpected error and don’t want to lose that message. In this case, an Agent thread might look at it to see if it’s for them using the <em>CorrelationId</em> and put it back so that it’s available for the other Agent thread(s).</p>

<p>If you scale to 10 concurrent Agent threads that all happen to need to make a Function call at the same time, it’s possible that multiple non-matching Agent threads might look at a response (dequeue it) and release it back to the queue if it’s not for them – each check incrementing the total dequeue count. Once five is hit, the Storage Account Queue will then move the message to a poison queue for review and the Agent thread would never receive the response.</p>

<p>A Service Bus Queue with <a href="https://learn.microsoft.com/en-us/azure/service-bus-messaging/message-sessions">message sessions</a> enabled would help address this issue. In effect, the <em>CorrelationId</em> could be used as the session ID ensuring that the responses are being dequeued only by the Agent thread with that <em>CorrelationId</em> instead of peeking and checking each message to see if the <em>CorrelationId</em> matches.</p>

<p>Unfortunately, integration with Service Bus Queues and message sessions is not currently supported, so until it is – if you’re noticing issues with lots of concurrent Agent threads, keep an eye on your Storage Queue to make sure you don’t get a poison outbound queue.</p>

</div>

<p>Looking at the slightly more complex path, multiple Agent threads flows might look a little different based on when the Function completes, which Agent polls first, etc. Here’s a more complex example:</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant Agent Thread 1
    participant Agent Thread 2
    participant Inbound Queue
    participant Outbound Queue
    participant Function

    Function--&gt;&gt;Inbound Queue: Start polling for work
    activate Agent Thread 1
    Agent Thread 1-&gt;&gt;Inbound Queue: Enqueue message with CorrelationId = `abc`
    Agent Thread 1--&gt;&gt;Outbound Queue: Start polling for `abc` response
    Function-&gt;&gt;Inbound Queue: Work triggered for `abc`
    activate Agent Thread 2
    Agent Thread 2-&gt;&gt;Inbound Queue: Enqueue message with CorrelationId = `xyz`
    Agent Thread 2--&gt;&gt;Outbound Queue: Start polling for `xyz` response
    Function-&gt;&gt;Inbound Queue: Work triggered for `xyz`
    Function-&gt;&gt;Outbound Queue: Work finished for `xyz`
    Agent Thread 1--xOutbound Queue: Checking for `abc`... no match.
    Agent Thread 2-&gt;&gt;Outbound Queue: Checking for `xyz`... matched. All done!
    deactivate Agent Thread 2
    Function-&gt;&gt;Outbound Queue: Work finished for `abc`
    Agent Thread 1-&gt;&gt;Outbound Queue: Checking for `abc`... matched. All done!
    deactivate Agent Thread 1
</code></pre>

<p>By decoupling the Agents from the Function invocation with a Storage Account Queue, the integration ensures the Function can scale out as needed to support the calls. It also supports long-running Functions that might be orchestrated with <a href="https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview?tabs=in-process%2Cnodejs-v3%2Cv1-model&amp;pivots=python">Durable Functions</a> to support stateful workflows for your business logic.</p>

<h3 id="tying-together-the-ai-agent-and-azure-function">Tying together the AI Agent and Azure Function</h3>

<p>You already know the communication is over Storage Queues, so this just highlights what’s tying them together. Assume they share a Storage Account Queue. They both also are setup to use an input queue <em>status-input-queue</em> and output queue <em>status-output-queue</em>.</p>

<p class="notice--warning">The following section is used to provide contextual comments to better understand the requirements on both the AI Agent service side and Azure Function side. <strong>DO NOT COPY</strong> or run this section.</p>

<p>For the AI Agent, it’s the tools specification at Agent creation that matters. (Using the Python SDK to annotate with contextual comments):</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
</pre></td><td class="rouge-code"><pre><span class="n">agent</span> <span class="o">=</span> <span class="n">project_client</span><span class="p">.</span><span class="n">agents</span><span class="p">.</span><span class="n">create_agent</span><span class="p">(</span>
  <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s">"x-ms-enable-preview"</span><span class="p">:</span> <span class="s">"true"</span><span class="p">},</span> <span class="c1"># Currently required as AI Agent service is in preview
</span>  <span class="n">model</span><span class="o">=</span><span class="s">"gpt-4o-mini"</span><span class="p">,</span> <span class="c1"># Any model deployment available to the AI Agent service
</span>  <span class="n">name</span><span class="o">=</span><span class="s">"function-created-agent-project-manager"</span><span class="p">,</span> <span class="c1"># This descriptive name is up to you
</span>  <span class="n">instructions</span><span class="o">=</span><span class="s">"You are a helpful project manager who reports on project status."</span><span class="p">,</span> <span class="c1"># The instructions for the Agent
</span>  <span class="n">tools</span><span class="o">=</span><span class="p">[</span> <span class="c1"># You can specify multiple tools, but for this example it is using a single Azure Function
</span>    <span class="p">{</span>
      <span class="s">"type"</span><span class="p">:</span> <span class="s">"azure_function"</span><span class="p">,</span>
      <span class="s">"azure_function"</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">"function"</span><span class="p">:</span> <span class="p">{</span>
          <span class="s">"name"</span><span class="p">:</span> <span class="s">"GetProjectStatus"</span><span class="p">,</span> <span class="c1"># The name of the Azure Function. Though triggered by 
</span>                                      <span class="c1"># the queue message, this descriptive name helps the Agent
</span>                                      <span class="c1"># determine when and how it should be used in conjunction
</span>                                      <span class="c1"># with the description below.
</span>          <span class="s">"description"</span><span class="p">:</span> <span class="s">"Retrieves the current status of the specified project."</span><span class="p">,</span>
          <span class="s">"parameters"</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">"type"</span><span class="p">:</span> <span class="s">"object"</span><span class="p">,</span>
            <span class="s">"properties"</span><span class="p">:</span> <span class="p">{</span> <span class="c1"># If your Function expects parameters, they should be defined here. The 
</span>                            <span class="c1"># Agent will match this specification, so the function can check the
</span>                            <span class="c1"># received message for the values of these properties.
</span>              <span class="s">"Project"</span><span class="p">:</span> <span class="p">{</span> <span class="s">"type"</span><span class="p">:</span> <span class="s">"string"</span><span class="p">,</span> <span class="s">"description"</span><span class="p">:</span> <span class="s">"The project name whose status is requested."</span> <span class="p">}</span>
            <span class="p">},</span>
            <span class="s">"required"</span><span class="p">:</span> <span class="p">[</span><span class="s">"Project"</span><span class="p">]</span> <span class="c1"># We require a project name, but not all functions require parameters.
</span>          <span class="p">}</span>
        <span class="p">},</span>
        <span class="s">"input_binding"</span><span class="p">:</span> <span class="p">{</span>
          <span class="s">"type"</span><span class="p">:</span> <span class="s">"storage_queue"</span><span class="p">,</span>
          <span class="s">"storage_queue"</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">"queue_service_uri"</span><span class="p">:</span> <span class="s">"https://mystorage.queue.core.windows.net"</span><span class="p">,</span> <span class="c1"># The Storage Account Queue Service URI
</span>            <span class="s">"queue_name"</span><span class="p">:</span> <span class="s">"my-input-queue"</span> <span class="c1"># The input queue (must match Azure Function trigger)
</span>          <span class="p">}</span>
        <span class="p">},</span>
        <span class="s">"output_binding"</span><span class="p">:</span> <span class="p">{</span>
          <span class="s">"type"</span><span class="p">:</span> <span class="s">"storage_queue"</span><span class="p">,</span>
          <span class="s">"storage_queue"</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">"queue_service_uri"</span><span class="p">:</span> <span class="s">"https://mystorage.queue.core.windows.net"</span><span class="p">,</span> <span class="c1"># The Storage Account Queue Service URI
</span>            <span class="s">"queue_name"</span><span class="p">:</span> <span class="s">"my-output-queue"</span> <span class="c1"># The output queue (must match Azure Function output)
</span>          <span class="p">}</span>
        <span class="p">}</span>
      <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">]</span>
<span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>For the Azure Function, it’s that the function described is setup to be triggered by Storage Queue and respond via Storage Queue (using the Python SDK and contextual comments):</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="rouge-code"><pre><span class="o">@</span><span class="n">app</span><span class="p">.</span><span class="n">function_name</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"GetProjectStatus"</span><span class="p">)</span> <span class="c1"># Matches the agent tool specification
</span><span class="o">@</span><span class="n">app</span><span class="p">.</span><span class="n">queue_trigger</span><span class="p">(</span> <span class="c1"># Function triggered when messages are available
</span>  <span class="n">arg_name</span><span class="o">=</span><span class="s">"request"</span><span class="p">,</span> 
  <span class="n">queue_name</span><span class="o">=</span><span class="s">"my-input-queue"</span><span class="p">,</span> <span class="c1"># Matches the agent tool specification
</span>  <span class="n">connection</span><span class="o">=</span><span class="s">"STORAGE_QUEUES_CONNECTION"</span><span class="p">)</span> <span class="c1"># Functions expects a setting name of 
</span>                                          <span class="c1"># "STORAGE_QUEUES_CONNECTION__queueServiceUri" to be set,
</span>                                          <span class="c1"># and it uses convention here to only require the first bit.
</span><span class="o">@</span><span class="n">app</span><span class="p">.</span><span class="n">queue_output</span><span class="p">(</span> <span class="c1"># Output binding to a storage queue when finished
</span>  <span class="n">arg_name</span><span class="o">=</span><span class="s">"response"</span><span class="p">,</span> 
  <span class="n">queue_name</span><span class="o">=</span><span class="s">"my-output-queue"</span><span class="p">,</span> <span class="c1"># Matches the agent tool specification
</span>  <span class="n">connection</span><span class="o">=</span><span class="s">"STORAGE_QUEUES_CONNECTION"</span><span class="p">)</span> <span class="c1"># See note on the trigger.
</span><span class="k">def</span> <span class="nf">get_project_status</span><span class="p">(</span><span class="n">request</span><span class="p">:</span> <span class="n">func</span><span class="p">.</span><span class="n">QueueMessage</span><span class="p">,</span> <span class="n">response</span><span class="p">:</span> <span class="n">func</span><span class="p">.</span><span class="n">Out</span><span class="p">[</span><span class="nb">str</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
  <span class="c1"># Decode the Storage Queue message (UTF-8 encoding), and load as JSON object
</span>  <span class="n">message_payload</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">get_body</span><span class="p">().</span><span class="n">decode</span><span class="p">(</span><span class="s">"utf-8"</span><span class="p">))</span>
  <span class="c1"># Grab any expected parameters -- always CorrelationId
</span>  <span class="n">correlation_id</span> <span class="o">=</span> <span class="n">message_payload</span><span class="p">[</span><span class="s">"CorrelationId"</span><span class="p">]</span>
  <span class="n">project_name</span> <span class="o">=</span> <span class="n">message_payload</span><span class="p">[</span><span class="s">"ProjectName"</span><span class="p">]</span>

  <span class="c1"># Do some work...
</span>  <span class="n">current_status</span> <span class="o">=</span> <span class="n">random</span><span class="p">.</span><span class="n">choice</span><span class="p">([</span><span class="s">"Active"</span><span class="p">,</span> <span class="s">"Completed"</span><span class="p">,</span> <span class="s">"Cancelled"</span><span class="p">,</span> <span class="s">"On Hold"</span><span class="p">])</span>

  <span class="c1"># Create the response. Don't forget that `Value` must be a string and always
</span>  <span class="c1"># include your entire response in `Value`. `CorrelationId` is also always
</span>  <span class="c1"># required to ensure the right Agent/thread pick up the response.
</span>  <span class="n">result</span> <span class="o">=</span> <span class="p">{</span>
      <span class="s">"Value"</span><span class="p">:</span> <span class="sa">f</span><span class="s">"Project </span><span class="si">{</span><span class="n">project_name</span><span class="si">}</span><span class="s">'s current status is: </span><span class="si">{</span><span class="n">current_status</span><span class="si">}</span><span class="s">"</span><span class="p">,</span>
      <span class="s">"CorrelationId"</span><span class="p">:</span> <span class="n">correlation_id</span><span class="p">,</span>
  <span class="p">}</span>
  <span class="c1"># Message formatted for a Storage Queue -- string with UTF-8 encoding
</span>  <span class="n">result_message</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">result</span><span class="p">).</span><span class="n">encode</span><span class="p">(</span><span class="s">"utf-8"</span><span class="p">)</span>
  <span class="n">response</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">result_message</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<div class="notice--danger">
    
<p><strong>Important: the return message matters!</strong> Be sure that the message you enqueue in the outbound queue is a json object that matches the schema:</p>
<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="rouge-code"><pre><span class="p">{</span><span class="w">
  </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"object"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"properties"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"Value"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"string"</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="nl">"CorrelationId"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"string"</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"required"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"Value"</span><span class="p">,</span><span class="w"> </span><span class="s2">"CorrelationId"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></pre></td></tr></tbody></table></code></pre></div></div>
<p>For example if your function needs to return an object instead of just a string:</p>
<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="p">{</span><span class="w">
    </span><span class="nl">"Value"</span><span class="p">:</span><span class="w"> </span><span class="s2">"{ </span><span class="se">\"</span><span class="s2">response</span><span class="se">\"</span><span class="s2">: </span><span class="se">\"</span><span class="s2">This is my response object, but it has to be a string.</span><span class="se">\"</span><span class="s2"> }"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"CorrelationId"</span><span class="p">:</span><span class="w"> </span><span class="s2">"this-comes-from-the-trigger-message-but-don't-forget-it!"</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></pre></td></tr></tbody></table></code></pre></div></div>
<p>In short, the AI Agent service expects <code class="language-plaintext highlighter-rouge">Value</code> to only be a string when it is processing the response from the Function. You can use a JSON object as long as it is in string format, but a structured output is not required.</p>

</div>

<p>The rest of the bits are really making sure the actual resources exist, have identities, and have permissions to interact with the other resources so that the queue-based integration can work as expected.</p>

<h2 id="lets-see-it-in-action">Let’s see it in action</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="rouge-code"><pre><span class="c"># Create a thread on the Agent</span>

<span class="nv">THREAD_ID</span><span class="o">=</span><span class="si">$(</span>az rest <span class="nt">--method</span> post <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/threads?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--body</span> <span class="s2">""</span> <span class="se">\</span>
<span class="nt">--query</span> <span class="nb">id</span> <span class="nt">--output</span> tsv<span class="si">)</span>

<span class="c"># Ask a question that requires a response from the Function</span>

az rest <span class="nt">--method</span> post <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/threads/<span class="nv">$THREAD_ID</span>/messages?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--body</span> <span class="s2">"{'role': 'user', 'content': 'What is the status of the Widget Whirlwind project?'}"</span>

<span class="c"># Run it and review the results</span>

<span class="nv">RUN_ID</span><span class="o">=</span><span class="si">$(</span>az rest <span class="nt">--method</span> post <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/threads/<span class="nv">$THREAD_ID</span>/runs?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--body</span> <span class="s2">"{'assistant_id': '</span><span class="nv">$AGENT_ID</span><span class="s2">'}"</span> <span class="se">\</span>
<span class="nt">--query</span> <span class="nb">id</span> <span class="nt">--output</span> tsv<span class="si">)</span>

<span class="c"># Poll run status until it's completed</span>

az rest <span class="nt">--method</span> get <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/threads/<span class="nv">$THREAD_ID</span>/runs/<span class="nv">$RUN_ID</span>?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--query</span> <span class="s2">"{Assistant: assistant_id, Thread: thread_id, RunStatus: status"</span><span class="o">}</span> <span class="se">\</span>
<span class="nt">--output</span> table

<span class="c"># Get the results of the run</span>

az rest <span class="nt">--method</span> get <span class="se">\</span>
<span class="nt">--resource</span> <span class="s2">"https://ml.azure.com/"</span> <span class="se">\</span>
<span class="nt">--url</span> <span class="nv">$AI_AGENT_ENDPOINT</span>/threads/<span class="nv">$THREAD_ID</span>/messages?api-version<span class="o">=</span><span class="nv">$API_VERSION</span> <span class="se">\</span>
<span class="nt">--query</span> <span class="s2">"reverse(data[].{Role: role, Message: content[0].text.value})"</span> <span class="se">\</span>
<span class="nt">--output</span> table
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Don’t believe it’s calling your Function? Let’s double check. You can go to the portal to navigate to the Function Invocations log to see the results of the run. <em>The invocations log may take up to five minutes to display invocation data.</em></p>

<p><img src="https://blog.awkward.industries/images/func-invocations-from-app-overview.png" alt="no-alignment" /></p>

<p>The invocation view will show the runs (successful or in error), and you can click on the invocation date to show the details:</p>

<p><img src="https://blog.awkward.industries/images/getprojectstatus-invocations.png" alt="no-alignment" /></p>

<h2 id="closing-thoughts-and-azd-shortcut">Closing thoughts (and <code class="language-plaintext highlighter-rouge">azd</code> shortcut)</h2>

<p>You now know how to setup an Azure AI Agent service that can automatically call Azure Functions. Congrats! If you’re finished playing and testing, don’t forget to cleanup your resources (e.g., <code class="language-plaintext highlighter-rouge">az group delete -n $RESOURCE_GROUP</code>).</p>

<p>If this feels like a lot to manually reproduce and you just want an easy end-to-end deployment, we’ve got you covered.</p>

<ol>
  <li>Make sure you have the <a href="https://learn.microsoft.com/en-us/azure/developer/azure-developer-cli/install-azd?tabs=winget-windows%2Cbrew-mac%2Cscript-linux&amp;pivots=os-windows">Azure Developer CLI</a> installed.</li>
  <li>Visit the Awkward Industries GitHub repository <a href="https://www.github.com/awkwardindustries/agents-and-functions-blog">agents-and-functions-blog</a> and clone it locally.</li>
  <li>Run <code class="language-plaintext highlighter-rouge">azd up</code>.</li>
  <li>Enjoy, and run <code class="language-plaintext highlighter-rouge">azd down</code> when you’re finished.</li>
</ol>

<p>Hopefully this demystifies the integration and shows how easy it can be to add your own custom Azure Functions to an AI Foundry Agent service. Happy hacking!</p>]]></content><author><name>Megan K. Meyer</name><email>mkm@awkward.industries</email></author><category term="AI" /><category term="Agents" /><category term="Azure AI Foundry" /><category term="Azure AI Agent Service" /><category term="Azure Functions" /><summary type="html"><![CDATA[Are you looking for a fast and easy way to provide custom business logic to your Agents without having to couple the function call to the Agent code? The **Azure AI Agent Service** is here to help with its **Azure Functions** integration!]]></summary></entry><entry><title type="html">Accessing Certificates in Service Fabric Hosted Windows Containers</title><link href="https://blog.awkward.industries/2018/06/30/accessing-certificates-in-service-fabric-hosted-windows-containers.html" rel="alternate" type="text/html" title="Accessing Certificates in Service Fabric Hosted Windows Containers" /><published>2018-06-30T00:00:00+00:00</published><updated>2018-06-30T00:00:00+00:00</updated><id>https://blog.awkward.industries/2018/06/30/accessing-certificates-in-service-fabric-hosted-windows-containers</id><content type="html" xml:base="https://blog.awkward.industries/2018/06/30/accessing-certificates-in-service-fabric-hosted-windows-containers.html"><![CDATA[<div id="entry-table-of-contents" class="toc-wrapper">
  <h2 id="toc-toggle" class="no_toc">
  Table of Contents <i class="toc-toggle-icon fas fa-chevron-down"></i>
</h2>
<ol id="markdown-toc">
  <li><a href="#create-a-web-application-for-containerization" id="markdown-toc-create-a-web-application-for-containerization">Create a Web Application for Containerization</a></li>
  <li><a href="#make-it-service-fabric-ready" id="markdown-toc-make-it-service-fabric-ready">Make it Service Fabric Ready</a></li>
  <li><a href="#configure-the-setupentrypoint-and-scripts" id="markdown-toc-configure-the-setupentrypoint-and-scripts">Configure the SetupEntryPoint and Scripts</a></li>
  <li><a href="#test-it-out" id="markdown-toc-test-it-out">Test it Out</a></li>
  <li><a href="#encryption" id="markdown-toc-encryption">Encryption</a></li>
  <li><a href="#decryption" id="markdown-toc-decryption">Decryption</a></li>
  <li><a href="#summary" id="markdown-toc-summary">Summary</a></li>
</ol>

</div>

<p class="notice"><em>This blog was originally posted on June 30, 2018. Much of the data, information, images, and links are outdated. It is included in its original form as an archive.</em></p>

<p>Azure Service Fabric is a great platform for container orchestration. It provides a full suite of features to ensure that your container is held up by the <a href="https://docs.microsoft.com/en-us/azure/architecture/guide/pillars">five pillars of software quality</a> – ensuring scalability, availability, resiliency, management, and security. Assuming your containerized application may need access to certificates to handle encryption, decryption, signing, or verification, Service Fabric even provides a built-in way to expose certificates installed in the LocalMachine store to the container by using a <code class="language-plaintext highlighter-rouge">ContainerHostPolicy</code>. You can also explicitly provide certificate files as part of the Data Package. Both approaches are documented well in the <a href="https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-securing-containers">use a certificate in a container</a> topic in the docs. What if you need more control over the certificates? What if they’re not installed on the node and you need to dynamically make them available to your container at the time of service startup? What actually needs to happen in the setupentrypoint.sh script?</p>

<p>This post shows how you can utilize SetupEntryPoint scripts to manage acquiring certificates and making them available to your Service Fabric hosted container. It will depend on the LocalMachine certificate store to provide the initial certificate, but it could also be a certificate file pulled from Azure Key Vault or some other certificate store. This code was originally created using Visual Studio 15.7.4 (taking advantage of the <a href="https://azure.microsoft.com/en-us/blog/container-tooling-for-service-fabric/">new container tooling</a>) and the Microsoft Azure Service Fabric SDK version 3.1.269.9494.</p>

<h2 id="create-a-web-application-for-containerization">Create a Web Application for Containerization</h2>

<p>With the container tooling available in the Service Fabric tools (Visual Studio 15.7 or greater), creating a Service Fabric hosted container is really simple. I started with an ASP.NET Core Web Application with a controller that handled encryption and decryption actions. I broke out the encryption and decryption into a separate service so that the certificate would only have to be loaded once. When finished, the controller remains very light:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
</pre></td><td class="rouge-code"><pre><span class="k">using</span> <span class="nn">Microsoft.AspNetCore.Http</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">Microsoft.AspNetCore.Mvc</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">System</span><span class="p">;</span>

<span class="k">namespace</span> <span class="nn">ContainerCrypto.Controllers</span>
<span class="p">{</span>
    <span class="p">[</span><span class="nf">Produces</span><span class="p">(</span><span class="s">"application/json"</span><span class="p">)]</span>
    <span class="p">[</span><span class="nf">Route</span><span class="p">(</span><span class="s">"[controller]"</span><span class="p">)]</span>
    <span class="k">public</span> <span class="k">class</span> <span class="nc">CryptoController</span> <span class="p">:</span> <span class="n">Controller</span>
    <span class="p">{</span>
        <span class="k">private</span> <span class="n">IStringCryptoService</span> <span class="n">_stringCryptoService</span><span class="p">;</span>

        <span class="k">public</span> <span class="nf">CryptoController</span><span class="p">(</span><span class="n">IStringCryptoService</span> <span class="n">stringCryptoService</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">_stringCryptoService</span> <span class="p">=</span> <span class="n">stringCryptoService</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="p">[</span><span class="n">HttpPost</span><span class="p">]</span>
        <span class="p">[</span><span class="nf">Route</span><span class="p">(</span><span class="s">"encrypt"</span><span class="p">)]</span>
        <span class="k">public</span> <span class="n">IActionResult</span> <span class="nf">Encrypt</span><span class="p">([</span><span class="n">FromBody</span><span class="p">]</span> <span class="kt">string</span> <span class="n">textToEncrypt</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">try</span>
            <span class="p">{</span>
                <span class="kt">var</span> <span class="n">encryptedText</span> <span class="p">=</span> <span class="n">_stringCryptoService</span><span class="p">.</span><span class="nf">Encrypt</span><span class="p">(</span><span class="n">textToEncrypt</span><span class="p">);</span>
                <span class="k">return</span> <span class="nf">Ok</span><span class="p">(</span><span class="n">encryptedText</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="k">return</span> <span class="nf">StatusCode</span><span class="p">(</span><span class="n">StatusCodes</span><span class="p">.</span><span class="n">Status500InternalServerError</span><span class="p">,</span> <span class="n">ex</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>

        <span class="p">[</span><span class="n">HttpPost</span><span class="p">]</span>
        <span class="p">[</span><span class="nf">Route</span><span class="p">(</span><span class="s">"decrypt"</span><span class="p">)]</span>
        <span class="k">public</span> <span class="n">IActionResult</span> <span class="nf">Decrypt</span><span class="p">([</span><span class="n">FromBody</span><span class="p">]</span> <span class="kt">string</span> <span class="n">base64EncodedTextToDecrypt</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">try</span>
            <span class="p">{</span>
                <span class="kt">var</span> <span class="n">decryptedText</span> <span class="p">=</span> <span class="n">_stringCryptoService</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">base64EncodedTextToDecrypt</span><span class="p">);</span>
                <span class="k">return</span> <span class="nf">Ok</span><span class="p">(</span><span class="n">decryptedText</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="k">return</span> <span class="nf">StatusCode</span><span class="p">(</span><span class="n">StatusCodes</span><span class="p">.</span><span class="n">Status500InternalServerError</span><span class="p">,</span> <span class="n">ex</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The encryption and decryption service <code class="language-plaintext highlighter-rouge">CertStringCryptoService</code> is mainly responsible for loading a certificate and storing its public and private keys for encryption and decryption respectively. Since it will be hosted in a container, the code depends on environment variables to be configured at runtime. In this case, it will need to know the path to the certificate PFX file and the path to a file containing the password to access the PFX. It will then use the retrieved keys for encryption and decryption.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="rouge-code"><pre><span class="k">public</span> <span class="kt">string</span> <span class="nf">Encrypt</span><span class="p">(</span><span class="kt">string</span> <span class="n">plainTextToEncrypt</span><span class="p">)</span>
<span class="p">{</span>
  <span class="nf">EnsurePublicKey</span><span class="p">();</span>
  <span class="kt">var</span> <span class="n">contentToEncrypt</span> <span class="p">=</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">Default</span><span class="p">.</span><span class="nf">GetBytes</span><span class="p">(</span><span class="n">plainTextToEncrypt</span><span class="p">);</span>
  <span class="kt">var</span> <span class="n">encryptedBytes</span> <span class="p">=</span> <span class="n">publicKey</span><span class="p">.</span><span class="nf">Encrypt</span><span class="p">(</span><span class="n">contentToEncrypt</span><span class="p">,</span> <span class="n">RSAEncryptionPadding</span><span class="p">.</span><span class="n">Pkcs1</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">Convert</span><span class="p">.</span><span class="nf">ToBase64String</span><span class="p">(</span><span class="n">encryptedBytes</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">public</span> <span class="kt">string</span> <span class="nf">Decrypt</span><span class="p">(</span><span class="kt">string</span> <span class="n">base64EncodedTextToDecrypt</span><span class="p">)</span>
<span class="p">{</span>
  <span class="nf">EnsurePrivateKey</span><span class="p">();</span>
  <span class="kt">var</span> <span class="n">contentToDecrypt</span> <span class="p">=</span> <span class="n">Convert</span><span class="p">.</span><span class="nf">FromBase64String</span><span class="p">(</span><span class="n">base64EncodedTextToDecrypt</span><span class="p">);</span>
  <span class="kt">var</span> <span class="n">decryptedBytes</span> <span class="p">=</span> <span class="n">privateKey</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">contentToDecrypt</span><span class="p">,</span> <span class="n">RSAEncryptionPadding</span><span class="p">.</span><span class="n">Pkcs1</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">Default</span><span class="p">.</span><span class="nf">GetString</span><span class="p">(</span><span class="n">decryptedBytes</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">void</span> <span class="nf">LoadKeysFromCertificateFile</span><span class="p">()</span>
<span class="p">{</span>
  <span class="c1">// Get password from file</span>
  <span class="kt">string</span> <span class="n">password</span> <span class="p">=</span> <span class="n">File</span><span class="p">.</span><span class="nf">ReadAllLines</span><span class="p">(</span>
    <span class="n">EnvironmentVariables</span><span class="p">.</span><span class="n">FullPathToCertificatePfxPasswordFile</span><span class="p">,</span>  
    <span class="n">Encoding</span><span class="p">.</span><span class="n">Default</span><span class="p">)[</span><span class="m">0</span><span class="p">];</span>
  <span class="n">password</span> <span class="p">=</span> <span class="n">password</span><span class="p">.</span><span class="nf">Replace</span><span class="p">(</span><span class="s">"\0"</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">);</span>

  <span class="c1">// Load certificate from file</span>
  <span class="n">X509Certificate2</span> <span class="n">certificate</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">X509Certificate2</span><span class="p">(</span>
    <span class="n">EnvironmentVariables</span><span class="p">.</span><span class="n">FullPathToCertificatePfxFile</span><span class="p">,</span> <span class="n">password</span><span class="p">);</span>

  <span class="n">publicKey</span> <span class="p">=</span> <span class="n">certificate</span><span class="p">.</span><span class="nf">GetRSAPublicKey</span><span class="p">();</span>
  <span class="n">privateKey</span> <span class="p">=</span> <span class="n">certificate</span><span class="p">.</span><span class="nf">GetRSAPrivateKey</span><span class="p">();</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>With this, we have a solution that can be run and tested as-is if the environment variables have been set. The two used are:</p>
<ul>
  <li>Custom_PfxFileName</li>
  <li>Custom_PfxPasswordFileName</li>
</ul>

<p>There is a third environment variable, <code class="language-plaintext highlighter-rouge">Fabric_Folder_App_Work</code>, required for the solution to work. This environment variable is automatically set by the Service Fabric runtime; however, you would need to explicitly set it to be the base path in which the PFX and PFX password files would be found for this to work outside of a Service Fabric hosted container.</p>

<h2 id="make-it-service-fabric-ready">Make it Service Fabric Ready</h2>

<p>How do we containerize our web application and setup a Service Fabric application to host and orchestrate the solution? <strong>Easy.</strong> Right-click on your ASP.NET Core Application project, and select <em>Add &gt; Container Orchestrator Support</em>. Select <em>Service Fabric</em> from the dialog drop-down and confirm with <em>OK</em>. <strong>You now have a Service Fabric application that is configured to host your web application in a container.</strong></p>

<p>Let’s look at what really happened when we added orchestrator support. First, the only change to our existing ASP.NET Core Web Application project is that a <em>PackageRoot</em> directory and a <em>Dockerfile</em> are added. The <em>PackageRoot</em> directory contains Service Fabric service artifacts that build out the service package such as the <em>Config</em> directory representing the Config package and the <em>ServiceManifest.xml</em> that declaratively defines the service type, version, and any other service-specific metadata. The <em>Dockerfile</em> allows Docker to build out the image for your ASP.NET Core Web Application and is used by the build and deploy tasks.</p>

<p>Second, there’s now a Service Fabric Application project in your solution. This declaratively defines the application type, version, and provides information about the services that make up that application. We’ll mainly be interested in the <em>ApplicationManifest.xml</em> under the <em>ApplicationPackageRoot</em>.</p>

<h2 id="configure-the-setupentrypoint-and-scripts">Configure the SetupEntryPoint and Scripts</h2>

<p>The SetupEntryPoint is a great place to execute any kind of service setup that might require elevated permissions or access on the node. More information can be found in the documentation <a href="https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-run-script-at-service-startup">here</a>.</p>

<p>We’ll need to create the <em>Code</em> directory under our service / ASP.NET Core Web Application project’s <em>PackageRoot</em> directory. This location will hold our setup scripts as they will now be part of the service fabric service code package. The SetupEntryPoint executable host requires either .EXE, .BAT, or .CMD files; however, we want to run a PowerShell script. To do that, simply create a CMD or BAT file with nothing more than a line to invoke the PowerShell executable with our PowerShell script.</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="err">@</span><span class="n">echo</span><span class="w"> </span><span class="nx">off</span><span class="w">
</span><span class="n">powershell.exe</span><span class="w"> </span><span class="nt">-ExecutionPolicy</span><span class="w"> </span><span class="nx">Bypass</span><span class="w"> </span><span class="nt">-Command</span><span class="w"> </span><span class="s2">".\setup.ps1"</span><span class="w">
</span></pre></td></tr></tbody></table></code></pre></div></div>

<p>Our PowerShell script will be doing the work. The first thing it does is randomly generate a password that will be used to secure the exported PFX. It also depends on a new environment variable – <code class="language-plaintext highlighter-rouge">Custom_CertThumbprint</code> – that will help it find the correct certificate in the LocalMachine store. Once it’s found the certificate, it will create a file containing the password and export a PFX secured with that password to the locations built from both the Service Fabric work directory and provided <code class="language-plaintext highlighter-rouge">Custom_PfxFileName</code> and <code class="language-plaintext highlighter-rouge">Custom_PfxPasswordFileName</code> environment variables.</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="rouge-code"><pre><span class="c"># Generate a random password. This is used to secure the exported PFX</span><span class="w">
</span><span class="c"># and will be added to the generated password file.</span><span class="w">
</span><span class="p">[</span><span class="n">Reflection.Assembly</span><span class="p">]::</span><span class="n">LoadWithPartialName</span><span class="p">(</span><span class="s2">"System.Web"</span><span class="p">)</span><span class="w">
</span><span class="nv">$password</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="n">System.Web.Security.Membership</span><span class="p">]::</span><span class="n">GeneratePassword</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span><span class="w">

</span><span class="c"># Find the cert with the thumbprint matching that provided in the</span><span class="w">
</span><span class="c"># Custom_CertThumbprint environment variable. Additional</span><span class="w">
</span><span class="c"># checks such as finding the one with the latest expiration date</span><span class="w">
</span><span class="c"># may be preferred.</span><span class="w">
</span><span class="nv">$matchedCerts</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Get-ChildItem</span><span class="w"> </span><span class="nt">-Path</span><span class="w"> </span><span class="nx">cert:\LocalMachine\My</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="nf">?</span><span class="p">{</span><span class="w"> </span><span class="bp">$_</span><span class="o">.</span><span class="nf">Thumbprint</span><span class="w"> </span><span class="o">-eq</span><span class="w"> </span><span class="s2">"</span><span class="nv">$</span><span class="nn">env</span><span class="p">:</span><span class="nv">Custom_CertThumbprint</span><span class="s2">"</span><span class="w"> </span><span class="p">}</span><span class="w">
</span><span class="nv">$certToExport</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nv">$matchedCerts</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="w">

</span><span class="c"># Build the destination full paths for the certificate and password</span><span class="w">
</span><span class="c"># file using Service Fabric's work directory for the service and</span><span class="w">
</span><span class="c"># provided Custom_PfxFileName and Custom_PfxPasswordFileName</span><span class="w">
</span><span class="c"># environment variables</span><span class="w">
</span><span class="nv">$certDestinationPath</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Join-Path</span><span class="w"> </span><span class="nt">-Path</span><span class="w"> </span><span class="nv">$</span><span class="nn">env</span><span class="p">:</span><span class="nv">Fabric_Folder_App_Work</span><span class="w"> </span><span class="nt">-ChildPath</span><span class="w"> </span><span class="nv">$</span><span class="nn">env</span><span class="p">:</span><span class="nv">Custom_PfxFileName</span><span class="w">
</span><span class="nv">$passwordDestinationPath</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Join-Path</span><span class="w"> </span><span class="nt">-Path</span><span class="w"> </span><span class="nv">$</span><span class="nn">env</span><span class="p">:</span><span class="nv">Fabric_Folder_App_Work</span><span class="w"> </span><span class="nt">-ChildPath</span><span class="w"> </span><span class="nv">$</span><span class="nn">env</span><span class="p">:</span><span class="nv">Custom_PfxPasswordFileName</span><span class="w">

</span><span class="c"># Write out the plain text password to file</span><span class="w">
</span><span class="nv">$password</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="n">Out-File</span><span class="w"> </span><span class="nv">$passwordDestinationPath</span><span class="w">

</span><span class="c"># Export the PFX with private key</span><span class="w">
</span><span class="nv">$securePassword</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">ConvertTo-SecureString</span><span class="w"> </span><span class="nt">-String</span><span class="w"> </span><span class="nv">$password</span><span class="w"> </span><span class="nt">-Force</span><span class="w"> </span><span class="err">–</span><span class="nx">AsPlainText</span><span class="w">
</span><span class="n">Export-PfxCertificate</span><span class="w"> </span><span class="nt">-Cert</span><span class="w"> </span><span class="nv">$certToExport</span><span class="w"> </span><span class="nt">-FilePath</span><span class="w"> </span><span class="nv">$certDestinationPath</span><span class="w"> </span><span class="nt">-Password</span><span class="w"> </span><span class="nv">$securePassword</span><span class="w"> </span><span class="nt">-Verbose</span><span class="w">
</span></pre></td></tr></tbody></table></code></pre></div></div>

<p>To let Service Fabric know that we have setup scripts for this particular service, we’ll need to update the <em>ServiceManifest.xml</em> by adding a <code class="language-plaintext highlighter-rouge">SetupEntryPoint</code> element under the <code class="language-plaintext highlighter-rouge">CodePackage</code> element. It will tell Service Fabric to start with the <em>setup.cmd</em> program and to run out of the <em>CodePackage</em>. This is important since our setup script expects our <em>setup.ps1</em> script to be in the same directory as we’re running. You can also use a <code class="language-plaintext highlighter-rouge">ConsoleRedirection</code> element for debugging only.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
</pre></td><td class="rouge-code"><pre><span class="nt">&lt;SetupEntryPoint&gt;</span>
  <span class="nt">&lt;ExeHost&gt;</span>
    <span class="nt">&lt;Program&gt;</span>setup.cmd<span class="nt">&lt;/Program&gt;</span>
    <span class="nt">&lt;WorkingFolder&gt;</span>CodePackage<span class="nt">&lt;/WorkingFolder&gt;</span>
    <span class="nt">&lt;ConsoleRedirection</span> <span class="na">FileRetentionCount=</span><span class="s">"5"</span> <span class="na">FileMaxSizeInKb=</span><span class="s">"2048"</span> <span class="nt">/&gt;</span>
  <span class="nt">&lt;/ExeHost&gt;</span>
<span class="nt">&lt;/SetupEntryPoint&gt;</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Service Fabric uses the <em>ApplicationManifest.xml</em> to control how services are run – including the SetupEntryPoint. To run our setup scripts with elevated permissions, we’ll need to update the Application Manifest. We’ll do two things – 1) define a <code class="language-plaintext highlighter-rouge">SetupAdminUser</code> in the Administrators group, and 2) add a <code class="language-plaintext highlighter-rouge">RunAsPolicy</code> element to our service to run the setup as the <em>SetupAdminUser</em>. This <code class="language-plaintext highlighter-rouge">Principals</code> element can be added to the end of the manifest, just after the <code class="language-plaintext highlighter-rouge">DefaultServices</code> element.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
</pre></td><td class="rouge-code"><pre><span class="nt">&lt;Principals&gt;</span>
  <span class="nt">&lt;Users&gt;</span>
    <span class="nt">&lt;User</span> <span class="na">Name=</span><span class="s">"SetupAdminUser"</span><span class="nt">&gt;</span>
      <span class="nt">&lt;MemberOf&gt;</span>
        <span class="nt">&lt;SystemGroup</span> <span class="na">Name=</span><span class="s">"Administrators"</span> <span class="nt">/&gt;</span>
      <span class="nt">&lt;/MemberOf&gt;</span>
    <span class="nt">&lt;/User&gt;</span>
  <span class="nt">&lt;/Users&gt;</span>
<span class="nt">&lt;/Principals&gt;</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This <code class="language-plaintext highlighter-rouge">RunAsPolicy</code> element will need to be added to the <code class="language-plaintext highlighter-rouge">Policies</code> under the <code class="language-plaintext highlighter-rouge">ServiceManifestImport</code> for our encrypting / decrypting service. In this case, there’s only one, but if there is more than one service in your application be sure to add the policy to the correct one. This policy specifies only the <em>Setup</em> entry point execute as this user, so the actual container host will continue to execute as the default user – likely Network Service. We want to avoid increasing the privileges of the container host, so this is exactly what we want, but you could run the container host with administrator privileges as well by changing the <em>EntrypPointType</em> to <em>Main</em> or <em>All</em> for both to run elevated.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="nt">&lt;RunAsPolicy</span> <span class="na">CodePackageRef=</span><span class="s">"Code"</span> <span class="na">UserRef=</span><span class="s">"SetupAdminUser"</span> <span class="na">EntryPointType=</span><span class="s">"Setup"</span> <span class="nt">/&gt;</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h2 id="test-it-out">Test it Out</h2>

<p>With this in place, the code we wrote in our encryption and decryption service will now be able to pull from a known location at runtime – even when being hosted within the container on Service Fabric. Let’s test it out to be sure. To test, just publish the Service Fabric application to a Service Fabric cluster that supports Windows containers.</p>

<p class="notice--warning">Note: Original image with caption ‘Publish Service Fabric Application dialog’ no longer available.</p>

<p>Since the controller was written to expect HTTP POST actions with bodies containing strings to be either encoded or decoded, you can use your favorite HTTP client to test. Just replace the cluster URL with the correct URL hosting your application. Don’t forget that you may need to update your load balancer to allow the port over which your service endpoint has been configured to pass through to your node(s). Also, make sure the certificate for which you’re providing a thumbprint is actually installed in the local machine store on all of the nodes.</p>

<h2 id="encryption">Encryption</h2>

<p class="notice--warning">Note: Original image with caption ‘Postman screen capture showing encryption request and response’ no longer available.</p>

<h2 id="decryption">Decryption</h2>

<p class="notice--warning">Note: Original image with caption ‘Postman screen capture showing decryption request and response’ no longer available.</p>

<h2 id="summary">Summary</h2>

<p>If you’re only in need of certificates known to already be installed on the node, you should continue to use the guidance to import a certificate file through the <code class="language-plaintext highlighter-rouge">CertificateRef</code> element in the <code class="language-plaintext highlighter-rouge">ContainerHostPolicies</code> in your ApplicationManifest.xml. However, this blog covers an approach that allows greater control and flexibility at the time of service setup so that you can have runtime access to certificate files within your container. A complete working example is available on the <a href="https://github.com/awkwardindustries">AwkwardIndustries</a> GitHub site in the <a href="https://github.com/awkwardindustries/servicefabric-containers-crypto">servicefabric-containers-crypto</a> repository.</p>

<p>Happy hacking!</p>]]></content><author><name>Megan K. Meyer</name><email>mkm@awkward.industries</email></author><category term="Microsoft Azure" /><category term="Azure Service Fabric" /><category term="Containers" /><summary type="html"><![CDATA[**Azure Service Fabric** is a robust platform for **container orchestration**, ensuring **scalability, availability, resiliency, management, and security**. It supports certificate access for encryption via a `ContainerHostPolicy` or by including certificate files in the Data Package. For dynamic certificate management at service startup, the `setupentrypoint.sh` script can be utilized.]]></summary></entry><entry><title type="html">Self-Hosting a Bot in Service Fabric with Katana</title><link href="https://blog.awkward.industries/2017/12/29/self-hosting-a-bot-in-service-fabric-with-katana.html" rel="alternate" type="text/html" title="Self-Hosting a Bot in Service Fabric with Katana" /><published>2017-12-29T00:00:00+00:00</published><updated>2017-12-29T00:00:00+00:00</updated><id>https://blog.awkward.industries/2017/12/29/self-hosting-a-bot-in-service-fabric-with-katana</id><content type="html" xml:base="https://blog.awkward.industries/2017/12/29/self-hosting-a-bot-in-service-fabric-with-katana.html"><![CDATA[<div id="entry-table-of-contents" class="toc-wrapper">
  <h2 id="toc-toggle" class="no_toc">
  Table of Contents <i class="toc-toggle-icon fas fa-chevron-down"></i>
</h2>
<ol id="markdown-toc">
  <li><a href="#setting-up-the-service-fabric-application" id="markdown-toc-setting-up-the-service-fabric-application">Setting up the Service Fabric Application</a></li>
  <li><a href="#creating-the-owin-icommunicationlistener" id="markdown-toc-creating-the-owin-icommunicationlistener">Creating the OWIN ICommunicationListener</a></li>
  <li><a href="#adding-the-bot" id="markdown-toc-adding-the-bot">Adding the Bot</a></li>
  <li><a href="#summary" id="markdown-toc-summary">Summary</a></li>
</ol>

</div>

<p class="notice"><em>This blog was originally posted on December 29, 2017. Much of the data, information, images, and links are outdated. It is included in its original form as an archive.</em></p>

<p>I recently participated in a small hackathon with some Microsoft ninjas where we were presented with the problem, <em>How do you host a bot in Service Fabric?</em> It seemed like an easy problem that had probably already been solved, but it wasn’t as straightforward as we thought it might be.</p>

<p>At its core from a technology perspective, a bot is really just a Web API. We didn’t want to actually host IIS on Service Fabric, so we knew we would want to self-host. If you use the built-in Stateless Service ASP.NET Core template, you’ll get a great Web API implementation that’s wired up with a <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.servicefabric.services.communication.aspnetcore.kestrelcommunicationlistener?view=azure-dotnet">KestrelCommunicationListener</a> for Service Fabric. But what if you want to use Kata – Microsoft’s .NET Framework OWIN implementation?</p>

<blockquote>
  <p>Katana is a flexible set of components for building and hosting OWIN-based web applications on .NET Framework.</p>

  <footer> Microsoft's <a href="https://github.com/aspnet/AspNetKatana">Katana Project</a> on GitHub</footer>
</blockquote>

<p>Although ASP.NET Core has incorporated most of the Katana project’s functionality, the project will still be kept up-to-date and ensure any bugs are fixed per their <a href="https://github.com/aspnet/AspNetKatana/wiki/Roadmap">roadmap</a>. Most will look to ASP.NET Core for new functionality, but if you are maintaining a project built with a Katana dependency that you would like to port to be hosted in Service Fabric, you will only need to build a Katana-based ICommunicationListener implementation.</p>

<p class="notice--info">This project was built and all screenshots were taken using Visual Studio 2017, version 15.5.2</p>

<h2 id="setting-up-the-service-fabric-application">Setting up the Service Fabric Application</h2>

<p>We know we’d like to build a Stateless Service to host the Web API, so we’ll first create the Service Fabric Application by using the File menu &gt; New &gt; Project… option. Find Service Fabric Application under the C# / Cloud templates.</p>

<p class="notice--warning">Note: Original image with caption ‘New Project dialog for creating a Service Fabric Application’ no longer available.</p>

<p>After you’ve picked a name for your application, select Stateless Service as your first service in the application. If you select Stateless Service ASP.NET Core, it will automatically include the KestrelCommunicationListener and stub out an ASP.NET Core Controller; however, selecting the Stateless Service will create a service with only Service Fabric scaffolding and no default communication listeners.</p>

<p class="notice--warning">Note: Original image with caption ‘New Service Fabric Service dialog’ no longer available.</p>

<p>At this point, we just need to create a Service Fabric ICommunicationListener for Katana, and we should be able to self-host any full framework ASP.NET website within Service Fabric.</p>

<h2 id="creating-the-owin-icommunicationlistener">Creating the OWIN ICommunicationListener</h2>

<p>It turns out we definitely were not the first to have to implement an OWIN ICommunicationListener, but it is not something available in the Service Fabric libraries. <a href="https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication">This page</a> of the documentation describes how to implement your own communication listener as required for Service Fabric reliable services communication stack. The Service Fabric team also has provided a sample available as part of the Azure Service Fabric Party Cluster <a href="https://github.com/Azure-Samples/service-fabric-dotnet-management-party-cluster">sample</a>. The <a href="https://github.com/Azure-Samples/service-fabric-dotnet-management-party-cluster/tree/master/src/PartyCluster.WebService">PartyCluster.WebService</a> uses an <a href="https://github.com/Azure-Samples/service-fabric-dotnet-management-party-cluster/blob/master/src/PartyCluster.WebService/OwinCommunicationListener.cs">OwinCommunicationListener</a>. There is also a somewhat-outdated example documented <a href="https://github.com/Huachao/azure-content/blob/master/articles/service-fabric/service-fabric-reliable-services-communication-webapi.md">here</a> that helps describe the implementation step-by-step. Because this example has not been kept up-to-date, there are a few method signatures that are no longer correct, but it might be worth a read to understand what is happening before using the OwinCommunicationListener from the Party Cluster sample.</p>

<p>Pulling this all together, our Stateless Service code now has four additional updates:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">OwinCommunicationListener</code> class: Sets up the Katana-based self-hosted web server and manages it within the Service Fabric Reliable Services communication stack</li>
  <li><code class="language-plaintext highlighter-rouge">IOwinAppBuilder</code> class: Interface supporting OWIN configuration as part of the application builder stack during startup</li>
  <li><code class="language-plaintext highlighter-rouge">Startup</code> class: Startup class to support configuration; passed into the <code class="language-plaintext highlighter-rouge">OwinCommunicationListener</code></li>
  <li>Updates to <code class="language-plaintext highlighter-rouge">StatelessService</code> implementation: Registers the <code class="language-plaintext highlighter-rouge">OwinCommunicationListener</code> in the <code class="language-plaintext highlighter-rouge">CreateServiceInstanceListeners()</code> override</li>
</ul>

<p>You’ll also need to configure the service to define the ports that will be used. For this example, we used port 80. This must be added to the configuration in the Service Manifest (found under the PackageRoot directory). Update the <code class="language-plaintext highlighter-rouge">ResourceEndpoints</code> section so that it includes the following for this <code class="language-plaintext highlighter-rouge">ServiceEndpoint</code>:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="nt">&lt;Endpoint</span> <span class="na">Name=</span><span class="s">"ServiceEndpoint"</span> <span class="na">Protocol=</span><span class="s">"http"</span> <span class="na">Port=</span><span class="s">"80"</span> <span class="na">Type=</span><span class="s">"Input"</span> <span class="nt">/&gt;</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h2 id="adding-the-bot">Adding the Bot</h2>

<p>We decided to make one additional change in our implementation. We wanted to keep our Stateless Service as thin as possible, so we created a separate Web API project to contain our controllers, models, and some startup information versus adding these files directly within the Stateless Service project.</p>

<p>For this example, we just used the basic Echo Bot provided as part of the Microsoft Bot Framework’s Bot Builder SDK. Their <a href="https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-quickstart">quickstart</a> provides a great walkthrough as well as links to download the Visual Studio templates. Once the templates are installed on your machine, you just have to right-click the solution and add a new project. Search for and select Bot Application.</p>

<p class="notice--warning">Note: Original image with caption ‘Add New Project dialog adding a Bot Application’ no longer available.</p>

<p>You now have an Echo Bot ready for use in your application. The final piece that ties these two projects together is the addition of configuration in the <code class="language-plaintext highlighter-rouge">Startup</code> class we added to the Stateless Service project. It needs a reference to the Bot Application project so that you can make a call to <code class="language-plaintext highlighter-rouge">WebApiConfig.Register(config);</code>. You’ll also need to ensure <code class="language-plaintext highlighter-rouge">appBuilder.UseWebApi(config);</code> is called since it will setup the Web API bits in the OWIN stack to ensure that is routed and handled correctly by your controllers.</p>

<h2 id="summary">Summary</h2>

<p>Although the Katana implementation has been supplanted by a fully-featured ASP.NET Core stack, it may be helpful to support some legacy applications with Katana dependencies in Service Fabric. With these small changes, you can have a complete OWIN stack based on the full-framework Katana project implementation for use within Service Fabric. A complete working example is available on the <a href="https://github.com/codingwithsasquatch">CodingWithSasquatch</a> GitHub site in the <a href="https://github.com/codingwithsasquatch/Zohan.ServiceFabricBot">Zohan.ServiceFabricBot</a> repository.</p>

<p>Happy Hacking!</p>]]></content><author><name>Megan K. Meyer</name><email>mkm@awkward.industries</email></author><category term="Microsoft Azure" /><category term="Azure Service Fabric" /><category term="Project Katana" /><category term="OWIN" /><category term="Microsoft Bot Framework" /><summary type="html"><![CDATA[I recently joined a hackathon with Microsoft experts, tackling the challenge of **hosting a bot in Service Fabric**. Initially, it seemed like a simple problem, but it turned out to be more complex than we anticipated.]]></summary></entry><entry><title type="html">Microsoft Flow: Expose Public APIs via Custom Connector</title><link href="https://blog.awkward.industries/2017/09/08/microsoft-flow-expose-public-apis-via-custom-connector.html" rel="alternate" type="text/html" title="Microsoft Flow: Expose Public APIs via Custom Connector" /><published>2017-09-08T00:00:00+00:00</published><updated>2017-09-08T00:00:00+00:00</updated><id>https://blog.awkward.industries/2017/09/08/microsoft-flow-expose-public-apis-via-custom-connector</id><content type="html" xml:base="https://blog.awkward.industries/2017/09/08/microsoft-flow-expose-public-apis-via-custom-connector.html"><![CDATA[<div id="entry-table-of-contents" class="toc-wrapper">
  <h2 id="toc-toggle" class="no_toc">
  Table of Contents <i class="toc-toggle-icon fas fa-chevron-down"></i>
</h2>
<ol id="markdown-toc">
  <li><a href="#microsoft-flow-azure-logic-apps-or-azure-functions" id="markdown-toc-microsoft-flow-azure-logic-apps-or-azure-functions">Microsoft Flow, Azure Logic Apps, or Azure Functions?</a></li>
  <li><a href="#building-a-microsoft-flow-or-logic-app-connector" id="markdown-toc-building-a-microsoft-flow-or-logic-app-connector">Building a Microsoft Flow or Logic App Connector</a></li>
  <li><a href="#registering-my-application" id="markdown-toc-registering-my-application">Registering my application</a></li>
  <li><a href="#creating-the-custom-connector" id="markdown-toc-creating-the-custom-connector">Creating the custom connector</a></li>
  <li><a href="#summary" id="markdown-toc-summary">Summary</a></li>
</ol>

</div>

<p class="notice"><em>This blog was originally posted on September 8, 2017. Much of the data, information, images, and links are outdated. It is included in its original form as an archive.</em></p>

<p>I love fitness trackers. I was excited to get the new Fitbit Alta HR, but some of my eagerness waned when I remembered why I hadn’t used Fitbit since my old Fitbit One – I hated how it didn’t integrate with any of my other applications I used to track my information. Fitbit does support some <a href="https://www.fitbit.com/partnership">integration with partner apps</a>, but just not with any apps that I happen to prefer and use.</p>

<p>I’m an Android user. I’ve started to look at Google Fit as a hub for all of my fitness data, but I’m not completely sold on that yet. I’ve been using Nike+ Run Club since I jumped on the Nike bandwagon years ago and purchased the Nike+ iPod Sport Kit (back when I carried an iPod). I was so excited to have a sensor nestled in my shoe and a coach speaking to me as I was running! Fast-forward to now, and although my phone is the main sensor for everything, I still prefer to use the Nike+ applications to track my runs and training. Nike+ synchronizes data to Google Fit, but not to Fitbit. In this scenario, Fitbit is an island; it doesn’t integrate with Google Fit or Nike+.</p>

<p>Here’s the thing – all of these fitness services provide APIs to interact with their data. All I need to do is write something to make them all talk to each other. I want to achieve a few things; my solution needs to be:</p>

<ul>
  <li><strong>Easy.</strong> I can be pretty lazy when it comes to writing and maintaining software on my own time.</li>
  <li><strong>Flexible and Extensible.</strong> I’m not sure exactly what makes the most sense – what data I plan to move from one system to the other, how frequently, etc. I know if I can write something that keeps my options open, I’ll be more likely to continue using it.</li>
  <li><strong>Available.</strong> Years ago, I’d hosted a handwritten integrator application on my home computer that synchronized my Nike+ runs with Fitbit. It was unreliable because I did not have an environment meant to be “always on” at my home. I know I need something that’s hosted externally and has the ability to be executing reliably throughout the day to ensure my data is fresh.</li>
</ul>

<h2 id="microsoft-flow-azure-logic-apps-or-azure-functions">Microsoft Flow, Azure Logic Apps, or Azure Functions?</h2>

<p>Really, I’m looking for an easily configurable integration space. I immediately thought of a few Microsoft technologies – Microsoft Flow, Azure Logic Apps, and Azure Functions. I’m a developer, so I tend to start with code. For this solution, I’d really like the convenience of having an integration workspace that I can easily add/remove and configure components to move data between my systems. I have a good feeling that these technologies can all achieve my goals, and I’ll probably end up with a few different flavors as I move forward. Here’s a great <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-compare-logic-apps-ms-flow-webjobs">article</a> describing some of the differences between the technologies.</p>

<p>The main goal is to get data into and out of Fitbit, so I’ll start by building out a custom connector that can be used in both Flow and Logic Apps. That should provide me with the most flexibility until I have a better idea if more advanced customization is required. In this case since I just need access to Fitbit, I don’t think I’ll need any additional configuration. I can defer the decision between technologies until after I get a chance to see how the custom connector works for me.</p>

<blockquote>
  <p>Basically, connectors are web APIs that use REST for pluggable interfaces, Swagger metadata format for documentation, and JSON as their data exchange format.</p>

  <footer>Microsoft's <a href="https://docs.microsoft.com/en-us/azure/logic-apps/logic-apps-create-api-app">documentation</a> on custom connectors for logic apps</footer>
</blockquote>

<p>So will this work for me? Fitbit provides a REST web API, an OpenAPI (Swagger) specification, and uses JSON. Should be easy to get started.</p>

<h2 id="building-a-microsoft-flow-or-logic-app-connector">Building a Microsoft Flow or Logic App Connector</h2>

<p>Creating a custom connector for either Microsoft Flow or an Azure Logic App is very similar, and both approaches share similar setup and requirements. I’ll be creating one for Microsoft Flow. While the custom connector should be easy to build out by importing the OpenAPI specification, there are a few requirements of the Fitbit API that must be met. First, I’ll need to register an application with Fitbit. Second, I’ll need to make sure the connector uses OAuth 2.0 authorization to the Fitbit API. After this is in place, I can expose the operations on the connector as actions that can be added to a Flow or Logic App. This should make it really easy to build out different scenarios around integrating with Fitbit.</p>

<h2 id="registering-my-application">Registering my application</h2>

<p>Registration with Fitbit was very easy. As a registered Fitbit user, I can use my standard (free) account to register and maintain my application. Register new applications <a href="https://dev.fitbit.com/apps/new">here</a> by filling out the form:</p>

<p class="notice--warning">Note: Original image with caption ‘Application registration form’ no longer available.</p>

<p>Note that I’m just creating this application for Personal use, so both the authorization code and implicit grant OAuth 2.0 flows are options for authorization. I also included a Callback URL, but don’t worry if you don’t have one yet – you can edit this later after we have the correct one from the Flow application. Finally, make sure you request Read and Write access since this connector could be used in both scenarios.</p>

<p>After registration, you’ll see some important details:</p>

<p class="notice--warning">Note: Original image with caption ‘Application registration details’ no longer available.</p>

<p>Keep these details handy, because you’ll need them when we create the connector. The Client ID and Secret will be used by the Flow Connector to authenticate, and the URI details will also be needed so that the identity provider (Fitbit) can be setup correctly.</p>

<h2 id="creating-the-custom-connector">Creating the custom connector</h2>

<p>Because Fitbit exposes an <a href="https://dev.fitbit.com/reference/web-api/explore/">OpenAPI specification</a>, this step should be pretty simple. The specification will provide the connector with all the information it needs to build out the actions based on the operations defined. There were several validation errors that didn’t allow me to directly import from URL, so I downloaded the specification locally and edited it until it validated successfully. This doesn’t change the Fitbit Web API nor what it exposes – it was just updates to the metadata around the naming of operations. Let’s see it work!</p>

<p class="notice--warning">Note: This section originally included images at every step. Those are no longer available.</p>

<ol>
  <li>First, go to <a href="https://flow.microsoft.com/">Flow</a>. Click on the settings gear to select that you want to go to custom connectors. Once there, choose to Import an OpenAPI file to create the custom connector. Select the file to upload and continue.</li>
  <li>The first part of the setup handles General settings. You can add a custom icon and color, and describe the connector. Most importantly, it defines the Host for the API. This information will be populated from the Open API specification, but you can also edit and adjust here.</li>
  <li>The next section of the setup, Security, is where that information from the Fitbit application registration will be used. Again most of it is defined in the OpenAPI specification, but you’ll need to add your Client ID and Secret here. Note that the Callback URL will be generated after saving the connector, so we’ll have to come back here to get that value as we will need to update it in the Fitbit application registration as well.</li>
  <li>The OpenAPI specification has 97 operations, and they’re all loaded super easily. There does seem to be an issue though. The specification did not validate because the operation IDs were not unique across all operations. In removing the operation ID, it still brings in the operations, but they will all need to have a unique Operation ID added. I could’ve done this through the specification file and reloaded, but it is very easy to just add a unique name on each action through the Flow UI.</li>
  <li>After adding a unique Operation ID to every connector action, you should be clear of all errors and good to save.</li>
  <li>The next and final step to ensure your connector is ready is to Test. The first thing you’ll need to do is create a New Connection. Click the button. It will use the security settings to go to Fitbit to authorize. But there’s an issue. The redirect_url is invalid. Remember in the security step that the Redirect URL doesn’t get generated until after save? Go back to the Security step and copy the Redirect URL to update the Fitbit application registration’s Callback URL field.</li>
  <li>After updating the Fitbit application registration settings with the correct Callback URL, test again. This time, you should see that everything is wired correctly. I’m already logged into Fitbit, so I’m getting asked to allow this registered application (Flow Connector) access to my account’s Fitbit information. If I click Allow, the connection information (the bearer token returned from Fitbit) will be saved so that I can test the actions.</li>
  <li>Select any action to test. In this example I tested the GetDevices action. As you can see, Fitbit responded successfully with the payload showing my Alta HR and Aria devices.</li>
  <li>Save your custom connector, and you’re all set to get using it. It should now be visible in your custom connectors list.</li>
</ol>

<h2 id="summary">Summary</h2>

<p>That’s all there is! It’s that easy to integrate an API in your Flow or Logic Apps via a custom connector. At its most simple, you can just import an OpenAPI specification and you’re set. In this example we dealt with the added complexity of requiring OAuth 2.0 to access the API. We registered with the identity provider, setup the security, updated the callback, and tested our imported operations.</p>

<p>With this in place, I should now be able to easily get data into and out of Fitbit. Applying the same approach to other public APIs enables me to create true flows between the systems to keep that data in sync. I should finally be able to have all the data where I want without having to resort to local polling services or other similar approaches.</p>]]></content><author><name>Megan K. Meyer</name><email>mkm@awkward.industries</email></author><category term="Azure Logic Apps" /><category term="Microsoft Azure" /><category term="Microsoft Flow" /><summary type="html"><![CDATA[I love fitness trackers and was excited to get the **Fitbit Alta HR**. However, my enthusiasm diminished upon recalling my previous frustration with Fitbit's lack of integration with my preferred tracking apps. While Fitbit offers some integration with partner apps, it doesn't include the ones I use.]]></summary></entry></feed>