What You’ll Learn

What You’ll Need

Additional Important Points

Look at the ACI administrator below. He is happy and excited. In fact, he is talking to his colleague about what he just discovered. The ACI administrator recently learned how to easily create Python scripts to automate several ACI tasks. Oh, and the best part: The ACI administrator has very little programming experience, and he can still easily create these scripts! Automating all these tasks will save the ACI administrator and his colleague a lot of time.

script

Have you made an API request to the APIC before? The answer is yes if you have previously interacted with the APIC GUI. In ACI, when you perform an action in the APIC GUI, the APIC GUI will send an API message to the APIC’s API to complete your action. Essentially, the APIC sends an API message to itself to complete the action on your behalf.

For example, if you create the “Hello_World” tenant from the APIC GUI, the APIC will send an API message to its own API to create the tenant on your behalf. View the steps in the following image to better understand how API messages are sent in ACI.

script

You can view the API messages sent to the APIC by using a built-in APIC tool called the API Inspector. From the API Inspector, you can view and copy the API messages that are sent to the APIC API.

In the following example, the Hello_World tenant is being created from the APIC GUI. Once you click the Submit button to create the tenant, an API message will be sent to the APIC’s API. You can view the API message sent to create the tenant from the API Inspector.

script

Next, from the API Inspector, you can copy the HTTP method, URL, and payload.

script

You can then take the data that you copied from the API Inspector and paste it into Postman to create your own API request.

script

Finally, you can convert your API request in Postman to Python code.

script

You can then copy the Python code into a Python script. You now have a Python script that can create tenants. No previous Python experience is needed!

script

We created just a tenant, but with anything you do in the APIC GUI, you can easily create a Python script, using the script creation process that I just revealed to you.

script

We will use the API Inspector to create our script, but we first need to obtain Python code that will authenticate us into the APIC.

Before you send an API request from your Python script to the APIC API to create, delete, or query for an object, it is required that you first authenticate into the APIC.

Referencing the following image, the administrator created a script called CreateTenant.py. When the administrator runs the script, the script must first authenticate into the APIC API to receive a token (step 1). Once our script authenticates into the APIC and receives a token, we can then successfully send an API request to the APIC to create the tenant (step 2).

script

I created ACI authentication code that will specifically work with the code that we will generate later in this tutorial.

Let’s create our script and call it CreateTenant.py. Copy and paste the following authentication code into your script:

import requests

url = "https://<YOUR_APIC'S_HOSTNAME>/api/aaaLogin.json"

payload = "{\r\n  \"aaaUser\":{\r\n    \"attributes\":{\r\n      \"name\":\"<YOUR_USERNAME>\",\r\n      \"pwd\":\"<YOUR_PASSWORD>\"\r\n    }\r\n  }\r\n}"
headers = {
  'Content-Type': 'text/plain'
}

response = requests.request("POST", url, headers=headers, data=payload, verify=False)

APIC_cookie = response.cookies['APIC-cookie']

print(APIC_cookie)

In your script you need to fill out your APIC’s hostname, username, and password.

script

For example, I reserved a publicly available APIC sandbox, and I am placing my hostname, username, and password into my script as follows:

script

Save and run your script. (Note that you may receive an InsecureRequestWarning message when running your scripts in this tutorial. The InsecureRequestWarning message is just a warning and can be ignored for the purposes of this tutorial. If you prefer to disable those messages, you can add the code from this blog into your Create_Tenants.py script.)

PS C:\> python .\CreateTenant.py
eyJhbGciOiJSUzI1NiIsImtpZCI6ImNzbW9mOTNid2E0aGNud3NyYTdqdXlha3Nncjd3bWRlIiwidHlwIjoiand0In0.eyJyYmFjIjpbeyJkb21haW4iOiJhbGwiLCJyb2xlc1IiOjAsInJvbGVzVyI6MX1dLCJpc3MiOiJBQ0kgQVBJQyIsInVzZXJuYW1lIjoiYWRtaW4iLCJ1c2VyaWQiOjE1Mzc0LCJ1c2VyZmxhZ3MiOjAsImlhdCI6MTY5NDA4ODk2OCwiZXhwIjoxNjk0MDg5NTY4LCJzZXNzaW9uaWQiOiI1VzdHTzFkN1RKYWNaVUl4amZCK2JnPT0ifQ.ZvAohKiiKx-7Kf5ZsqLWYQ2jnRfJH0pJ-cI8g78TYEfEv3yEgFkUq9Ypmpr6MkGhSpxTmqejG6LfUlNu2KoH14J69d3uZ6hliyDbfbasBEIyI5HMVImHzyvQFXcwKdilCz5q-dakxKwZu8ZAmJ8tguTVUUcYtChuQHLYJuyGZhj40cozaRhpoDS5H7KCiWJeHBHhMvdN_65zlEg-Eut9j58BRhDKC3LTKl0_gvefNc7xkdsIt0mhKEspHkNrpPJ4eKzXO1yVNP4F1Uw6pB45XcnDSFfnzA4vEpxIfddyUXKNJkued41o0IUywNKSYe-WHv74EcWux-HNn2j2e4xlow

When running your script, you should see a long string of alphanumeric characters get printed out. This output confirms that you successfully authenticated into the APIC and received a token.

In line 14, we printed out the token ID when running our script to confirm that we successfully received a token. Now that we have confirmed that our script is able to receive a token, we can delete line 14.

Go ahead and delete line 14 in your script. Save your script, which should look like the following:

script

We will now connect to the APIC GUI, manually create a tenant, and then capture the corresponding API message with the API Inspector. (Please note that the steps in this tutorial are written using screenshots from an APIC running version 6.0. The APIC on the DevNet Sandbox gets upgraded on a recurring basis, so the steps in this tutorial may not match exactly what you see in your APIC GUI.)

Open up a web browser and log in to your APIC.

You might see a “Getting Started” pop-up window when you initially log in to the APIC. Close that window.

Look for the gear icon in the top-right corner of the APIC GUI, and follow these steps to open up the API Inspector:

script

While your API Inspector is running in the background, follow these steps to create the Hello_World tenant:

script

script

After you create your tenant, go back to the API Inspector and uncheck the Log option so that the API Inspector stops logging API messages.

script

From the API Inspector, search for hello_world. Find the method, URL, and payload of the API message sent to create the Hello_World tenant. The method should be POST because it is the HTTP method that is used to create objects. Highlight and copy the method, URL, and payload data to your clipboard.

script

Create a new file called file.json. Paste the text that you copied from the API Inspector into your file.json file.

script

Click 3 to highlight the entire payload in line 3. Right-click the code, and then format the code.

script

The JSON data inside your payload should be more readable now.

script

Now that we have extracted the API call to create the Hello_World tenant from the API Inspector, we can now set up an API request in Postman.

Open Postman. (Please note that depending on which version of Postman you are using, the screenshots in this tutorial might look different from what you see in your own setup. I am using Postman version 10.17.)

Follow these steps to create a new collection:

script

Rename the collection ACI Collection.

script

script

Create a new request called Create Tenant.

script

script

Next, recreate the API message that we copied from the API Inspector in Postman. Go back to your file.json file. Take note of the HTTP method used in our API message.

script

Now that we have confirmed that our API message to create a tenant sent an HTTP POST, set the method in your Postman request to POST.

script

Go back to the file.json file, then copy the URL and paste it into Postman.

script

script

Next, from the file.json file, copy the payload and paste it into Postman.

script

script

We now have our Postman request set up and ready to configure a tenant. Time to click the Send button.

script

Oh no! When you send your API request, you should get a 403 Forbidden error.

script

Why do you think this might be happening?

Below is a clue. It’s an image that we looked at previously in this tutorial.

script

If you answered, “We forgot to authenticate into the APIC API first,” you would be correct!

Next, we will create another API request in Postman so that we can authenticate into the APIC API.

Create a new request in Postman, and name the request Auth.

script

script

Set the HTTP method to POST.

script

Copy and paste the following URL into your Postman request: https://<YourApicIP>/api/aaaLogin.json. Also, make sure to specify the hostname or IP address of your APIC in your URL.

script

Copy and paste the following JSON data into the body of your Postman request:

{
  "aaaUser":{
    "attributes":{
      "name":"<Your_Username>",
      "pwd":"<Your_Password>"
    }
  }
}

script

Make sure to edit the JSON data and add the username and password for your APIC.

script

Now, let’s send our API request to authenticate into the APIC API.

script

If authentication is successful, you will receive a 200 OK message.

script

Now that we have successfully authenticated into the APIC, it is time to resend our other API request to create the Hello_World tenant. Click the Send button.

script

Oops! You should receive a 400 Bad Request error when sending the API request. You are receiving this error because the Hello_World tenant has already been created.

script

Go back to the APIC GUI Tenants tab, then right-click and delete the Hello_World tenant.

script

script

Now that the Hello_World tenant has been deleted, let’s try creating the Hello_World tenant again.

script

If you get a status 200 OK message, that means you successfully created your tenant. (If you get a 403 Forbidden error, that means your authentication token timed out. You will need to resend the authentication API request to obtain a new token, and then you can resend your API request to create the tenant.)

script

Go back to the APIC GUI and confirm that your Hello_World tenant has been created.

script

Nice work! Our API request to create the Hello_World tenant is set up and working in Postman.

Next, we will convert what we did in Postman to usable Python code. First, go back your CreateTenant.py script and add the comment in line 14:

script

Follow these steps to convert your Create Tenant Postman API request to Python code:

script

script

Copy the Python code to your clipboard, and then paste the code into the bottom of your CreateTenants.py script.

script

Your script should look like the following:

script

Delete the code import requests in line 16. (It might be a different line in your script.) We do not need this code because we already imported the requests module in line 1 of our script.

Next, we need to make a couple of tweaks to the CreateTenant.py script to get it to work.

Remember, in the first part of our script, we authenticate into the APIC’s API and receive a token from the APIC. In order for our second API request to work, we will need to update the latter part of our script to ensure that the token ID gets sent in the cookie header.

Let’s delete our header that contains the token ID. Notice that I highlighted four specific lines of code in the following script. Make sure to highlight the same four lines of code (including the curly brace in the fourth highlighted line). Delete those four lines of code.

script

Copy the following code:

headers = {
  'Content-Type': 'text/plain',
  'Cookie': f'APIC-Cookie={APIC_cookie}'
  }

From exactly where you previously deleted the code, paste in the newly copied code into your script.

script

Finally, add verify=False to the end of the line that has the response variable. In my script, it is line 25.

script

Our script should be ready! Go to the CLI and run your script.

PS C:\> python CreateTenant.py
{"totalCount":"1","imdata":[{"error":{"attributes":{"code":"103","text":"Cannot create Tenant (fvTenant); object uni\/tn-Hello_World already exists."}}}]}

You should get a message that the tenant already exists.

Go back to the APIC GUI, and manually delete the Hello_World tenant.

script

script

Let’s try to run our script again.

PS C:\> python CreateTenant.py
{"totalCount":"0","imdata":[]}

It appears that our script ran with no errors.

Let’s see if our Hello_World tenant was created.

script

Congratulations! You now have a script that you can run to easily create tenants. Want to create another tenant?

Let’s create the “Sales” tenant. Go back into your CreateTenant.py script, search for all instances of Hello_World, and replace them with the word Sales.

script

Save and run your script.

PS C:\> python CreateTenant.py
{"totalCount":"0","imdata":[]}

Confirm that you can see the newly created Sales tenant.

script

You can follow the same process to automate almost anything else in ACI. Attempt to accomplish the following two tasks on your own:

Task 1 : Create a Python script to create a virtual routing and forwarding (VRF) instance in the Hello_World tenant.

Task 2: Create a Python script to get interface statistics for leaf 101 interface 1/1. Try to find the place in the APIC GUI where you can obtain ingress and egress byte rates for the interface.

The solution for the tasks will be displayed on the following page.

Task 1 Solution:

I manually created the VRF in the Hello_World tenant. I unselected Create A Bridge Domain because I wanted to create only a VRF instance.

script

I then copied the following API message from the API Inspector:

script

Next, I set up my API request in Postman as follows:

script

Finally, I copied and pasted the authentication code and the code that I created from Postman into the Create_VRF.py script. I also made some tweaks to the script to ensure that the correct token ID was sent in the cookie header (lines 20 to 23 below). I also turned off Secure Sockets Layer (SSL) verification: verify=False (line 25).

script

Task 2 Solution:

Finding leaf 101 interface statistics in the APIC GUI is a little tricky. To manually perform the steps, I went here:

script

I then copied the following API message from the API Inspector. (Note that when sending HTTP GET requests, there is no payload.)

script

Next, I set up my API request in Postman. Notice that when I send my API request, we can see the interface statistics in the response from the APIC’s API at the bottom of the screen.

script

Finally, I copied the authentication code and the code that I created from Postman into the Get_Int_Stats.py script. I also made some tweaks to the script to ensure that the correct token ID was sent in the cookie header. I also turned off SSL verification: verify=False.

script

Nice work! You can now easily create your own Python scripts to automate almost anything in ACI. Also, if you are interested, I teach at Cisco DevNet Automation Bootcamp.

Learn More