Showing posts with label REST API. Show all posts
Showing posts with label REST API. Show all posts

Wednesday, 1 December 2021

OAC - Using CLI to Automate Starting-Stopping of Instances

A couple of years ago I blogged on how to start and stop Oracle Analytics instances using the REST API. This enabled you to schedule scripts to manage the uptime of your instances so you can save those valuable oracle credits. This worked well for the old Autonomous instances but those scripts no longer work with the newer Gen2 OAC architecture. In this blog I’ll show how to use the Oracle CLI (Command Line Interface) to control your instances. 

The Oracle CLI is very simple to use, requires no coding skills and has the added bonus of being able to manage most of your Oracle Cloud Infrastructure tasks (e.g. managing DBaaS instances or virtual machines etc).

Pre-Requisites

You will require an IAM user account (non-IDCS) in your Oracle tenancy to run the CLI commands. You will need the OCID value for this user:


You also need the OCID value of your Oracle tenancy:


Installing the Oracle CLI on Windows


You can install on either Linux or Windows. I've chosen Windows as it's what most of our customers use. 

I followed the Oracle documentation on how to install CLI on Windows here: https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/cliinstall.htm 

Here is the process in a nutshell:
  • Download a powershell script
  • Run the powershell script. 
    • This will download the Python and install it.
    • It will also download the CLI and install it.

Initially, I installed Python manually but the auto-installer kept failing on the import ssl statement. I ended up deinstalling Python and getting the installation utility to install python for me.
This version of python is older (3.6) than the one I installed (failed with both 3.9 and 3.8).

Here are the commands you need to run:

Start Powershell as an administrator.

Set-ExecutionPolicy RemoteSigned 
(allow the script to run).

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls" 
(enable tls otherwise it won’t be able to download the install files).

Invoke-WebRequest https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.ps1 -OutFile install.ps1
(download the script).


iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.ps1'))
(run the installer with prompts)


Here is the rest of  the input/output:

===> In what directory would you like to place the install? (leave blank to use 'C:\Users\Administrator\lib\oracle-cli')
: E:\oracle-cli
-- Creating directory 'E:\oracle-cli'.
-- We will install at 'E:\oracle-cli'.

===> In what directory would you like to place the 'oci.exe' executable? (leave blank to use 'C:\Users\Administrator\bin
'): E:\oracle-cli\bin
-- Creating directory 'E:\oracle-cli\bin'.
-- The executable will be in 'E:\oracle-cli\bin'.

===> In what directory would you like to place the OCI scripts? (leave blank to use 'C:\Users\Administrator\bin\oci-cli-
scripts'): E:\oracle-cli\scripts
-- Creating directory 'E:\oracle-cli\scripts'.
-- The scripts will be in 'E:\oracle-cli\scripts'.

===> Currently supported optional packages are: ['db (will install cx_Oracle)']
What optional CLI packages would you like to be installed (comma separated names; press enter if you don't need any opti
onal packages)?:
-- The optional packages installed will be ''.
-- Trying to use python3 venv.
-- Executing: ['C:\\Users\\Administrator\\Python\\python.exe', '-m', 'venv', 'E:\\oracle-cli']
-- Executing: ['E:\\oracle-cli\\Scripts\\python.exe', '-m', 'pip', 'install', '--upgrade', 'pip']
Collecting pip
  Downloading https://files.pythonhosted.org/packages/47/ca/f0d790b6e18b3a6f3bd5e80c2ee4edbb5807286c21cdd0862ca933f751dd
/pip-21.1.3-py3-none-any.whl (1.5MB)


There was an error at the end but it seemed to install successfully:


Test the oci.exe by running the oci –version command:



OCI CLI Setup

Run the oci setup config command to configure the OCI CLI. This will prompt you to input your User and Tenancy OCID values. It will also prompt whether you want to create the API RSA key pair which I will do in this example:



Here is the rest of the input/output:

Enter a user OCID:
Enter a user OCID: ocid1.user.oc1..xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Enter a tenancy OCID: ocid1.tenancy.oc1..xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Enter a region by index or name(e.g.
1: ap-chiyoda-1, 2: ap-chuncheon-1, 3: ap-hyderabad-1, 4: ap-melbourne-1, 5: ap-
mumbai-1,
6: ap-osaka-1, 7: ap-seoul-1, 8: ap-sydney-1, 9: ap-tokyo-1, 10: ca-montreal-1,
11: ca-toronto-1, 12: eu-amsterdam-1, 13: eu-frankfurt-1, 14: eu-zurich-1, 15: m
e-dubai-1,
16: me-jeddah-1, 17: sa-santiago-1, 18: sa-saopaulo-1, 19: sa-vinhedo-1, 20: uk-
cardiff-1,
21: uk-gov-cardiff-1, 22: uk-gov-london-1, 23: uk-london-1, 24: us-ashburn-1, 25
: us-gov-ashburn-1,
26: us-gov-chicago-1, 27: us-gov-phoenix-1, 28: us-langley-1, 29: us-luke-1, 30:
 us-phoenix-1,
31: us-sanjose-1): 23
Do you want to generate a new API Signing RSA key pair? (If you decline you will
 be asked to supply the path to an existing key.) [Y/n]: Y
Enter a directory for your keys to be created [C:\Users\Administrator\.oci]: E:\oracle-cli\keys
Enter a name for your key [oci_api_key]: oci_api_key
Public key written to: E:\oracle-cli\keys\oci_api_key_public.pem
Enter a passphrase for your private key (empty for no passphrase):
Private key written to: E:\oracle-cli\keys\oci_api_key.pem
Fingerprint: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
Config written to c:\oracle-cli\bin

    If you haven't already uploaded your API Signing public key through the
    console, follow the instructions on the page linked below in the section
    'How to upload the public key':

        https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#How
2


The keys were generated here:




Note that I got the config location wrong when I ran this first time (C:\oracle-cli\bin instead of E:). I'm not sure if the CLI doesn't let you use another folder than the default one but I had to create the config file in C:\Users\Administrator\.oci\config.

I just copied the contents of the file which got created by the config command earlier and created a new file called config in C:\Users\Administrator\.oci\config. I had to use the cmd mkdir command to create the folder because it starts with a full-stop.

Add the Keys to your IAM User Account

Next we need to associate the public key we created earlier with our IAM user account.

Open the oci_api_key_public.pem file and copy the entire contents (including the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----).

Login to OCI and go to your IAM user account.

In the bottom left of the screen click on API Keys and then Add API Key:



Copy the contents of the public key and paste into the box:



You should then see the fingerprint and the contents which should match the config file you have on the oracle-CLI install:



Stopping and Starting OAC using the CLI Command Line

Finally we get to the nitty gritty!

Once you have configured the Oracle CLI and you have imported the keys to your IAM user account you should be able to use CLI to manage your Oracle Analytics instances (and other OCI services).

To stop OAC using CLI you run this command: 
oci analytics analytics-instance stop --analytics-instance-id <OAC instance ID>


To start OAC you run this command:
oci analytics analytics-instance start --analytics-instance-id <OAC instance ID>



You can see the commands are successful in the OAC activity log:

You can also use the GET command to get the status of the instruction:

oci analytics analytics-instance get --analytics-instance-id <OAC instance ID>


Once it is complete the lifecycle-state changes:



All that remains is to save your script as a batch file and schedule it using the standard Windows scheduler.

Other Oracle CLI Commands

There are other useful commands such as scale which allows you to scale your instance up or down.

You can find all CLI commands in the OCI CLI Command Reference guide here:

Wednesday, 11 September 2019

OAC - Starting and stopping instances using the REST API (Autonomous/Oracle Managed)

We waited a while to be able to start and stop OAC Oracle Managed (autonomous) instances through the OAC console but there isn't a way to schedule the starting and stopping of instances in the console. This is of course very important if you want to keep costs down by automatically shutting down your instances overnight for example.


Thankfully there are now REST API calls available for Oracle Managed OAC instances which allow you to stop and start your instances. You can schedule these commands from a scripting tool of your choice to automate this process e.g. create a batch script and schedule the start/stop using the Windows scheduler.

OAC Start Instance REST API Call

The call to start the instance is a follows:

curl -v -i -X POST -u username:password -H
"Content-Type:application/vnd.com.oracle.oracloud.provisioning.Service+json"
-H "X-ID-TENANT-NAME:idcs-<IDCS-Account-Name>"
"https://psm-cacct-<PSM-Account-Name>.console.oraclecloud.com/paas/api/v1.1/instancemgmt/idcs-<IDCS-Account-Name>/services/AUTOANALYTICSINST/instances/<Instance-Name>/start"

<IDCS-Account-Name>: You can get this by logging into your Oracle MyServices homepage and clicking on the Oracle Identity Cloud Service icon:




Your IDCS account name can be found in the URL of the new tab: 
https://idcs-ef1234567fds1234567df123456.identity.oraclecloud.com/ui/v1/adminconsole


<PSM-Account-Name>: You can get this by logging into your Oracle MyServices homepage and clicking on the Oracle Analytics Cloud icon


Your PSM account name can be found in the URL of the new tab:

https://psm-cacct-ef123456gh123456hi456.console.oraclecloud.com/psmui/faces/paasRunner.jspx?serviceType=AUTOANALYTICSINST

<Instance-Name>: You can find your instance names by clicking on the Oracle Analytics Cloud icon:


Notice in the above screenshot we have both a BI instance and an Essbase instance. These commands can be used to start/stop any of your OAC instances.

So in this example the command would be:

curl -v -i -X POST -u username:password -H
"Content-Type:application/vnd.com.oracle.oracloud.provisioning.Service+json"
-H "X-ID-TENANT-NAME:idcs-ef1234567fds1234567df123456"
"https://psm-cacct-ef123456gh123456hi456.console.oraclecloud.com/paas/api/v1.1/instancemgmt/idcs-ef1234567fds1234567df123456/services/AUTOANALYTICSINST/instances/PrdOBI/start"

Once you have launched the command you will recieve this output if the command is successful:


You should also see the message in the console saying that the startup is in progress:


Everything gets logged in the OAC activity log as you would expect:



OAC Stop Instance REST API Call

The call to start the instance is a follows:

curl -v -i -X POST -u username:password -H
"Content-Type:application/vnd.com.oracle.oracloud.provisioning.Service+json"
-H "X-ID-TENANT-NAME:idcs-<IDCS-Account-Name>"
"https://psm-cacct-<PSM-Account-Name>.console.oraclecloud.com/paas/api/v1.1/instancemgmt/idcs-<IDCS-Account-Name>/services/AUTOANALYTICSINST/instances/<Instance-Name>/stop"


Spare Oracle Credits!

You can now schedule your instances to stop when they are not being used saving you valuable Oracle Universal Credits which you could use to spin up other Oracle cloud services or add more OCPU during heavy usage periods!

Friday, 8 March 2019

OAC - Bulk Importing Users & Groups via IDCS REST API

In my previous post (here) we saw how it's possible to bulk import users using a CSV file. Here we look at how we can automate creating/importing users using the IDCS REST API.

Note: there is a tool called the Identity Bridge Agent which you can install to sync your MSAD users with IDCS with no coding required. However, you will need to subscribe to a paid version of IDCS to use the Identity Bridge Agent. There are 3 versions of IDCS:

  • Foundation: Free with your OACS subscription
  • Basic: Not included with OACS. You need to subscribe to this if you want to use the Bridge Agent. It also includes additional authentication features above Foundation
  • Standard: Same as Basic with even more features
  • Go here for information on IDCS versions
  • Go here for information on the IDCS Bridge Agent and here for a lovely tutorial on how you install it


Okay, back to the IDCS REST API. Here are the links to the Oracle documentation I used. Kudos again to the documentation team!
Make your first REST API call
Managing Users Using REST API Calls

IDCS REST API Pre-Requisites

There are a couple of things we need to do before we make our first REST API calls:


  • Choose a REST API client. I'm using Windows and PowerShell has the ability to make REST API calls. However, I've decided to use CURL as all the Oracle examples use this. You can download it from here. Just unzip the package to use it, there is no install required:


  • Register a Client Application in IDCS to enable connectivity from the REST client.

Registering the REST API Client Application in IDCS

You need to enable connectivity from a client app in the IDCS admin console. By doing this you will get the Client ID and Client Secret which are the equivalent of the user name and password that the REST API will use to login to IDCS.
  • In the IDCS Admin Console go to Application->Add:

  • Select Confidential Application
  • Enter a name for the app. You can have different apps for different purposes. Each app will have it's own unique CLIENT_ID and CLIENT_SECRET combination. Using this logic you could for instance create 3 apps; App1 for managing all the REST API user management, App2 for managing Essbase REST API calls and App3 for managing BI REST API calls. By disabling one of the apps you could  disable all calls from one specific application team if you wished.
  • Click Next
  • Select 'Client Credentials' and 'JWT Assertion' in the Allowed Grant Types:
The grant types define how the IDCS handles authorisation:
Client Credentials - This will generate our Client ID and Client Secret
JWT Assertion - this enables the REST client to connect using a JSON web token (JWT)

  • On the Client page, scroll down to the Grant the client access to Identity Cloud Service Admin APIs. section, and click Add

  • In the Add App Role dialog box, select the type of access your REST API account needs. We are doing high-level security tasks so we will select Identity Domain Administrator, and then click Add:
  • Now keep clicking next and Finish

After you click Finish you will see a pop-up box containing your Client ID (think username) and Client Secret (think password). Note this down safely to use when you start making REST API calls.

  • Finally click Activate to enable the application:


Running Your First IDCS REST API Call

To keep things nice and simple for my old brain I'm going to use the Windows command tool to launch our REST calls.

The first call we need to make is effectively the login. The login will create an access token for us and we will use this access token in subsequent commands.


Login to IDCS Using REST

curl -k -X POST -u "CLIENT_ID:CLIENT_SECRET" -d "grant_type=client_credentials&scope=urn:opc:idm:__myscopes__" "IDCS_URL/oauth2/v1/token" -o access_token.json

I've highlighted in bold the parts of the command we need to modify namely:

  • CLIENT_ID: This is what we generated when we created our IDCS client app earlier.
  • CLIENT_SECRET: Same as above.
  • IDCS_URL: This is the URL to our IDCS instance. You can get this by copying it from the URL of your IDCS console. The URL will look something like this:
https://idcs-<WHOLE_BUNCH_OF_RANDOM_CHARACTERS>.identity.oraclecloud.com
  • access_token.json: This is the file which will contain the output of the REST API call. It will contain the token we need to run subsequent calls to IDCS. It looks something like this:

{
"access_token":"<ENORMOUS_STRING_OF_RANDOM_CHARACTERS>",
"token_type":"Bearer",
"expires_in":3600
}

Here is what it looks like in the windows command window:


If your REST call is unsuccessful for whatever reason you will see an HTML error message in your access_token.json file:



Creating an IDCS User Using REST (equivalent to manual user creation)

This was the first example I found for adding a user and it worked but it did not end up being my preferred solution. The preferred solution was to use the bulk user CSV upload (scroll further down this blog) as this was more user friendly but I'm adding the non-bulk method here for completeness.

The CURL command to create a user in IDCS is as follows:

curl -k -v -X POST -H "Content-Type: application/scim+json" -H "Authorization: Bearer ACCESS_TOKEN" "IDCS_URL/admin/v1/Users" -d "@FILE_NAME" -o user_output.json

Note the double quotes around the FILE_NAME. The Oracle documentation uses single quotes but this causes an error, double quotes are required when using Windows.

The FILE_NAME is a file containing the user information in JSON format or the JSON payload:

{
  "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
  "userName": "john.smith@brewery.com",
  "name": {
    "familyName": "Smith",
    "givenName": "John",
  },
  "emails": [{
    "value": "john.smith@brewery.com",
    "type": "work",
    "primary": true
  }]
}

Example:

curl -k -v -X POST -H "Content-Type: application/scim+json" -H "Authorization: Bearer ENORMOUS_STRING_OF_CHARACTERS" "https://idcs-db123456789.identity.oraclecloud.com/admin/v1/Users" -d "@users.json" -o user_output.json



You can add as many users in the payload as you wish. The user_output.json file will contain any errors that may have occurred during your import. You would need to add a mechanism to catch any errors and alert the end users. One drawback of this solution is these loads to not appear as a job in the IDCS admin console  and whilst there are many ways to create JSON formatted files the format is not nice for end users.


IDCS Bulk CSV User Import Using the REST API

This was my preferred solution for this particular customer. They already had an on-prem SQL database regularly updated from MS Active Directory with new users so we could use this as our source to create our Users.CSV file. This method also uses a IDCS job to import the users so all success/failure logging appears in the IDCS console. It makes it a more integrated solution and more user friendly for the administrators.

The steps we need to go through for the CSV import are documented here

  1. Login to IDCS
  2. Upload the CSV file to the IDCS storage area
  3. Schedule a IDCS user import job (to run immediately)
  4. Check the status of the job

We've seen the command to login and get our access token earlier in this blog.

Upload a File to IDCS Using REST

This is the CURL command to upload our CSV file:

curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Bearer ACCESS_TOKEN" -H "Cache-Control: no-cache" -F "fileName=FILE_NAME" -F "contentType=text/csv" -F "isPublic=false" -F file=@"FILE" "IDCS_URL/storage/v1/Files" -o file_output.json


  • FILE_NAME: This is the name you give to the file when it is uploaded to the IDCS storage
  • FILE: This is the local file name for your Users.CSV file
  • file_output.json: This will contain the output of the command in JSON format. This output will contain the IDCS storage location of our uploaded file. We will need this to schedule the IDCS job

Example:

curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Bearer ENORMOUS_STRING_OF_CHARACTERS" -H "Cache-Control: no-cache" -F "fileName=users.csv" -F "contentType=text/csv" -F "isPublic=false" -F file=@"users.csv" "https://idcs-db123456789.identity.oraclecloud.com/storage/v1/Files" -o file_output.json


This is what the file_output.json looks like:

{"fileName":"files/12345678987654321/users.csv",
"isPublic":false,
"fileUrl":"https://em3.storage.oraclecloud.com/v1/RANDOM_CHARACTERS/users.csv"}

The fileUrl in bold above is what we need to be able to run the IDCS User import job.


Schedule an IDCS User Import Job using REST

The CURL command to schedule an IDCS job is:

curl -X POST -H "Content-Type: application/scim+json" -H "Authorization: Bearer ACCESS_TOKEN" -H
"Cache-Control: no-cache" -d '{
   "schemas": [
     "urn:ietf:params:scim:schemas:oracle:idcs:JobSchedule"
   ],
  "jobType": "UserImport",
   "runNow": true,
   "parameters": [
    {
      "name": "fileLocation",
      "value": "files/201608261841/UsersImp1.csv"
     },
    {
       "name": "fileType",
       "value": "csv"
     }
   ]
 }' "https://IDCS_URL/job/v1/JobSchedules"

The JSON payload in the command defines our scheduled job and is self explanatory. The job type is to UserImport, we want it to run immediately, the fileLocation is the fileName we captured in our previous upload command, the fileType is CSV.

In order to get the windows command line to read the payload on one line we need to do some escaping of the characters. This is what the command actually looks like in the command prompt (apologies, it looks awful!):

curl -X POST -H "Content-Type: application/scim+json" -H "Authorization: Bearer ENORMOUS_STRING_OF_CHARACTERS" -H "Cache-Control: no-cache" -d "{\"schemas\": [\"urn:ietf:params:scim:schemas:oracle:idcs:JobSchedule\"], \"jobType\": \"UserImport\", \"runNow\": true, \"parameters\": [{ \"name\": \"fileLocation\", \"value\": \"files/12345678987654321/users.csv\"}, {\"name\": \"fileType\", \"value\": \"csv\"}]}" https://idcs-db123456789.identity.oraclecloud.com/job/v1/JobSchedules -o schedule_output.json

If the command is successful you will see the job in the IDCS job console:




The output to the JobSchedules command gives you the Job ID which you can use to check the job status. Here is the output of the schedule_output.json:

{"id":"95b78969-58f2-4efg-p0ac-16ae6702f8e0",
"isDisabled":false,
"jobType":"UserImport",
"nextFireTime":"2019-02-28T15:20:15.280Z",
"runAt":"2019-02-28T15:20:15.280Z",
"parameters":[
{"name":"fileLocation",
"value":"files/12345678987654321/users.csv"},
{"name":"fileType","value":"csv"}],
"schemas":["urn:ietf:params:scim:schemas:oracle:idcs:JobSchedule"],
"meta":{"resourceType":"JobSchedule",
"location":"https://IDCS_URL/job/v1/JobSchedules"}
}


The Oracle documentation is very good but there are some parts where the quotes aren't quite correct or the syntax differs slightly in Windows. Hopefully this blog might help others out there looking for a quick start to dip their toes into IDCS and the REST API.