Here's the organized list of scripts in Markdown format, categorized by functionality and sorted alphabetically within each category for better readability and structure:

# Descriptions of Scripts in This Repository

## Network Configuration

- **addroutes/addroutes.py:** Script to add static routes to a non-template network from a CSV file.
- **asa_cryptomap_converter/cryptomap_converter.py:** Migrate crypto map-based site-to-site VPN configuration to a Meraki MX security appliance.
- **cloneprovision.py:** Mass-provisions MX security appliances as individually managed networks, without using templates.
- **copymxvlans.py:** Export MX VLAN configuration of a source organization to a file and import it to a destination organization.
- **copynetworks.py:** Copies networks and their base attributes from one organization to another.
- **copyswitchcfg.py:** Export switchport configuration of a source organization to a file and import it to a destination organization.
- **deployappliance.py:** Claims a single Security Appliance or Teleworker Gateway into an organization, creates a new network for it, and binds that network to an existing template.
- **deploycustomer.py:** Automates customer account/organization creation for service providers.
- **deploydevices.py:** Claims multiple devices and licenses into an organization, creates a new network for them, and binds that network to an existing template.
- **migrate_cat3k:** Proof of concept script to migrate switchport configuration from Catalyst 3750-X switches to Meraki MS switches.
- **migratecomware.py:** Migrates legacy switch infrastructure based on Comware to Meraki MS switches.
- **migrate_devices:** Moves devices from one organization to another.
- **migrate_networks:** Copies networks from one organization to another.
- **movedevices.py:** Moves all devices from one organization to another.
- **privateApplicationsImport.py:** Imports Meraki Secure Connect private applications from a CSV file into the Meraki Dashboard.
- **provision_sites:** Provisions template-based networks with manually defined VLAN subnets to the Meraki dashboard.
- **removetemplate.py:** Creates a copy of a template-based network that preserves as many settings as possible without relying on a configuration template.
- **setlocation.py:** Sets the street address and optionally the map marker of all devices in a network or organization.
- **setlocation_legacy.py:** Legacy script to set the street address of all devices in a given network.
- **setssidvlanid.py:** Sets the VLAN ID of SSIDs in 'Layer 3 with concentrator' or 'VPN' mode to a value.
- **setSwitchPortOnMacOui.py:** Sets attributes of a switch port if a client with a matching MAC OUI is found connected to it.
- **tag_all_ports.py:** Tags all MS switch ports in an organization with a user-defined tag.
- **update_ports.py:** Finds MS switchports that match input search parameters and changes their configuration.

## Device Management

- **android_patch_audit:** Checks the date of the last security patch of Android devices managed by Meraki Systems Manager.
- **audit_client_tracking.py:** Checks if the client tracking method in any of a set of networks is set to a required value.
- **auto-cycle-port:** Checks if devices of a particular model are offline and cycles specific switchports in the same network.
- **auto_reboot:** Reboots devices with a matching device tag once a week.
- **autovpn_tunnel_count.py:** Counts how many VPN tunnels are consumed per network for establishing Auto VPN connectivity to peers.
- **clientcount.py:** Counts the total unique client MAC addresses connected to MR access points for an organization during the last month.
- **clients_in_ip_range.py:** Prints a list of all clients in one or more organizations that belong to a specified IPv4 subnet or address range.
- **deviceupdownstatus.py:** Prints a list of all devices in an organization's inventory along with their current up/down status.
- **find_clients.py:** Finds all clients with descriptions, MAC addresses, or IP addresses including a query string and prints their basic statistics.
- **find_ports.py:** Finds all MS switchports that match the input search parameter and applies new access policies.
- **get_license_info.py:** Prints the license info summary for a specific organization or all organizations an admin has access to.
- **inventorycsv.py:** Creates a list of all Meraki devices in one or all organizations accessible by an administrator.
- **invlist.py:** Creates a list of all serial numbers and models of devices that are part of a Meraki network for an organization.
- **latest_devices.py:** Exports CSV of all in-use devices claimed after a specific date.
- **license_counts_csv.py:** Creates a CSV file with aggregated license info for all co-term organizations accessible by an administrator.
- **listip.py:** Prints the "lanIp" of the device if available.
- **manageadmins.py:** Add, delete, find, and list administrators across organizations.
- **merakidevicecounts.py:** Prints total device counts per device family for all organizations accessed by an admin account.
- **merakilicensealert.py:** Sends an email alert if the remaining license time in any org is less than X days or if its license capacity is insufficient.
- **mi_bom_tool.py:** Counts the numbers and sizes of Meraki Insight licenses needed to cover a set of networks in an organization.
- **RadiusCertSurvey:** Surveys managed devices for updated radius.meraki.com certificates.
- **reboot.py:** Reboots devices using a list of serial numbers.
- **set_client_tracking.py:** Sets the client tracking method of a group of networks to a desired value.

## Monitoring and Reporting

- **bssid.py:** Pulls the BSSID of the enabled SSID for all networks in an organization and writes them to a CSV per network.
- **checksubnets.py:** Checks if the LAN IPs of all access points belong to specific IPv4 subnets.
- **CiscoLive/createWebhookTemplate.py:** Creates a custom webhook template.
- **eos_scanner.py:** Scans organizations for devices with announced End of Sales/End of Life dates.
- **getbeacons.py:** Prints a list of all bluetooth beacons in an organization.
- **googletimezonetest.py:** Gets the time zone corresponding to a street address using Google Maps APIs.
- **offline_logging:** Logs data from the Meraki dashboard to a MongoDB database.
- **orgclientscsv.py:** Creates a CSV file with all client devices in an organization.
- **org_subnets.py:** Prints a list of all subnets configured to MX security appliances.
- **postman_collection_generator.py:** Creates a Postman collection for the Meraki Dashboard API v1.
- **remoteAccessLogsAnalyzer.py:** Fetches and analyzes Meraki Secure Connect remote access logs and generates statistics.
- **topusers:** Finds bandwidth hoggers in a network through a web UI.
- **uplink.py:** Exports WAN uplink information to CSV files.
- **usagestats.py:** Produces reports on per user group network usage.
- **usagestats_initconfig.txt:** Example initial configuration file for usagestats.py.
- **usagestats_manual.pdf:** Manual for usagestats.py.

## Utilities

- **firmware_lock/firmware_lock.py:** Locks firmware for devices in an organization to desired builds or release trains.
- **mx_firewall_control/mxfirewallcontrol.py:** Displays, modifies, and creates backups of MX Layer 3 firewall rulesets.
- **mx_firewall_control/mxfirewallcontrol_example_input_file.txt:** Example input file for mxfirewallcontrol.py.
- **nodejs_sdk_builder:** Builds a NodeJS SDK for the Meraki Dashboard API.
- **migration_init_file.txt:** Example init config file for migratecomware.py.

---

Cisco Meraki organizes its networks and devices in a hierarchical structure that provides a clear and scalable way to manage and monitor your network infrastructure. Understanding this hierarchy is essential for effectively using the Meraki Dashboard and API. Here’s a breakdown of the hierarchy:

## Meraki Hierarchy

1. **Organizations**
2. **Networks**
3. **Devices**
4. **Clients**

### 1. Organizations

**Organizations** are the top-level entities in the Meraki ecosystem. An organization can represent a company, a business unit, or a large geographical area. Each organization can contain multiple networks.

- **Key Attributes:**
  - `id`: Unique identifier for the organization.
  - `name`: Name of the organization.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### 2. Networks

**Networks** are collections of devices and configurations that work together to provide network services. Networks can be configured for different purposes such as office locations, retail stores, or different sites within a campus.

- **Key Attributes:**
  - `id`: Unique identifier for the network.
  - `organizationId`: ID of the organization to which the network belongs.
  - `name`: Name of the network.
  - `type`: Type of network (e.g., `wireless`, `switch`, `appliance`, `combined`).

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations/ORGANIZATION_ID/networks" | jq .
```

### 3. Devices

**Devices** are the individual hardware units that make up a network. This includes wireless access points, switches, security appliances, cameras, and other Meraki devices.

- **Key Attributes:**
  - `serial`: Unique serial number of the device.
  - `networkId`: ID of the network to which the device belongs.
  - `model`: Model of the device (e.g., `MX64`, `MR33`).
  - `name`: Name of the device.
  - `mac`: MAC address of the device.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/devices" | jq .
```

### 4. Clients

**Clients** are the end devices that connect to the Meraki network. This can include computers, smartphones, tablets, and IoT devices.

- **Key Attributes:**
  - `id`: Unique identifier for the client.
  - `description`: Description of the client.
  - `mac`: MAC address of the client.
  - `ip`: IP address assigned to the client.
  - `usage`: Data usage statistics for the client.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/clients" | jq .
```

## Practical Usage Example

Here’s how you can traverse this hierarchy using the Meraki Dashboard API:

### Step 1: List Organizations

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### Step 2: List Networks in an Organization

Replace `ORGANIZATION_ID` with the actual ID of your organization.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations/ORGANIZATION_ID/networks" | jq .
```

### Step 3: List Devices in a Network

Replace `NETWORK_ID` with the actual ID of your network.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/devices" | jq .
```

### Step 4: List Clients in a Network

Replace `NETWORK_ID` with the actual ID of your network.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/clients" | jq .
```

## Conclusion

Understanding the hierarchy used by Meraki to organize networks and devices is crucial for effective network management and monitoring. The Meraki Dashboard API provides a powerful way to programmatically interact with your network infrastructure, allowing you to automate tasks, gather data, and perform complex queries.

By practicing with the Meraki Dashboard API and using `jq` to parse and manipulate the JSON data, you can gain deeper insights into your network and improve your overall management capabilities. If you have any further questions or need additional examples, feel free to ask!

---

Great! Let's explore some freely available JSON data sources on the web that you can use to practice `jq`, and then we can touch on how to use the Meraki Dashboard API.

## Free JSON Data Sources

### 1. JSONPlaceholder
JSONPlaceholder is a free online REST API that you can use for testing and prototyping.

**API Endpoint:** `https://jsonplaceholder.typicode.com/`

**Example:** Fetch a list of users

```sh
curl -s https://jsonplaceholder.typicode.com/users | jq .
```

### 2. OpenWeatherMap
OpenWeatherMap provides weather data, and you can get a free API key for accessing their services.

**API Endpoint:** `http://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY`

**Example:** Fetch current weather for London

```sh
curl -s "http://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY" | jq .
```

### 3. The Dog API
The Dog API provides random images and information about dogs.

**API Endpoint:** `https://dog.ceo/api/breeds/list/all`

**Example:** Fetch a list of all dog breeds

```sh
curl -s https://dog.ceo/api/breeds/list/all | jq .
```

### 4. SpaceX API
The SpaceX API provides information about launches, rockets, and other SpaceX-related data.

**API Endpoint:** `https://api.spacexdata.com/v4/launches/latest`

**Example:** Fetch the latest SpaceX launch information

```sh
curl -s https://api.spacexdata.com/v4/launches/latest | jq .
```

## Working with the Meraki Dashboard API

The Meraki Dashboard API provides programmatic access to Cisco Meraki's cloud-managed networking products. To use the Meraki API, you'll need an API key from your Meraki dashboard account.

### Getting Started with the Meraki Dashboard API

1. **Get an API Key:**
   Log in to the Meraki dashboard, navigate to your profile, and generate an API key.

2. **API Endpoint:**
   The base URL for the Meraki API is `https://api.meraki.com/api/v1`.

3. **Example:** Fetch a list of organizations

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### Example Usage of `jq` with the Meraki Dashboard API

#### Fetch a List of Networks in an Organization

1. **Get Organization ID:**
   ```sh
   curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
   ```

2. **Fetch Networks in an Organization:**
   Replace `ORGANIZATION_ID` with the actual organization ID obtained from the previous command.
   ```sh
   curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations/ORGANIZATION_ID/networks" | jq .
   ```

### Practical Exercises with the Meraki Dashboard API

#### 1. List All Devices in a Network

Replace `NETWORK_ID` with the actual network ID.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/devices" | jq .
```

#### 2. Get Device Uplink Status

Replace `SERIAL` with the device serial number.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/devices/SERIAL/uplinks" | jq .
```

### Conclusion

Practicing with freely available JSON data from the web and exploring APIs like the Meraki Dashboard API provides a hands-on approach to learning how to work with `jq`. Use the examples provided to get started, and experiment with different queries and filters to deepen your understanding.

If you have any specific questions or need further assistance, feel free to ask!

---

Sure! Let's review our conversation and integrate all the topics we've covered into a cohesive approach for working with the Meraki Dashboard API. Here's a step-by-step guide that incorporates the key points discussed, focusing on using `curl` and Python for interacting with the API, processing data, and automating tasks.

### Comprehensive Guide to Working with the Meraki Dashboard API

#### 1. Authorization and Setup

Before making any API calls, set up your environment by obtaining your Meraki API key and exporting it for use in `curl` commands.

**Setting Up Authorization:**

```sh
export MERAKI_API_KEY="your_api_key"
```

#### 2. Making API Calls with `curl`

**Find Your Organization ID:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" > organizations.json
```

**List Networks in an Organization:**

Replace `{organizationId}` with your actual organization ID.

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/networks" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/networks" > networks.json
```

**List Devices in an Organization:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/devices" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/devices" > devices.json
```

#### 3. Creating and Managing Action Batches

**Create an Action Batch:**

This example creates an action batch to update a switch port configuration. Replace `{organizationId}` with your organization ID.

```sh
curl -X POST https://api.meraki.com/api/v1/organizations/{organizationId}/actionBatches \
-L \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer $MERAKI_API_KEY' \
-d '{
    "confirmed": true,
    "synchronous": true,
    "actions": [
        {
            "resource": "/devices/QXXX-XXXX-XXXX/switchPorts/3",
            "operation": "update",
            "body": {
                "enabled": true
            }
        }
    ]
}'
```

**List All Action Batches:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/actionBatches" | jq .
```

**Get a Specific Action Batch:**

Replace `{id}` with the actual action batch ID.

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/actionBatches/{id}" | jq .
```

**Delete an Action Batch:**

```sh
curl -X DELETE -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/actionBatches/{id}"
```

#### 4. Automation and Scripting with `curl`

Automate repetitive tasks using shell scripts.

**Automate Data Fetch:**

```sh
#!/bin/bash
# Fetch Meraki data and save to files

API_KEY="your_api_key"
ORGANIZATION_ID="your_organization_id"
BASE_URL="https://api.meraki.com/api/v1"

# Fetch organizations
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations" > organizations.json
echo "Organizations data saved to organizations.json"

# Fetch networks
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/networks" > networks.json
echo "Networks data saved to networks.json"

# Fetch devices
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/devices" > devices.json
echo "Devices data saved to devices.json"

# Fetch uplinks for a specific device
DEVICE_SERIAL="your_device_serial"
curl -s "$BASE_URL/organizations/$ORGANIZATION_ID/devices/uplinks/addresses/byDevice?serials[]=$DEVICE_SERIAL" -H "Authorization: Bearer $API_KEY" > uplinks.json
echo "Uplinks data saved to uplinks.json"
```

#### 5. Data Processing with Python

Use Python for more complex data processing and analysis.

**Loading and Analyzing Data with Python:**

```python
import json

# Load organizations data
with open('organizations.json') as f:
    organizations = json.load(f)

# Load networks data
with open('networks.json') as f:
    networks = json.load(f)

# Load devices data
with open('devices.json') as f:
    devices = json.load(f)

# Load uplinks data
with open('uplinks.json') as f:
    uplinks = json.load(f)

# Example: Print organization names and IDs
for org in organizations:
    print(f"Organization ID: {org['id']}, Name: {org['name']}")

# Example: Find and print offline devices
offline_devices = [device for device in devices if device.get('status') != 'online']
print(f"Number of offline devices: {len(offline_devices)}")
for device in offline_devices:
    print(f"Offline Device: {device['name']} (Serial: {device['serial']})")
```

#### 6. Monitoring and Alerts with `curl`

Set up monitoring and alerts using `curl` in conjunction with shell scripts.

**Monitoring Device Status:**

```sh
#!/bin/bash
# Monitor device status and alert if any device is offline

API_KEY="your_api_key"
ORGANIZATION_ID="your_organization_id"
BASE_URL="https://api.meraki.com/api/v1"
OUTPUT_FILE="device_status.json"

# Fetch devices
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/devices" > $OUTPUT_FILE

# Check device statuses
offline_devices=$(jq '.[] | select(.status != "online")' $OUTPUT_FILE)

if [ -n "$offline_devices" ]; then
  echo "ALERT: Some devices are offline!"
  echo "$offline_devices" | jq '.'
else
  echo "All devices are online."
fi
```

#### 7. Data Analysis and Visualization with Python

**Analyzing Device Data with pandas:**

```python
import pandas as pd
import matplotlib.pyplot as plt

# Load data from file
df = pd.read_json('devices.json')

# Perform analysis
offline_devices = df[df['status'] != 'online']
print(f"Number of offline devices: {len(offline_devices)}")

# Visualize data
df['status'].value_counts().plot(kind='bar')
plt.title('Device Status Distribution')
plt.xlabel('Status')
plt.ylabel('Count')
plt.show()
```

### Global Meraki Path Parameter IDs

Understanding the path parameters and their corresponding API operations helps in navigating the Meraki Dashboard API efficiently. Use the provided table to identify the necessary path parameters and the corresponding endpoints.

### Conclusion

By following this comprehensive guide, you can efficiently interact with the Meraki Dashboard API, automate tasks, monitor network status, and gain insights from your Meraki network data. Using `curl` for API requests and Python for data processing allows you to create robust and scalable solutions for managing your Meraki infrastructure.

If you have any further questions or need additional examples, feel free to ask!

---

### Efficient Workflow with the Meraki API Using `curl` and Python

Let's create an efficient workflow for interacting with the Meraki API, primarily using `curl` and then supplementing with Python where necessary. This approach will focus on fetching, storing, processing, and automating tasks with `curl`, and using Python for more complex data manipulation and analysis.

### 1. Authorization and Setup

Set up your environment with your Meraki API key.

**Example: Setting Up Authorization**

```sh
export MERAKI_API_KEY="your_api_key"
```

### 2. Making API Calls with `curl`

#### Find Your Organization ID

**Request:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" > organizations.json
```

#### List Networks in an Organization

Replace `{organizationId}` with your actual organization ID.

**Request:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/networks" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/networks" > networks.json
```

#### List Devices in an Organization

**Request:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/devices" | jq .
```

**Store the Response:**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations/{organizationId}/devices" > devices.json
```

#### Get Device Uplink Addresses

**Request for One Device:**

Replace `{serial}` with the actual device serial number.

```sh
curl -s "https://api.meraki.com/api/v1/organizations/{organizationId}/devices/uplinks/addresses/byDevice?serials[]={serial}" -H 'Authorization: Bearer $MERAKI_API_KEY' | jq .
```

**Store the Response:**

```sh
curl -s "https://api.meraki.com/api/v1/organizations/{organizationId}/devices/uplinks/addresses/byDevice?serials[]={serial}" -H 'Authorization: Bearer $MERAKI_API_KEY' > uplinks.json
```

### 3. Automation and Scripting with `curl`

Automate repetitive tasks using shell scripts.

**Example: Automating Data Fetch**

```sh
#!/bin/bash
# Fetch Meraki data and save to files

API_KEY="your_api_key"
ORGANIZATION_ID="your_organization_id"
BASE_URL="https://api.meraki.com/api/v1"

# Fetch organizations
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations" > organizations.json
echo "Organizations data saved to organizations.json"

# Fetch networks
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/networks" > networks.json
echo "Networks data saved to networks.json"

# Fetch devices
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/devices" > devices.json
echo "Devices data saved to devices.json"

# Fetch uplinks for a specific device
DEVICE_SERIAL="your_device_serial"
curl -s "$BASE_URL/organizations/$ORGANIZATION_ID/devices/uplinks/addresses/byDevice?serials[]=$DEVICE_SERIAL" -H "Authorization: Bearer $API_KEY" > uplinks.json
echo "Uplinks data saved to uplinks.json"
```

### 4. Data Processing with Python

Use Python for more complex data processing and analysis.

**Example: Loading and Analyzing Data with Python**

```python
import json

# Load organizations data
with open('organizations.json') as f:
    organizations = json.load(f)

# Load networks data
with open('networks.json') as f:
    networks = json.load(f)

# Load devices data
with open('devices.json') as f:
    devices = json.load(f)

# Load uplinks data
with open('uplinks.json') as f:
    uplinks = json.load(f)

# Example: Print organization names and IDs
for org in organizations:
    print(f"Organization ID: {org['id']}, Name: {org['name']}")

# Example: Find and print offline devices
offline_devices = [device for device in devices if device.get('status') != 'online']
print(f"Number of offline devices: {len(offline_devices)}")
for device in offline_devices:
    print(f"Offline Device: {device['name']} (Serial: {device['serial']})")
```

### 5. Monitoring and Alerts with `curl`

Use `curl` in conjunction with shell scripts to set up monitoring and alerts.

**Example: Monitoring Device Status**

```sh
#!/bin/bash
# Monitor device status and alert if any device is offline

API_KEY="your_api_key"
ORGANIZATION_ID="your_organization_id"
BASE_URL="https://api.meraki.com/api/v1"
OUTPUT_FILE="device_status.json"

# Fetch devices
curl -s -H "Authorization: Bearer $API_KEY" "$BASE_URL/organizations/$ORGANIZATION_ID/devices" > $OUTPUT_FILE

# Check device statuses
offline_devices=$(jq '.[] | select(.status != "online")' $OUTPUT_FILE)

if [ -n "$offline_devices" ]; then
  echo "ALERT: Some devices are offline!"
  echo "$offline_devices" | jq '.'
else
  echo "All devices are online."
fi
```

### 6. Data Analysis and Visualization with Python

**Example: Analyzing Device Data with pandas**

```python
import pandas as pd
import matplotlib.pyplot as plt

# Load data from file
df = pd.read_json('devices.json')

# Perform analysis
offline_devices = df[df['status'] != 'online']
print(f"Number of offline devices: {len(offline_devices)}")

# Visualize data
df['status'].value_counts().plot(kind='bar')
plt.title('Device Status Distribution')
plt.xlabel('Status')
plt.ylabel('Count')
plt.show()
```

### Conclusion

Using `curl` for making API calls and shell scripting for automation allows for efficient interaction with the Meraki API. Python serves as a powerful tool for more complex data processing, analysis, and visualization tasks. By integrating these tools into your workflow, you can automate tasks, monitor network status, and gain insights from your Meraki network data.

---

Interacting with APIs, including the Meraki Dashboard API, typically involves a series of steps to automate tasks, gather data, and make data-driven decisions. Since API calls can be ephemeral, it's important to think about how to efficiently use the returned JSON payloads. Here’s a structured approach to interacting with the Meraki API and working with the JSON data it returns.

### Typical Workflow for Interacting with the Meraki API

1. **Authorization and Setup**
2. **Making API Calls**
3. **Storing and Processing Data**
4. **Automation and Scripting**
5. **Monitoring and Alerts**
6. **Data Analysis and Visualization**

### 1. Authorization and Setup

Before making any API calls, you need to set up your environment, including obtaining an API key and setting up any required tools (like Postman, Python libraries, or shell scripts).

**Example: Setting Up Authorization**

```sh
export MERAKI_API_KEY="your_api_key"
```

### 2. Making API Calls

Use tools like `curl`, Postman, or a programming language (e.g., Python) to make API calls. These calls fetch data from Meraki's servers.

**Example: Fetching Organizations**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### 3. Storing and Processing Data

API responses can be stored in databases or files for further processing. Storing data locally allows for repeated analysis without re-fetching data.

**Example: Saving API Response to a File**

```sh
curl -s -H "Authorization: Bearer $MERAKI_API_KEY" "https://api.meraki.com/api/v1/organizations" > organizations.json
```

**Example: Loading and Processing Data with Python**

```python
import json

with open('organizations.json') as f:
    data = json.load(f)

# Process the data
for org in data:
    print(f"Organization ID: {org['id']}, Name: {org['name']}")
```

### 4. Automation and Scripting

Automate repetitive tasks using scripts. This can include fetching data periodically, updating configurations, or processing logs.

**Example: Automating Data Fetch with a Shell Script**

```sh
#!/bin/bash
# Script to fetch Meraki organizations and save to a file

API_KEY="your_api_key"
API_URL="https://api.meraki.com/api/v1/organizations"
OUTPUT_FILE="organizations.json"

curl -s -H "Authorization: Bearer $API_KEY" $API_URL > $OUTPUT_FILE
echo "Data saved to $OUTPUT_FILE"
```

**Example: Scheduling Script with Cron**

```sh
# Edit crontab to run the script daily at midnight
crontab -e

# Add the following line
0 0 * * * /path/to/your/script.sh
```

### 5. Monitoring and Alerts

Set up monitoring to watch for specific conditions or thresholds. This can include network performance, device status, or security events. Use tools like Nagios, Zabbix, or even custom scripts.

**Example: Monitoring Device Status with Python**

```python
import requests

API_KEY = 'your_api_key'
ORGANIZATION_ID = 'your_organization_id'
HEADERS = {
    'Authorization': f'Bearer {API_KEY}'
}

# Fetch device status
response = requests.get(f'https://api.meraki.com/api/v1/organizations/{ORGANIZATION_ID}/devices', headers=HEADERS)
devices = response.json()

# Check device statuses
for device in devices:
    if device['status'] != 'online':
        print(f"Device {device['name']} is offline!")
```

### 6. Data Analysis and Visualization

Analyze the data to gain insights and make informed decisions. Use tools like Jupyter Notebooks, pandas, or visualization libraries like Matplotlib or Tableau.

**Example: Analyzing Device Data with pandas**

```python
import pandas as pd

# Load data from file
df = pd.read_json('devices.json')

# Perform analysis
offline_devices = df[df['status'] != 'online']
print(f"Number of offline devices: {len(offline_devices)}")

# Visualize data
df['status'].value_counts().plot(kind='bar')
plt.show()
```

### Efficient Use of API Responses

- **Caching:** Store API responses locally to avoid repeated API calls. Use databases like SQLite, MongoDB, or even simple JSON files for small-scale caching.
- **Batch Processing:** Process data in batches to minimize the number of API calls. Fetch larger datasets and process them locally.
- **Rate Limiting:** Respect API rate limits to avoid being throttled. Implement retry logic and backoff strategies.
- **Incremental Updates:** Fetch only updated data instead of the entire dataset to reduce the load and increase efficiency.

### Practical Examples

#### Example: Fetching and Storing Network Data

**Shell Script:**

```sh
#!/bin/bash
# Fetch networks for an organization and store in a file

API_KEY="your_api_key"
ORGANIZATION_ID="your_organization_id"
API_URL="https://api.meraki.com/api/v1/organizations/$ORGANIZATION_ID/networks"
OUTPUT_FILE="networks.json"

curl -s -H "Authorization: Bearer $API_KEY" $API_URL > $OUTPUT_FILE
echo "Network data saved to $OUTPUT_FILE"
```

**Python Script:**

```python
import requests
import json

API_KEY = 'your_api_key'
ORGANIZATION_ID = 'your_organization_id'
HEADERS = {
    'Authorization': f'Bearer {API_KEY}'
}

# Fetch networks
response = requests.get(f'https://api.meraki.com/api/v1/organizations/{ORGANIZATION_ID}/networks', headers=HEADERS)
networks = response.json()

# Save to file
with open('networks.json', 'w') as f:
    json.dump(networks, f, indent=4)
```

### Conclusion

By following these steps, you can efficiently interact with the Meraki Dashboard API, store and process data, automate tasks, monitor network status, and analyze the data to make informed decisions. The key is to leverage the API for automation, efficient data handling, and actionable insights. If you have further questions or need more specific examples, feel free to ask!

---

Cisco Meraki organizes its networks and devices in a hierarchical structure that provides a clear and scalable way to manage and monitor your network infrastructure. Understanding this hierarchy is essential for effectively using the Meraki Dashboard and API. Here’s a breakdown of the hierarchy:

## Meraki Hierarchy

1. **Organizations**
2. **Networks**
3. **Devices**
4. **Clients**

### 1. Organizations

**Organizations** are the top-level entities in the Meraki ecosystem. An organization can represent a company, a business unit, or a large geographical area. Each organization can contain multiple networks.

- **Key Attributes:**
  - `id`: Unique identifier for the organization.
  - `name`: Name of the organization.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### 2. Networks

**Networks** are collections of devices and configurations that work together to provide network services. Networks can be configured for different purposes such as office locations, retail stores, or different sites within a campus.

- **Key Attributes:**
  - `id`: Unique identifier for the network.
  - `organizationId`: ID of the organization to which the network belongs.
  - `name`: Name of the network.
  - `type`: Type of network (e.g., `wireless`, `switch`, `appliance`, `combined`).

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations/ORGANIZATION_ID/networks" | jq .
```

### 3. Devices

**Devices** are the individual hardware units that make up a network. This includes wireless access points, switches, security appliances, cameras, and other Meraki devices.

- **Key Attributes:**
  - `serial`: Unique serial number of the device.
  - `networkId`: ID of the network to which the device belongs.
  - `model`: Model of the device (e.g., `MX64`, `MR33`).
  - `name`: Name of the device.
  - `mac`: MAC address of the device.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/devices" | jq .
```

### 4. Clients

**Clients** are the end devices that connect to the Meraki network. This can include computers, smartphones, tablets, and IoT devices.

- **Key Attributes:**
  - `id`: Unique identifier for the client.
  - `description`: Description of the client.
  - `mac`: MAC address of the client.
  - `ip`: IP address assigned to the client.
  - `usage`: Data usage statistics for the client.

**Example API Request:**
```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/clients" | jq .
```

## Practical Usage Example

Here’s how you can traverse this hierarchy using the Meraki Dashboard API:

### Step 1: List Organizations

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations" | jq .
```

### Step 2: List Networks in an Organization

Replace `ORGANIZATION_ID` with the actual ID of your organization.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/organizations/ORGANIZATION_ID/networks" | jq .
```

### Step 3: List Devices in a Network

Replace `NETWORK_ID` with the actual ID of your network.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/devices" | jq .
```

### Step 4: List Clients in a Network

Replace `NETWORK_ID` with the actual ID of your network.

```sh
curl -s -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" "https://api.meraki.com/api/v1/networks/NETWORK_ID/clients" | jq .
```

## Conclusion

Understanding the hierarchy used by Meraki to organize networks and devices is crucial for effective network management and monitoring. The Meraki Dashboard API provides a powerful way to programmatically interact with your network infrastructure, allowing you to automate tasks, gather data, and perform complex queries.

By practicing with the Meraki Dashboard API and using `jq` to parse and manipulate the JSON data, you can gain deeper insights into your network and improve your overall management capabilities. If you have any further questions or need additional examples, feel free to ask!

---
### Understanding the Meraki Dashboard API

The Meraki Dashboard API is designed to enable programmatic management and monitoring of Cisco Meraki networks. It allows you to automate tasks, gather data, and create custom solutions for network administration. This guide will walk you through the basics of using the Meraki Dashboard API, including finding organization IDs, network IDs, and device information, as well as retrieving device uplink addresses.

### Getting Started with the Meraki Dashboard API

#### Tools

- **Postman Collection:** A graphical tool to explore and interact with the Meraki API.
- **Python Library:** The Meraki Python library can be installed via `pip install meraki` for scripting API interactions.

#### Base URI

The base URI for API requests is typically:

```
https://api.meraki.com/api/v1
```

For specific regions, use the respective URIs:

| Country              | URI                                 |
|----------------------|-------------------------------------|
| Canada               | https://api.meraki.ca/api/v1        |
| China                | https://api.meraki.cn/api/v1        |
| India                | https://api.meraki.in/api/v1        |
| United States FedRAMP| https://api.gov-meraki.com/api/v1   |

#### Authorization

The API requires a bearer token for authorization. Include the following header in your requests:

```json
{
  "Authorization": "Bearer <Meraki_API_Key>"
}
```

### Step-by-Step Guide

#### 1. Find Your Organization ID

The first step is to retrieve the organization ID associated with your API key. This ID is required for most API requests.

**Request:**

```sh
curl https://api.meraki.com/api/v1/organizations \
  -L -H 'Authorization: Bearer {MERAKI-API-KEY}'
```

**Response:**

```json
[
  {
    "id": "549236",
    "name":"DevNet Sandbox"
  }
]
```

#### 2. Find Your Network ID

With the organization ID, you can list all networks within the organization.

**Request:**

```sh
curl https://api.meraki.com/api/v1/organizations/{organizationId}/networks \
  -L -H 'Authorization: Bearer {MERAKI-API-KEY}'
```

**Response:**

```json
[
  {
    "id":"N_1234",
    "organizationId":"12345678",
    "type": "wireless",
    "name":"My network",
    "timeZone": "US/Pacific",
    "tags": null
  }
]
```

#### 3. Find Your Devices and Their Serials

Use the organization ID to list all devices within the organization.

**Request:**

```sh
curl https://api.meraki.com/api/v1/organizations/{organizationId}/devices \
  -L -H 'Authorization: Bearer {MERAKI-API-KEY}'
```

**Response:**

```json
[
    {
        "name": "My AP",
        "lat": 37.4180951010362,
        "lng": -122.098531723022,
        "address": "1600 Pennsylvania Ave",
        "notes": "My AP note",
        "tags": [ "recently-added" ],
        "networkId": "N_24329156",
        "serial": "Q234-ABCD-5678",
        "model": "MR34",
        "mac": "00:11:22:33:44:55",
        "lanIp": "1.2.3.4",
        "firmware": "wireless-25-14",
        "productType": "wireless"
    }
]
```

#### 4. Get Devices Uplink Addresses

Retrieve the uplink addresses for specific devices using their serial numbers.

**Request for One Device:**

```sh
curl "https://api.meraki.com/api/v1/organizations/{organizationId}/devices/uplinks/addresses/byDevice?serials[]={serial}" \
  -L -H 'Authorization: Bearer {MERAKI-API-KEY}'
```

**Response for One Device:**

```json
[
 {
  "mac": "00:11:22:33:44:55",
  "name": "My Switch 1",
  "network": {
   "id": "L_24329156"
  },
  "productType": "switch",
  "serial": "{serial}",
  "tags": [
   "example",
   "switch"
  ],
  "uplinks": [
   {
    "interface": "man1",
    "addresses": [
     {
      "protocol": "ipv4",
      "address": "10.0.1.2",
      "gateway": "10.0.1.1",
      "assignmentMode": "dynamic",
      "nameservers": {
       "addresses": [
        "208.67.222.222",
        "208.67.220.220"
       ]
      },
      "public": {
       "address": "78.11.19.49"
      }
     },
     {
      "protocol": "ipv6",
      "address": "2600:1700:ae0::c8ff:fe1e:12d2",
      "gateway": "fe80::fe1b:202a",
      "assignmentMode": "dynamic",
      "nameservers": {
       "addresses": [
        "::",
        "::"
       ]
      },
      "public": {
       "address": null
      }
     }
    ]
   }
  ]
 }
]
```

**Request for Two Devices:**

```sh
curl "https://api.meraki.com/api/v1/organizations/{organizationId}/devices/uplinks/addresses/byDevice?serials[]={serial1}&serials[]={serial2}" \
  -L -H 'Authorization: Bearer {MERAKI-API-KEY}'
```

**Response for Two Devices:**

```json
[
  {
    "mac": "00:11:22:33:44:55",
    "name": "My Switch 1",
    "network": {
      "id": "L_24329156"
    },
    "productType": "switch",
    "serial": "{serial1}",
    "tags": [
      "example",
      "switch"
    ],
    "uplinks": [
      {
        "interface": "man1",
        "addresses": [
          {
            "protocol": "ipv4",
            "address": "10.0.1.2",
            "gateway": "10.0.1.1",
            "assignmentMode": "dynamic",
            "nameservers": {
              "addresses": [
                "208.67.222.222",
                "208.67.220.220"
              ]
            },
            "public": {
              "address": "78.11.19.49"
            }
          },
          {
            "protocol": "ipv6",
            "address": "2600:1700:ae0::c8ff:fe1e:12d2",
            "gateway": "fe80::fe1b:202a",
            "assignmentMode": "dynamic",
            "nameservers": {
              "addresses": [
                "::",
                "::"
              ]
            },
            "public": {
              "address": null
            }
          }
        ]
      }
    ]
  },
  {
    "mac": "00:11:22:33:44:55",
    "name": "My Switch 2",
    "network": {
      "id": "L_24329156"
    },
    "productType": "switch",
    "serial": "{serial2}",
    "tags": [
      "example",
      "switch"
    ],
    "uplinks": [
      {
        "interface": "man1",
        "addresses": [
          {
            "protocol": "ipv4",
            "address": "10.0.1.3",
            "gateway": "10.0.1.1",
            "assignmentMode": "dynamic",
            "nameservers": {
              "addresses": [
                "208.67.222.222",
                "208.67.220.220"
              ]
            },
            "public": {
              "address": "78.11.19.49"
            }
          },
          {
            "protocol": "ipv6",
            "address": "2600:1700:ae0:f84c::9c2f",
            "gateway": "fe80::aa46:202a",
            "assignmentMode": "dynamic",
            "nameservers": {
              "addresses": [
                "::",
                "::"
              ]
            },
            "public": {
              "address": null
            }
          }
        ]
      }
    ]
  }
]
```

### Conclusion

The Meraki Dashboard API provides a robust set of tools for managing and monitoring Meraki networks. By following this guide, you can:

1. Retrieve organization IDs.
2. List networks within an organization.
3. Find devices and their serial numbers.
4. Retrieve uplink addresses for devices.

This allows for efficient automation and detailed network management, enabling you to streamline network operations and create custom solutions to fit your specific needs. If you have any questions or need further assistance, feel free to ask!

---

Sure! Here's a Mermaid chart that visualizes the hierarchical structure of Organizations, Networks, and Devices. You can use this chart on your GitHub site to illustrate the relationships and IDs associated with each entity.

### Mermaid Chart Code

```mermaid
graph TD;
  A[Organizations] -->|Each organization has a unique ID| B[Networks]
  B -->|Each network has a unique ID| C[Devices]
  C -->|Devices are identified by their serial numbers| C
```

### Explanation

- **Organizations**: The top-level entity.
- **Networks**: Child entities of organizations.
- **Devices**: Child entities of networks.

### Adding the Mermaid Chart to Your GitHub Site

1. **Create or Edit a Markdown File**: Open the Markdown file where you want to add the chart.

2. **Insert the Mermaid Chart Code**: Copy and paste the Mermaid chart code into your Markdown file.

3. **Enable Mermaid in GitHub Pages**: If you're using GitHub Pages with Jekyll, ensure that the `jekyll-mermaid` plugin is enabled in your `_config.yml` file.

### Example Markdown File

# Understanding the Hierarchical Structure

```mermaid
graph TD;
  A[Organizations] --> B[Networks]
  B --> C[Devices]
  A -->|Each organization has a unique ID| B
  B -->|Each network has a unique ID| C
  C -->|Devices are identified by their serial numbers| C
```


By adding this Mermaid chart to your GitHub site, you'll have a clear visual representation of the hierarchical structure within Meraki's organization, network, and device model. If you need further customization or have additional questions, feel free to ask!

---

### Guide: Converting Python Scripts to Ansible Playbooks and Vice Versa

This guide provides a step-by-step approach for converting Python scripts to Ansible playbooks and Ansible playbooks to Python scripts. It also outlines when to choose Bash/Python scripts versus Ansible playbooks based on your use case.

---

### Converting Python to Ansible

**1. Identify each API call in the Python script.**

**2. Use the Ansible `uri` module for HTTP requests.**

**3. Use the `set_fact` module to store variables.**

**4. Use the `copy` module to save content to files.**

**5. Use `ansible.builtin.debug` for debugging output.**

---

**Example Python Script: Fetching Organizations and Networks**

```python
import requests
import json

API_KEY = 'your_api_key'
BASE_URL = 'https://api.meraki.com/api/v1'

# Fetch organizations
response = requests.get(f'{BASE_URL}/organizations', headers={'Authorization': f'Bearer {API_KEY}'})
organizations = response.json()
with open('organizations.json', 'w') as f:
    json.dump(organizations, f, indent=4)
print("Organizations data saved to organizations.json")

# Extract organization ID
org_id = organizations[0]['id']

# Fetch networks
response = requests.get(f'{BASE_URL}/organizations/{org_id}/networks', headers={'Authorization': f'Bearer {API_KEY}'})
networks = response.json()
with open('networks.json', 'w') as f:
    json.dump(networks, f, indent=4)
print("Networks data saved to networks.json")
```

**Converted Ansible Playbook (myplaybook.yml):**

```yaml
---
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Get all Organizations
      uri:
        url: "https://api.meraki.com/api/v1/organizations"
        method: GET
        headers:
          Authorization: "Bearer {{ lookup('env', 'MERAKI_DASHBOARD_API_KEY') }}"
        return_content: yes
      register: organizations

    - name: Save organizations to file
      copy:
        content: "{{ organizations.json | to_nice_json }}"
        dest: ./organizations.json

    - name: Extract organization ID
      set_fact:
        organization_id: "{{ organizations.json[0].id }}"

    - name: Get all Networks for the first Organization
      uri:
        url: "https://api.meraki.com/api/v1/organizations/{{ organization_id }}/networks"
        method: GET
        headers:
          Authorization: "Bearer {{ lookup('env', 'MERAKI_DASHBOARD_API_KEY') }}"
        return_content: yes
      register: networks

    - name: Save networks to file
      copy:
        content: "{{ networks.json | to_nice_json }}"
        dest: ./networks.json
```

**Hosts File (hosts):**

```ini
[local]
localhost
```

**Run the Playbook:**

```sh
ansible-playbook -i hosts myplaybook.yml
```

---

### Converting Ansible to Python

**1. Identify each task in the Ansible playbook.**

**2. Use the `requests` library for HTTP requests.**

**3. Use Python variables to store and manipulate data.**

**4. Use `print` or `json.dumps` for output.**

---

**Example Ansible Playbook:**

```yaml
---
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Get all Organizations
      cisco.meraki.organizations_info:
        meraki_api_key: "{{ lookup('env', 'MERAKI_DASHBOARD_API_KEY') }}"
      register: result

    - name: Show Organizations List
      ansible.builtin.debug:
        msg: "{{ result.meraki_response | json_query('[*].{id: id, name: name}') }}"

    - name: Get all Networks for the first Organization
      cisco.meraki.networks_info:
        meraki_api_key: "{{ lookup('env', 'MERAKI_DASHBOARD_API_KEY') }}"
        organization_id: "{{ result.meraki_response[0].id }}"
      register: networks

    - name: Show Networks List
      ansible.builtin.debug:
        msg: "{{ networks.meraki_response | json_query('[*].{id: id, name: name}') }}"
```

**Converted Python Script:**

```python
import requests
import json
import os

API_KEY = os.getenv('MERAKI_DASHBOARD_API_KEY')
BASE_URL = 'https://api.meraki.com/api/v1'

# Get all Organizations
response = requests.get(f'{BASE_URL}/organizations', headers={'Authorization': f'Bearer {API_KEY}'})
organizations = response.json()
print("Organizations List:")
print(json.dumps([{ 'id': org['id'], 'name': org['name'] } for org in organizations], indent=4))

# Extract organization ID
organization_id = organizations[0]['id']

# Get all Networks for the first Organization
response = requests.get(f'{BASE_URL}/organizations/{organization_id}/networks', headers={'Authorization': f'Bearer {API_KEY}'})
networks = response.json()
print("Networks List:")
print(json.dumps([{ 'id': net['id'], 'name': net['name'] } for net in networks], indent=4))
```

---

### Choosing Between Bash/Python and Ansible

**Bash/Python:**
- **Use for quick scripts**: Ideal for simple, one-off tasks.
- **Fine-grained control**: Offers detailed control over each step and can handle dynamic programming logic easily.
- **Flexibility**: Easily switch between different tasks and workflows.

**Ansible:**
- **Use for automation**: Best for automating routine tasks and ensuring consistency across environments.
- **Scalability**: Designed to scale across many devices and networks.
- **Readability and simplicity**: Playbooks are written in YAML, which is easy to read and understand.
- **Error handling and idempotence**: Handles errors gracefully and ensures tasks run once with the same effect.

---

By following this guide, you can convert Python scripts to Ansible playbooks and vice versa, allowing you to choose the best tool for your specific needs. Whether you need fine-grained control with Bash/Python or scalable automation with Ansible, this guide provides the necessary steps for effective conversions.

If you have any further questions or need additional examples, feel free to ask!