5 min,  azure

5 min Azure Functions compute

Free 1,000,000 requests per month,Process events with a serverless code architecture.
Functions lets you execute your code in a serverless environment without having to first create a VM or publish a web application and write less code, maintain less infrastructure, and save cost.

https://docs.microsoft.com/en-us/azure/azure-functions/functions-overview

Implement endpoint for wep app with, HTTP trigger
Run code when a file is uploaded, blob storage
Series of functions, durable functions
Run logic whe doc is created/updated, Cosmos db
[…]

https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Cpython%2Cportal%2Cbash%2Ckeda

Developing functions on your local computer and publishing them to Azure using Core Tools follows these basic steps:

Install the Core Tools and dependencies.
Create a function app project from a language-specific template.
Register trigger and binding extensions.
Define Storage and other connections.
Create a function from a trigger and language-specific template.
Run the function locally.
Publish the project to Azure.

Let’s create the function app in Azure

The basic tab lets you select a name, code or docker, runtime stack, version and more.

Hosting overview of plans

  • Consumption plan, scale automatically and pay for compute when functions are running
  • Premium plan (if need to run continuously, need more cpu/mem then consumption plan, and more)
  • Dedicated plan (best for long-running scenarios, you have a VM you can use that is underutilized, predictive cost/scale.)

Operating system, we will select Linux and consumption (serverless) for plan type, we will exclude monitoring for now.

Before we create the function we can use the Resource visualizer:

Hm, editing functions in Azure portal is not supported for Linux consumption function apps, args.

How to Azure functions with VSC

A bit more then 5 min, just follow the same link.

1 Download Azure Functions Core Tools and install it

2 Init function project

Open a terminal in VSC in your project folder (which is empty, just create a folder)

func init myfunctionproject

I selected Python with enter after arrow down,result:

$ func init myfunctionproject
Use the up/down arrow keys to select a worker runtime:python
Found Python version 3.8.3 (py).
Writing requirements.txt
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\giti2021\codehelloworldnorway\myfunctionproject\.vscode\extensions.json

3 Extension

Bundle was present, great

4 Connection string

Get your storage connection strings, storage account, select Access keys in Settings, then copy one of the Connection string values from the storage account we got in Azure when we made the function in the portal. If you need, you now know where it is.

5 Create a function

Run

$ func new
Use the up/down arrow keys to select a worker runtime:python
Found Python version 3.8.3 (py).
Writing requirements.txt
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\giti2021\codehelloworldnorway\.vscode\extensions.json
Use the up/down arrow keys to select a template:
Azure Blob Storage trigger
Azure Cosmos DB trigger   
Durable Functions activity
Durable Functions entity
Durable Functions HTTP starter
Durable Functions orchestrator
Azure Event Grid trigger
Azure Event Hub trigger
HTTP trigger
Kafka output
Kafka trigger
Azure Queue Storage trigger
RabbitMQ trigger
Azure Service Bus Queue trigger
Azure Service Bus Topic trigger
Timer trigger

Result after selecting Python, HTTP trigger and testhttp as name

$ func new
Use the up/down arrow keys to select a worker runtime:python
Found Python version 3.8.3 (py).
Writing requirements.txt
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\giti2021\codehelloworldnorway\.vscode\extensions.json
Use the up/down arrow keys to select a template:HTTP trigger
Function name: [HttpTrigger] testhttp
Writing C:\giti2021\codehelloworldnorway\testhttp\__init__.py
Writing C:\giti2021\codehelloworldnorway\testhttp\function.json
The function "testhttp" was created successfully from the "HTTP trigger" template.

6 Run the function

Run the function from the root directory of the project.

The __init__.py was auto generated from the step above, a free function

func start

Args, and error:

ImportError: cannot import name ‘cygrpc’ from ‘grpc.cython’ (C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\grpc_cython__init_.py)

PS C:\Users\admin> py -c 'import platform; print(platform.architecture()[0])'
32bit
PS C:\Users\admin> python --version
Python 3.8.3

Get Python 3.8.10 – May 3, 2021, Download Windows installer (64-bit)

Hm, 32 vs 64 bit….

Installed 3.8.10 64 bit and uninstalled 3.8.3 32 bit

PS C:\Users\admin> py -c 'import platform; print(platform.architecture()[0])'
64bit
PS C:\Users\admin>

Ok, done and now it works.

Now we can visit the url

The default Python function

import logging

import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

7 Visit URL

http://localhost:7071/api/testhttp

And the result with parameter

http://localhost:7071/api/testhttp?name=Azure%20Rocks%20Espen

8 Alter function

Add some code and func start if it does not auto refresh, but it should.

GIT Bash and curl

Or you can use git bash with curl

GET request


curl --get http://localhost:7071/api/testhttp

curl --get http://localhost:7071/api/testhttp?name=Azure%20Rocks

curl --request POST http://localhost:7071/api/testhttp --data '{"name":"Azure Rocks"}'

9 Publish project to Azure

Next up, Publish, You must have the Azure CLI or Azure PowerShell installed locally to be able to publish to Azure from Core Tools.

We will now use the function app we created above from the portal.

(yesterday I rm’ed the function app, and when I made the same again in Azure portal, the name was misspelled; helloworldnorway became hellowordlnorway. I usally rm everything i build except for some of rg’s and vnet’s I frequently use. Just a habit, keep the possible cost down.)

To publish your local code to a function app in Azure, use the publish command, but first navigate into the project and login to azure.

func azure functionapp publish <FunctionAppName>

$ az login

# If that does not work, go to Portal.azure.com > Azure Active Directory > Properties and you will see the tenant id, cp it

# az login --tenant The-tenant-id-we-copied

$ func azure functionapp publish hellowordlnorway

The rest of the result

[...]
Uploading built content /home/site/artifacts/functionappartifact.squashfs for linux consumption function app...
Resetting all workers for hellowordlnorway.azurewebsites.net
Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in hellowordlnorway:
    testhttp - [httpTrigger]
        Invoke url: https://hellowordlnorway.azurewebsites.net/api/testhttp?code=here-is-appkey-this-is-not-a-goodway==

Let’s test with curl, great! It works in Azure, we can now use the app.

Les’s alter the function and try to redeploy to Azure. We added this to the function in VSC in Python:

", and an update to push to Azure" 

Test it

func start

Deploy it, stop it with ctrl+c

func azure functionapp publish hellowordlnorway

Great work, it took the update and restarted the service in Azure.

let’s have a quick look in Azure, since we have just used VSC. Go and visit the function app.

Paste the URL in a browser.

Securing Azure Functions


https://hellowordlnorway.azurewebsites.net/api/testhttp?code=here-is-appkey-this-is-not-a-goodway==

There are two ways for providing the appkey when calling the function:
query parameter code=here-is-appkey-this-is-not-a-goodway==
If you have the possibility in the client calling the function, a better solution is to include the key in the x-functions-key HTTP request header.
Create an app key for each client, then we get essential API key functionality, and we can identify clients.
Might also add user authentication.

https://blog.bredvid.no/patterns-for-securing-your-azure-functions-2fef634f4020

What does it cost?

https://docs.microsoft.com/en-us/azure/azure-functions/pricing

https://azure.microsoft.com/nb-no/pricing/details/functions/

Comments Off on 5 min Azure Functions compute