# Technical Solutions

Integration notes and learned experiences


# Automating Microsoft Entra Employee Provisioning with Mimecast Email Gateway

Well-run technical organizations need to automate IAM access provisioning in order to quickly and securely onboard and off-board employees or contractors. This is often easier said than done.

**System Components:**\
\
Mimecast provides web email filtering gateways and services for many companies. \
Microsoft Entra (Azure AD) is Microsoft's online identity service for Azure and Office 365. <br>

**Automation Flow:**\
\
A company wants to create new users in the Microsoft365 admin portal and fill out relevant AD metadata during the onboarding process. Afterwards, the user should be automatically added to Entra dynamic groups based on his or her department, job title, physical location, and other relevant attributes. User licenses should be assigned and baseline access should be granted automatically to the greatest extent possible. \
\
\
**Technical Issue Description:**\
\
The company utilizes Microsoft365 for its email system, but also has a Mimecast email gateway filter in place which filters incoming external messages before they can be delivered to employees. The Mimecast filter is connected to the directory and automatically syncs user lists 3x a day, in the US Central Timezone. The sync times are not configurable. The issue is that new users can be created at any time of day because the company has offices all over the world. Sometimes onboardings need to happen on the same day.&#x20;

Unfortunately, the Mimecast gateway only syncs to the Entra AD 3x each day (8am-11am, 1pm-4pm, & 12am-3am) in US central time only, and this cannot be modified. This is suboptimal as it leaves new international users waiting many hours before a sync takes place. During this interval, internal company emails can be delivered but any external source emails are rejected.&#x20;

To make matters worse, the automated IT provisioning process causes emails to be sent to the new user address within the first several minutes of account generation, all of which bounce back as undeliverable. The sending parties add the new user's email to their 'do not send' suppression lists, which prevents the IT department helpdesk from successfully resending the invites. \
\
The filter issue has caused so many problems that an iT staff member needs to manually login and run the filter sync as part of every onboarding process. The vendor also suggests manually provisioning the services which are leading to onboarding emails that are then suppressed, including Cisco Duo, Mimecast, Slack, Salesforce, and other relevant IT services. This could all be avoided if the Mimecast filter could sync more often... However, Mimecast does not allow it. They sync 3x a day in fixed windows and the company has no choice in the matter. If the IT department wants to run an out of bound sync to the directory, they need to manually login to the web filter admin console and click through several menus to run a manual directory sync. They also much do so before the automated provisioning sends the emails that get suppressed, which happens very quickly. Since this is difficult to do, they have given up on fully automating their onboarding process.&#x20;

**Solution:**\
\
Mimecast has an API. We can call the API to run the execute sync operation defined here:<https://integrations.mimecast.com/documentation/endpoint-reference/directory-sync/execute-sync/>\
\
We just need to figure out how to call the API endpoint we need programmatically whenever an onboarding event is taking place. To do this easily and keep it within the Microsoft Entra environment, I configured an Entra dynamic security group to use as a trigger for the automation. The dynamic group query ensures that all active users in the domain with an email license assigned will be added to the group.&#x20;

Two additional pieces must be configured in Azure:

1. We need to create an [Azure Logic App](https://azure.microsoft.com/en-us/products/logic-apps/). \
   The logic app will be triggered whenever a new user is added to the Azure AD group of licensed users. Whenever a new user is added to an Entra dynamic group, we can trigger an action from it. \
   I configured the logic app to check the group membership for new employees every 5 minutes. You can use the drag-and-drop logic app designer with the prebuilt 'Office 365: when a group member is added or removed'  module for this part of the process:\
   \
   &#x20;![](https://359961788-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8sD0yqyCvG9Cvige5Pw3%2Fuploads%2F1IQHSCDdteBPRHEs7Hp4%2FScreenshot%202024-08-01%20at%2011.06.58%20PM.png?alt=media\&token=4dbb7702-7856-4ef9-a140-09fcebb2a431)<br>
2. We also need to create an [Azure Python Function](https://azure.microsoft.com/en-us/products/functions/) which can actually call the Mimecast API and trigger a sync operation whenever it is invoked. <br>

   Any time the Azure function is triggered, it will make a call to the Mimecast API endpoint for the company and trigger a full directory sync immediately. This functionality is equivalent to a human clicking the button in the admin portal manually and happens as soon as the Logic App runs.&#x20;

Here is the code I used in the Azure Functions application for this solution; you will need to provide your API credentials for Mimecast in the `# Setup required variables` section.&#x20;

```
import logging
import azure.functions as func
import base64
import hashlib
import hmac
import uuid
import datetime
import requests

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

    # Setup required variables
    base_url = "https://xx-api.mimecast.com"
    uri = "/api/directory/execute-sync"
    url = base_url + uri
    access_key = "YOUR ACCESS KEY"
    secret_key = "YOUR SECRET KEY"
    app_id = "YOUR APPLICATION ID"
    app_key = "YOUR APPLICATION KEY"

    # Generate request header values
    request_id = str(uuid.uuid4())
    hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

    # DataToSign is used in hmac_sha1
    dataToSign = ':'.join([hdr_date, request_id, uri, app_key])

    # Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
    hmac_sha1 = hmac.new(base64.b64decode(secret_key), dataToSign.encode(), digestmod=hashlib.sha1).digest()

    # Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
    sig = base64.b64encode(hmac_sha1).rstrip()

    # Create request headers
    headers = {
        'Authorization': 'MC ' + access_key + ':' + sig.decode(),
        'x-mc-app-id': app_id,
        'x-mc-date': hdr_date,
        'x-mc-req-id': request_id,
        'Content-Type': 'application/json'
    }

    payload = {
        'data': [
            # Populate this with necessary data for the directory sync if required? Not clear if any payload needed: 
            # https://integrations.mimecast.com/documentation/endpoint-reference/directory-sync/execute-sync/
        ]
    }

    response = requests.post(url=url, headers=headers, json=payload)

    if response.status_code == 200:
        return func.HttpResponse("Directory sync executed successfully.", status_code=200)
    else:
        return func.HttpResponse(f"Failed to execute directory sync: {response.text}", status_code=response.status_code)
```

**Results:**

The company's baseline onboarding process now completes automatically within 30 minutes after a new user is setup in the Microsoft Admin portal. A variety of SCIM provisioning, base policy access, and dynamic group triggers like this have freed up the company's IT department to handle bigger and more complex problems without spinning their wheels with basic account provisioning tasks.  \
\
\
**Closing Notes:**\
\
Panorbital's Microsoft-certified experts can help you build complex technical integrations that solve real business problems. We handle integration problems big and small. Give us a call (888 850 9585) or  send an inquiry email (<info@panorbital.com>) if you're interested in working together.&#x20;


# Generating Heroku App Inventory Lists (CSV) using Python/Pandas

Many businesses need to leave PAAS vendors like Heroku after a while. It's nice to have a list of all the moving parts as part of any migration plan. Here's a quick script to generate one:

When migrating thousands of containers across dozens of teams to Kubernetes or Dockerized environments, it can really help to have an inventory list which describes all the running services on all slugs in the ecosystem. \
\
\
Here's a python script that will do just that:

```
import requests

import pandas as pd

import csv

 

API_KEY = 'HRKU-API-Token' #get a token from your user profile settings

team_ids = ['dev-test-team’, ‘any-number-of-teams-here-comma-separated’]

 

all_apps_data = []

headers = {

    "Accept": "application/vnd.heroku+json; version=3",

    "Authorization": f"Bearer {API_KEY}",

}

 

# Loop through each team ID and fetch config data

for team_id in team_ids:

    response = requests.get(f'https://api.heroku.com/teams/{team_id}/apps', headers=headers)

    apps = response.json()

    for app in apps:

        app_id = app['id']

        response = requests.get(f'https://api.heroku.com/apps/{app_id}/dynos', headers=headers)

        dynos = response.json()

        response = requests.get(f'https://api.heroku.com/apps/{app_id}/addons', headers=headers)

        addons = response.json()

        for dyno in dynos:

            dyno_data = {

                'app_id': app_id,

                'app_name': app['name'],

                'dyno_id': dyno['id'],

                'dyno_size': dyno['size'],

                'dyno_type': dyno['type'],

                'addons': ', '.join([f"{addon['name']} ({addon['plan']['name']})" for addon in addons]),

            }

            all_apps_data.append(dyno_data)

 

#organize data

df = pd.DataFrame(all_apps_data)

df.to_csv('heroku_apps_data.csv', index=False)
```

Output is in this format (CSV): <br>

| app\_id | app\_name | dyno\_id   | dyno\_size | dyno\_type  | addons                                                                                    |
| ------- | --------- | ---------- | ---------- | ----------- | ----------------------------------------------------------------------------------------- |
| UUID    | Name01    | dyno\_UUID | Basic      | proc\_name0 | postgresql-metric-NUM (heroku-postgresql:PLAN), redis-silhouetted-NUM (heroku-redis:PLAN) |
| UUID    | Name01    | dyno\_UUID | Basic      | web         | postgresql-metric-NUM (heroku-postgresql:PLAN), redis-silhouetted-NUM (heroku-redis:PLAN) |
| UUID    | Name02    | dyno\_UUID | Basic      | web         | postgresql-metric-NUM (heroku-postgresql:PLAN), redis-silhouetted-NUM (heroku-redis:PLAN) |
| UUID    | Name02    | dyno\_UUID | Basic      | proc\_name0 | postgresql-metric-NUM (heroku-postgresql:PLAN), redis-silhouetted-NUM (heroku-redis:PLAN) |

If you're looking to migrate from Heroku into AKS, GKE, EKS, or some other Kubernetes solution, we've got your back. Reach out to talk to our certified experts for your next cloud migration project.&#x20;


# How It Works

Simple, straightforward, high-level explanations you may find helpful


# AWS Cost Management Tools (are not made equal)

Financial optimization tools for AWS are basically a cottage industry these days. These tools all work similarly, but some of them will cost you a lot more than others...

FinOps Tools for Optimizing AWS Reserved Instances and Savings Plans

While AWS provides a robust set of financial optimization tools in-platform, some clients and other organizations find there's more value from using third-party solutions that focus on optimizing AWS Reserved Instances (RIs) and Compute Savings Plans. These tools can dynamically manage  commitments to match your changing capacity needs, often resulting in significant cost savings. Let's take a quick look at some notable third-party tools like Apptio, nOps, and Zesty and see if they make sense:

**Apptio Cloudability**

**Apptio Cloudability** is a comprehensive cloud cost management platform that provides in-depth financial analytics and recommendations. Cloudability offers:

* **Automated Recommendations**: Uses machine learning to analyze usage patterns and recommend the optimal mix of RIs and Savings Plans.
* **RI and SP Portfolio Management**: Helps you manage your portfolio of RIs and Savings Plans, ensuring you are neither overcommitted nor underutilized.
* **Reporting and Alerts**: Provides detailed reports and alerts to help you monitor your commitments and make data-driven decisions.
* This tool is targeted at very large companies. Pricing starts at around $3500/month for the platform. They offer a limited version that is billed on savings model as well. &#x20;

**nOps**

**nOps** is another powerful cloud management tool that focuses on cost optimization, compliance, and security. When it comes to RI and Savings Plan optimization, nOps excels in:

* **Real-Time Analytics**: Offers real-time insights into your AWS usage and costs, helping you identify opportunities for savings.
* **Automated Buy and Sell**: Automatically buys and sells RIs to match your current and projected usage, minimizing waste.
* **Savings Plan Management**: Provides detailed recommendations on purchasing Savings Plans based on your usage patterns and financial goals.
* This tool is targeted at small to mid-sized companies. They bill you based on a 'percentage of savings' model with no set monthly fee.&#x20;

**Zesty**

**Zesty** is an innovative platform that takes a proactive approach to managing AWS costs. It offers unique features for optimizing RIs and Savings Plans, including:

* **Dynamic Scaling**: Automatically adjusts your RI and Savings Plan commitments based on real-time usage, ensuring you always have the right capacity.
* **Cost Savings Insights**: Provides actionable insights and recommendations to help you reduce costs without compromising performance.
* **Risk-Free Management Pledge**: Manages your commitments with minimal risk, ensuring you don't end up with unused or underutilized resources.&#x20;
* This tool is targeted at small to mid-sized companies. They bill you based on a 'percentage of savings' model with no set monthly fee.&#x20;

So these are three of the largest AWS cost management tools out there, but there's plenty of others (like Antimetal, Densify, etc - there's literally dozens of them out there). The important thing to know is that these tools all work the same way and they are selling you a commodity service for different prices with a different interface on it. You should make sure to focus on the one that costs the least amount and saves you the most.&#x20;

Cost is always negotiable for something like this, but there's a lot of obfuscation about what you should be paying when you try to understand how it all works. And that's where Panorbital can help - we are not direct partners with any of these firms so we can tell you what we think. And we think all of this is a waste of money if you know what you're doing. You can do the same thing and realize the same savings these tools do on your own using AWS native tools at a $0 markup. Or you can pay a 15% markup for the same thing. &#x20;

One important thing to realize is that tools like Zesty charge you a percentage of hypothetical savings realized, whether or not those savings were actually realized by Zesty or by you. So if you've bought any Reserved Instances or Savings Plans on your own, implementing Zesty will cost you 15% more than you're already paying on those resources. They charge you the delta of the price you pay and the second list rate even if they're not doing anything. So a tool like this only makes sense for a company that doesn't have an existing cost management program in place.&#x20;

A better alternative for many smaller to mid sized orgs is something like Vantage Autopilot. They charge 5% of realized savings from things they automated, and 0% of savings from things your team did.&#x20;

The cost difference between these tools is really significant. If you choose to use one, understand how it works before signing on.&#x20;


# Tech Tips

Over time, I've built up a variety of elaborate python, bash, and other scripts, so it's deeply annoying when a provider makes major breaking changes to their API or CLI without advanced notice.

See the nested articles for more quick tech tips and useful information.&#x20;


# Reverting Heroku CLI to v8 using Homebrew

Over time, I've built up a variety of elaborate python, bash and other scripts, so it's deeply annoying when a tech provider makes major breaking changes to their API or CLI without advanced notice...

Heroku recently released CLI v9, which breaks all sorts of command syntax and outputs data in different formats and structures. It is a travesty. Our systems updated and things went haywire right away. Looking at hours and hours of work to fix something that should never have broken, we decided  version reversion might be the best path forward to resolve the issues with a variety of handler scripts and functions.&#x20;

Unfortunately, reverting Heroku CLI versions is easier said than done when you installed a package like Heroku CLI on a MacOS system via Homebrew (brew\.sh) initially. It's quite a bit easier on Ubuntu, where you can just use npm. Trying this approach on a mac is an exercise in frustration as well, so I came up with a better solution and wanted to share it with the internet in case anyone else feels similar frustration in the future.&#x20;

if you have a mac that updated to Heroku CLI v9 (or any version with breaking changes), you can revert it to the terminal version 8 with this command:

`brew uninstall Heroku && wget` [`https://raw.githubusercontent.com/heroku/homebrew-brew/3b6ca6a88b49e47a0fd7625eff10a2475ac7e1a4/Formula/heroku.rb`](https://raw.githubusercontent.com/heroku/homebrew-brew/3b6ca6a88b49e47a0fd7625eff10a2475ac7e1a4/Formula/heroku.rb)`&& brew install heroku.rb`&#x20;

Homebrew (the package manager) blocks insecurely linking brew digests, which is why we need to download the file locally to re-install it.&#x20;

The structure of this file is <https://raw.githubusercontent.com/heroku/homebrew-brew/COMMITHASH/Formula/heroku.rb>, in case you need another version in the future.&#x20;


# AWS EKS Extended Support Costs

AWS charges a \*lot\* for extended support. You probably don't need it. Extended support can easily quadruple your bills.

Choosing this extended box:

<figure><img src="https://359961788-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8sD0yqyCvG9Cvige5Pw3%2Fuploads%2FRjOyKH7ok1sC3AKSuuvj%2FScreen%20Shot%202024-08-23%20at%203.27.07%20PM.png?alt=media&amp;token=5db2e3f3-b9a6-462d-8edd-76d1a0dd9104" alt=""><figcaption></figcaption></figure>

can lead to large billing impacts:

<figure><img src="https://359961788-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8sD0yqyCvG9Cvige5Pw3%2Fuploads%2FnQCW5nTUsVhtqmuRFv8H%2FScreen%20Shot%202024-08-23%20at%202.21.35%20PM.png?alt=media&amp;token=31da105e-bd5a-45f0-98db-f60d8a4edcf0" alt=""><figcaption></figcaption></figure>


