API Archives - TEKSpace Blog https://blog.tekspace.io/tag/api/ Tech tutorials for Linux, Kubernetes, PowerShell, and Azure Wed, 30 Aug 2023 15:19:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://blog.tekspace.io/wp-content/uploads/2023/09/cropped-Tekspace-logo-icon-32x32.png API Archives - TEKSpace Blog https://blog.tekspace.io/tag/api/ 32 32 Access Azure REST API using PowerShell https://blog.tekspace.io/access-azure-rest-api-using-powershell/ https://blog.tekspace.io/access-azure-rest-api-using-powershell/#respond Mon, 05 Mar 2018 08:06:49 +0000 https://blog.tekspace.io/index.php/2018/03/05/access-azure-rest-api-using-powershell/ PowerShell can be used as a REST client to access Azure REST APIs. To access Azure REST methods, you will need to have access to subscription with Azure AD App Registration. If you haven’t done Azure AD App registration. You can follow this article here. Make sure you capture client secret key after app is

The post Access Azure REST API using PowerShell appeared first on TEKSpace Blog.

]]>
PowerShell can be used as a REST client to access Azure REST APIs. To access Azure REST methods, you will need to have access to subscription with Azure AD App Registration. If you haven’t done Azure AD App registration. You can follow this article here. Make sure you capture client secret key after app is registered. Once you have tenant id, client id, client secret, and subscription id you can proceed forward with below instructions.

To make life easier, I have checked my PowerShell code on Github. Feel free to download them and modify them to your needs.

In this tutorial, I will go over how to get resource groups from Azure REST API. One of the basic CRUD operations, I will perform.

Create a file called Get-AzureResourceGroup.ps1. Let’s create the required variables. Make sure to fill in the required variables from your Azure subscription.

Variables

# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.

Once you have updated the above required values. Let’s make a first REST call to get access token.

We will use the below URL to make a REST call to get access token.

POST https://login.microsoftonline.com/{tenantId}/oauth2/token

Request Access Token

Add the following code to your PowerShell script after variables.

$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"

$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token

After you have retrieved the access token, we will use that to authorize Azure REST methods.

Get Resource groups

To retrieve all resource groups in Azure. We will use the below URL.

GET https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups?api-version=2017-05-10

Enter below code to Get-AzureResourceGroup.ps1.

# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2017-05-10"

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")

$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers

Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups

The above line of code should return all the resource groups from an Azure subscription.

Below is the full script and output.

# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.

$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"

$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token

# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2017-05-10"

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")

$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers

Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups

Output:

The post Access Azure REST API using PowerShell appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/access-azure-rest-api-using-powershell/feed/ 0
Accessing Azure REST API https://blog.tekspace.io/accessing-azure-rest-api/ https://blog.tekspace.io/accessing-azure-rest-api/#respond Sun, 04 Mar 2018 16:47:35 +0000 https://blog.tekspace.io/index.php/2018/03/04/accessing-azure-rest-api/ If you are looking to automate some or all the task in Azure, you can use Azure REST API. In this tutorial, I will show you how to perform basic task such as Authenticating, Authorizing, getting access token, performing crud actions, and many more. NOTE: You will need to have a Azure subscription and Microsoft

The post Accessing Azure REST API appeared first on TEKSpace Blog.

]]>
If you are looking to automate some or all the task in Azure, you can use Azure REST API. In this tutorial, I will show you how to perform basic task such as Authenticating, Authorizing, getting access token, performing crud actions, and many more.

NOTE: You will need to have a Azure subscription and Microsoft account to perform below actions.

Before we get started, we need to first login to portal.azure.com and register application in Azure Active Directory (Azure AD). Follow below steps to get started.

Register App with Azure AD

What do I mean when I say register app with Azure AD?

In order to access Azure API, or any API’s in Microsoft products, we need to create an App. The app could be called anything. For example, if you have an application that provisions IAAS VM’s in Azure, you can register an App in Azure AD that is called Azure IAAS VM provisioning. You can create as many apps in Azure AD. The app is like a service account to access Azure API. It can have RBAC permissions and can be restricted what it can access. Now that you know what app registration means, let’s go ahead and create an App.

App Registration

After you log in to Azure Portal, click on All services in the top left-hand side.

It will display another window next to the navigation panel. In all services filter, go ahead and type Azure and select Azure Active Directory.

After you click on Azure Active Directoroy, click on App registrations.

Now click on New application registration

In the Create window, fill in the below fields:

Name: {Name your application}
Application Type: {Select Web app / Api or Native}
Sign-on URL: {URL where you can sign in. This can be changed later.}

Now, you might be thinking what option to select in Application Type? This depends on whether your application that will access is a web app or some script that will access Azure API. If you like your users to log in to access Azure resources via the web, you can use Web app / API. For the purpose of this tutorial let’s select web app / api to register app.

After you have defined all the values, click on Create.

Once it has been successfully created, in the App registration window, change the second drop down from my apps to all apps.

Generating Client Secret

After you have successfully created an App. Let’s generate client secret that will be used later to call REST methods.

In New application registration window, after selecting all apps, click on Azure Resource Management. It will take you to new window. In there click on Settings that is on the top and then click on Keys.

In Passwords, fill in the required information. Select Expires in dropdown to define when your key will expire. For the purpose of this tutorial, I will select In 1 year. You can add any string values in Description & Value fields as long as it makes sense to you.

Click on Save.

Once you have saved the key, it will show you randomly generated key in Value field. Store it somewhere securely. We will use that secret key to authenticate later.

Subscription level access to App

In order for you to access resources in Azure subscription. You need to add a recently created app to your subscription. Follow the below steps to grant contributor access to the app.

Go to All Servers -> Subscriptions.

You will be navigated to the Subscription window where you will see all the subscriptions you are part of. If you have more than one subscription, select the subscription you want to grant access to. In my case, I only have one subscription. So I will select that subscription as shown below.

Click on Access Control IAM and then click on Add.

In the Add Permission window, select contributor for role. In the select input box, type the app name you created in Azure AD and select it. In my case, I created Azure Resource Management.

Once you have set the required fields. Click on Save at the bottom.

After you have given successful permission, click on Refresh in your subscription window and you will see your app showing in the list. See below example.

Accessing Azure Resources with Postman

After you have successfully registered an App in Azure AD and given appropriate permissions, let’s go ahead and request access token to access Azure resources.

Request Access Token

To request access token, we need to make a post request at this URL:

POST https://login.microsoftonline.com/{tenant_id}/oauth2/token

You can get the tenant id from Azure Active Directory -> Property -> Directory ID.

Below are the required parameters that needs to be sent in post request.

Parameter Description
grant_typeRequiredThe value must be client_credentials.
client_idRequiredHere the value must be the application id.
You can get the application id from Azure AD from a recently created app.
client_secretRequiredUse the secret key we created from the above tutorial.
resourceRequiredThe value must be https://management.core.windows.net/.

To learn more about the above requirements. Visit the link here.

Using postman to request access token.

In Postman, change the dropdown to POST and next to it enter URL to make the POST request to. Make sure you enter tenant id. Without tenant id request will not work.

In body tab, select x-www-form-urlencoded and enter required fields grant_type, client_id, ‘client_secret’, and resource.

After you have filled in the required information, click on the send button, and you should see a response as shown below.

Now we will use the access token to get resource groups by using below URL.

GET https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups?api-version=2017-05-10

Replace {subscriptionId} with your subscription id. You can get that information from All Services -> Subscriptions.

In postman, enter above URL and change the subscriptionId to your subscription ID. Then go to Headers and in Key field enter Authorization and in Value field enter Bearer {YOUR_ACCESS_TOKEN} and click send. You should receive a response with all the resource groups available in your subscription.

Links used to create this tutorial are as followed:

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-service-to-service#service-to-service-access-token-request

https://docs.microsoft.com/en-us/rest/api/#authorization-code-grant-interactive-clients

https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list

The post Accessing Azure REST API appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/accessing-azure-rest-api/feed/ 0
Kubernetes Services Watch For New Events https://blog.tekspace.io/kubernetes-services-watch-for-new-events/ https://blog.tekspace.io/kubernetes-services-watch-for-new-events/#respond Mon, 12 Feb 2018 01:57:33 +0000 https://blog.tekspace.io/index.php/2018/02/11/kubernetes-services-watch-for-new-events/ Are you one of those who likes to understand how giant cloud providers create load balancer virtual IP address in cloud? If yes, you are in the right place. I will go over how to establish connection to Kubernetes API; and then I will go over how to listen for new changes in Kubernetes watch

The post Kubernetes Services Watch For New Events appeared first on TEKSpace Blog.

]]>
Are you one of those who likes to understand how giant cloud providers create load balancer virtual IP address in cloud? If yes, you are in the right place. I will go over how to establish connection to Kubernetes API; and then I will go over how to listen for new changes in Kubernetes watch API for services and perform action accordingly.

I will be using PowerShell to listen for new changes. You can use any scripting / programing language you like. I chose PowerShell because I would like to manage my Kubernetes Cluster via the Windows system.

Before I get into details, I recommend following this articles on

Understanding Kubernetes API

Kubernetes API provides access to Kubernetes Cluster to manage Pods, Services, and much more. You can get more details from Kubernetes Reference Documentation.. One of the challenge I had was finding right examples on above reference doc from kubernetes site. But I was able to manage to understand how the API worked using Kubernetes Dashboard and using Fiddler to monitor calls made my Kubernetes Dashboard.

If you followed my articles from above. You will see that accessing API via Kubectl proxy makes it much more easier. You can then write your code in any language and make request to proxy URL that already has all the authentication and access mechanism created for you. So you don’t have to add that in your code.

In this tutorial, I will use a proxy URL to make API calls. You can choose any method you like by referring to Kubernetes Documentation.

From your remote machine where you have kubectl and kube config file setup, execute below command to proxy your API requests.

kubectl proxy

The above link will provide you a proxy URL that then you can use in your script to watch for events. You should receive something similar as shown below.

Starting to serve on 127.0.0.1:8001

The default API URL is http://127.0.0.1:8001/api/v1. Depending on when you are reading this blog, the API version may change. You can get the API version from http://127.0.0.1:8001/ and then you can use that in your code.

Now that you know how to access API. Let’s go deep on how make a get request to watch for changes in services API.

Accessing Services API

Services API can be accessed by making a GET request to http://127.0.0.1:8001/api/v1/services. This will give you all the available services as JSON.

There is also a watch API where you can make GET request, which will keep the connection open as long as your proxy is up and running. You can make the request at http://127.0.0.1:8001/api/v1/watch/services. This will return all the events that are created in all the namespaces. If you want to make a get request on a specific namespace, you can use /api/v1/watch/namespaces/{namespace}/services/{name} and change values that are in {}. I will use /api/v1/watch/services to watch for events for all the namespaces and then filter out on what I need.

I have created a repository on Git that contains PowerShell script that will watch for new events. You can download it and make appropriate changes for your environments from here.

The script contains following logic that will run in while loop and perform action accordingly.

#regions HTTP Watch Request
$request = [System.Net.WebRequest]::Create($watch_services_url)
# Get Response
$resp = $request.GetResponse()
# Get Response Stream
$reqstream = $resp.GetResponseStream()
# Create new object for StreamReader
$sr = New-Object System.IO.StreamReader $reqstream
# Create a loop for listening for new events
while (!$sr.EndOfStream)
{
    # Read the line
    $line = $sr.ReadLine();
    # Convert json string to PSObject
    $line_object = $line | ConvertFrom-Json
    # Get Metadata
    $metadata = $line_object.object.metadata
    # Get request type
    $type = $line_object.type

    # Process data returned
    Process-Request -object $line_object
}
# Function
function Process-Request
{
    Param
    (
        [psobject]$object
    )
    $data = $object
    $data = Remove-Old-Events -object $data
    if ($data.type -eq "ADDED")
    {
        # Create Load balancer
        $metadata = Create-LB-Metadata -object $data
        Create-LoadBalancer -object $metadata
    }
    if ($data.type -eq "DELETED")
    {
        # Delete Load balancer
        # Add logic here

    }
    if ($data.type -eq "MODIFIED")
    {
        # Modify Load balancer 
        # Add logic here

    }
}
#endregions

The above while loop example will run until it reaches the end of the stream. The watch request that we made to Kubernetes API, will continuously run and connection will stay open between client and master node for infinitely unless there is a network disconnect or master node is unreachable. You will have to write your own logic to add retry function in case you have lost access to API.

In the script, I left Create-LoadBalancer & Delete-LoadBalancer empty. You can insert your own business logic to create proxy or virtual IP via your external load balancer.

This tutorial is created to understand how API works for watch events and does not go very deep to it. As long as you understand how the integration to API works, you should be able to add your own custom logic depending on your environment.

The post Kubernetes Services Watch For New Events appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/kubernetes-services-watch-for-new-events/feed/ 0