{{announcement.body}}
{{announcement.title}}

Automating IT Operations With Oracle Functions

DZone 's Guide to

Automating IT Operations With Oracle Functions

See how to use Oracle Functions as your FaaS platform. In this tutorial, we'll build an example application and learn how to use Oracle's serverless offering.

· Cloud Zone ·
Free Resource

Oracle Functions is a fully managed, multi-tenant, highly scalable, functions-as-a-service platform. It's built on enterprise-grade Oracle Cloud Infrastructure components and powered by the open source Fn Project serverless platform. Along with Oracle Events, Oracle Functions can deliver powerful capabilities for infrastructure and application automation. Together, they enable services to act automatically based on state changes in infrastructure resources, a common use case for enterprise IT environments.

This post walks through an example of a function that verifies whether a compute instance is tagged correctly when it's provisioned. If the instance isn't tagged properly, the function acts to stop the instance. This practice is common in infrastructure automation; it allows resources to be audited for compliance with internal governance policies as they are created, rather than after.

This function is triggered by the Instance - Launch End event, which the Compute service generates at the completion of instance provisioning, based on whether the instance succeeds or fails.

This example uses Oracle Cloud Infrastructure Search to search for Compute resources with a tag key of costcenter and tag value of 1234.

oracle-cloud

Prerequisites

  • Set up your tenancy for Functions development.

  • Set up the Fn CLI with Oracle Functions.

  • To use and retrieve information about other Oracle Cloud Infrastructure services, include the function in a dynamic group. The following example rule allows functions in a specific compartment to be included in a dynamic group:

    Plain Text
     




    xxxxxxxxxx
    1


     
    1
    ALL {resource.type = 'fnfunc', resource.compartment.id = 'ocid1.compartment.oc1..exampleuniqueID'}


    For more information, see To create a dynamic group.

  • Create or update policies to grant dynamic group access to resources.

    After your dynamic group is created, create a policy that allows the dynamic group to use the instances in the compartment. Your policy should look something like this:

    Plain Text
     




    xxxxxxxxxx
    1


     
    1
    Allow dynamic-group <dynamic-group-name> to use instances in compartment <compartment-name>


    For example:

    Plain Text
     




    xxxxxxxxxx
    1


     
    1
    Allow dynamic-group demo-func-dyn-group to use instances in compartment demo-func-compartment


    For more information, see Policy Syntax.

Create an Application

Use the Oracle Cloud Infrastructure Console to create an application in Oracle Functions.

  • From the navigation menu, select Developer Services, and then select Functions.

    oracle-developer-services-functions
  • Click Create Application and then enter values in the New Application dialog box. If you have previously created VCNs, they are listed, and you can select the appropriate subnet.

    oracle-new-application
  • Open a terminal and create the Python function:

Shell
 




xxxxxxxxxx
1


1
fn init --runtime python stop-untagged-instance
2
 
3
cd stop-untagged-instance


  • In the requirements.txt file, add the following entries:

    Shell
     




    x


    1
    fdk
    2
    oci


    When the Compute service emits the Instance - Launch End event, the JSON looks as follows:

JSON
 




xxxxxxxxxx
1
24


1
{
2
  "eventType" : "com.oraclecloud.computeapi.launchinstance.end",
3
  "cloudEventsVersion" : "0.1",
4
  "eventTypeVersion" : "2.0",
5
  "source" : "ComputeApi",
6
  "eventTime" : "2020-03-04T21:24:16.151Z",
7
  "contentType" : "application/json",
8
  "data" : {
9
    "compartmentId" : "ocid1.compartment.oc1..exampleuniqueID",
10
    "compartmentName" : "sandbox",
11
    "resourceName" : "instance-20200304-1322",
12
    "resourceId" : "ocid1.instance.oc1.iad.exampleuniqueID",
13
    "availabilityDomain" : "QGaa:US-ASHBURN-AD-1",
14
    "additionalDetails" : {
15
      "imageId" : "ocid1.image.oc1.iad.exampleuniqueID",
16
      "shape" : "VM.Standard2.1",
17
      "type" : "CustomerVmi"
18
    }
19
  },
20
  "eventID" : "08a71051-cb5c-490d-8e47-2354cfe503b5",
21
  "extensions" : {
22
    "compartmentId" : "ocid1.compartment.oc1..exampleuniqueID"
23
  }
24
}


The resourceId is the instance identifier (OCID).

Following are some snippets of code from the func.py file:

  • From the JSON body, get the instance ID:
Python
 




xxxxxxxxxx
1


 
1
body = json.loads(data.getvalue())
2
instanceId = body["data"]["resourceId"]


  • Use a signer to authenticate to Oracle Cloud Infrastructure services:
Python
 




xxxxxxxxxx
1


 
1
signer = oci.auth.signers.get_resource_principals_signer()


  • Use Oracle Cloud Infrastructure Search to verify whether the Compute instance is properly tagged:
Python
 




xxxxxxxxxx
1


 
1
search_client = oci.resource_search.ResourceSearchClient(config={}, signer=signer)
2
key="costcenter"
3
value="1234"
4
structured_search = oci.resource_search.models.StructuredSearchDetails(
5
query="query instance resources where ((freeformTags.key != '{}' && freeformTags.value != '{}') && (identifier='{}'))".format(key,value,instanceId),
6
type='Structured',
7
matching_context_type=oci.resource_search.models.SearchDetails.MATCHING_CONTEXT_TYPE_NONE)
8
results = search_client.search_resources(structured_search)
9
 
           


  • If the search finds that the instance was not tagged properly, then stop the instance:
Python
 




xxxxxxxxxx
1
10


 
1
compute_client = oci.core.ComputeClient(config={}, signer=signer)
2
try:
3
  if compute_client.get_instance(instanceId).data.lifecycle_state in ('RUNNING'):
4
  try:
5
      resp = compute_client.instance_action(instanceId,'STOP')
6
  except oci.exceptions.ServiceError as :
7
     print('Action failed. {0}'.format(e), flush=True)
8
    raise
9
  else:
10
   print('The instance {0} was in the incorrect state to stop'.format(instanceId),flush=True)


  • Deploy the function:
Shell
 




xxxxxxxxxx
1


1
fn deploy --app control-instance-app


Create an Events Rule

  1. In the navigation menu of the Console, select Application Integration, and then select Events Service.

    oracle-application-integration
  2. Click Create Rule and enter values in the Edit Rule dialog box.

    In this example, the service name is Compute, the event type is Instance - Launch End, and the action to take is to call the stop-untagged-instance function in the control-instance-app function application.

    oracle-edit-rule

Test the Function

Launch a Compute instance with no tags.

oracle-function-testing

After a few minutes, you should see that the instance has stopped for you to take further action.

oracle-function-testing-2

Conclusion

This post shows an example of how to implement IT compliance rules by using Cloud Events and Functions in Oracle Cloud Infrastructure.

Resources

Topics:
cloud ,faas ,oracle cloud infrastructure ,oracle events ,oracle functions ,serverless ,tutorial

Published at DZone with permission of Raghavendra Prasad . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}