CSV-Powered Tagging Recipes for Azure & OCI

No-fuss CSV tagging scripts for Azure RGs & OCI compartments—serve up tags with a single file.

Overview

Think of these CSV-powered tagging tools as your FinOps sous-chefs—just feed them a simple CSV and they’ll sprinkle the five essential tags (Environment, Owner, CostCenter, Project, Application) onto your Azure RGs and OCI compartments, keeping your cloud kitchen organized and cost-savvy.

CloudCostChefs Azure RG Tag Chef

Whip up consistent tags across all your Azure Resource Groups in a snap—just feed it a CSV and watch the magic happen.

CloudCostChefs OCI Compartment Tag Chef

Serve up standardized tags across all your OCI compartments—just feed it a CSV and watch it cook up consistency and cost clarity.

Why Use These Tools?

Sure, the portals have tagging buttons—but these scripts let you:

  • 🔄 Tag dozens of resources in one swoop
  • ✅ Keep tags uniform across your entire organization
  • 🤖 Bake tagging into your automation pipelines
  • 📝 Capture every tag change in detailed logs

Key Features

CSV-Driven

A plain CSV means even non-techy teammates can update tags—no code wizardry needed.

Core Tag Ingredients

We zero in on the five must-have tags—Environment, Owner, CostCenter, Project, and Application—to keep your cloud costs in check and your resources well-seasoned.

Minimal Dependencies

All you need is pandas and the Azure or OCI SDK—no extra garnish, quick to install, and ready to run.

Detailed Logging

Every tagging action is logged to both console and file—so you’ll have a clear audit trail and troubleshooting breadcrumbs whenever you need them.

Tag Merger Magic

Keeps your old tags intact and blends in new ones—no empty-handed tag overwrites here.

Error Resilience

If one resource throws a tantrum, the script keeps cooking—no full-stop failures here.

Prerequisites

Azure Prerequisites

  1. Python 3.6+ installed on your system
  2. Required Python packages:
    bash
    pip install pandas azure-identity azure-mgmt-resource
  3. Azure CLI installed and configured with appropriate permissions:
    bash
    # Login to Azure az login  # Verify you have the correct permissions az account show
  4. Permissions: You need at least Reader and Tag Contributor role on the resource groups you want to tag

CSV Format

Azure CSV Format

Create a CSV file named ResourceGroup_Tags.csv with the following columns:

csv
ResourceGroupName,SubscriptionId,Environment,Owner,CostCenter,Project,Application

Example entries:

csv
rg-finance-prod,12345678-1234-1234-1234-123456789012,Production,jane.doe@example.com,FIN1234,ERP-Migration,ERP-App rg-devops-dev,87654321-4321-4321-4321-987654321098,Development,john.smith@example.com,ENG5678,CI-CD,Build-Pipeline
Required Columns

Only ResourceGroupName and SubscriptionId are required. The tag columns (Environment, Owner, CostCenter, Project, Application) are optional, but you should include at least one tag column for the script to be useful.

Installation & Setup

Azure Setup

  1. Download the Azure Resource Group Tagger script:
  2. Create a directory for your tagging operations:
    bash
    mkdir -p azure-tagging/logs
  3. Place the script in the directory:
    bash
    mv azure_rg_tagger.py azure-tagging/
  4. Create your CSV file (see CSV Format section) and place it in the same directory:
    bash
    # Example: Create a simple CSV echo 'ResourceGroupName,SubscriptionId,Environment,Owner,CostCenter,Project,Application' > azure-tagging/ResourceGroup_Tags.csv echo 'rg-example,12345678-1234-1234-1234-123456789012,Production,admin@example.com,IT001,Core-Infra,Monitoring' >> azure-tagging/ResourceGroup_Tags.csv
  5. Make the script executable:
    bash
    chmod +x azure-tagging/azure_rg_tagger.py

Usage

Running the Azure Tagger

  1. Navigate to your script directory:
    bash
    cd azure-tagging
  2. Run the script:
    bash
    ./azure_rg_tagger.py
  3. Check the output in the console and the log file:
    bash
    cat logs/azure_rg_tagger.log

Environment Variables

You can customize the script behavior with these environment variables:

  • RESOURCE_GROUP_CSV_PATH - Path to your CSV file (default: ./ResourceGroup_Tags.csv)
  • LOG_DIR - Directory for log files (default: ./logs)

Example with Custom CSV Path

bash
RESOURCE_GROUP_CSV_PATH=/path/to/my/custom_tags.csv ./azure_rg_tagger.py

Customization

Customizing the Azure Tagger

Adding Custom Tags

To add custom tags beyond the default five, modify the prepare_tags function in the script:

python
def prepare_tags(row): # Original tags tags = {} if pd.notnull(row.get('Environment')): tags['Environment'] = str(row['Environment']).strip() if pd.notnull(row.get('Owner')): tags['Owner'] = str(row['Owner']).strip() if pd.notnull(row.get('CostCenter')): tags['CostCenter'] = str(row['CostCenter']).strip() if pd.notnull(row.get('Project')): tags['Project'] = str(row['Project']).strip() if 'Application' in row and pd.notnull(row.get('Application')): tags['Application'] = str(row['Application']).strip()  # Add your custom tag if 'Department' in row and pd.notnull(row.get('Department')): tags['Department'] = str(row['Department']).strip()  return tags

Changing Log Format

To modify the logging format, update the logging.basicConfig call:

python
logging.basicConfig( filename=LOG_FILENAME, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s'  # Custom format )

Adding Email Notifications

To add email notifications when tagging is complete, add this function and call it at the end of main():

python
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart  def send_notification_email(log_file, recipients): # Read the log file with open(log_file, 'r') as f: log_content = f.read()  # Create email msg = MIMEMultipart() msg['Subject'] = 'Azure Resource Group Tagging Complete' msg['From'] = 'your-email@example.com' msg['To'] = ', '.join(recipients)  body = f''' Azure Resource Group tagging process has completed.  Summary: {log_content[-500:]}  # Last 500 characters of log  Full log attached. ''' msg.attach(MIMEText(body, 'plain'))  # Add log as attachment attachment = MIMEText(log_content) attachment.add_header('Content-Disposition', 'attachment', filename='tagging_log.txt') msg.attach(attachment)  # Send email try: server = smtplib.SMTP('smtp.example.com', 587) server.starttls() server.login('your-email@example.com', 'your-password') server.send_message(msg) server.quit() logging.info(f'Notification email sent to {recipients}') except Exception as e: logging.error(f'Failed to send notification email: {e}')

Troubleshooting

Azure Troubleshooting

Authentication Errors

If you see authentication errors:

  1. Ensure you're logged in with Azure CLI: az login
  2. Check if your credentials have expired and re-login if necessary
  3. Verify you have the correct permissions on the target subscriptions

Resource Group Not Found

If you see "Resource Group not found" errors:

  1. Verify the resource group name is spelled correctly in your CSV
  2. Check that the subscription ID is correct
  3. Confirm the resource group exists in the specified subscription

CSV Format Issues

If you see CSV parsing errors:

  1. Ensure your CSV has the correct headers
  2. Check for special characters or encoding issues in your CSV
  3. Try opening and resaving the CSV in a text editor with UTF-8 encoding

Best Practices

Consistent Naming

Use consistent tag values across your organization:

  • Standardize environment names (e.g., "Production", "Development", "Testing")
  • Use email addresses for Owner tags
  • Use established cost center codes

Automation Integration

Integrate tagging into your workflows:

  • Run the script as part of your CI/CD pipeline
  • Schedule regular tagging updates
  • Combine with tag enforcement policies

CSV Management

Maintain your CSV files effectively:

  • Store CSV files in version control
  • Document the purpose and owner of each CSV
  • Consider using a central database or spreadsheet as the source of truth

Validation & Testing

Ensure your tagging operations are reliable:

  • Test on non-production resources first
  • Validate CSV data before running the script
  • Review logs after each run to catch any issues
Tag Inheritance

Remember that in both Azure and OCI, tags are not automatically inherited by child resources. Consider implementing additional tagging strategies for individual resources if needed.

Next Steps

After implementing these tagging tools, consider these next steps to enhance your cloud cost management:

Tag-Based Reporting

Leverage your tags for cost analysis:

  • Create cost reports grouped by Environment, CostCenter, or Project
  • Set up dashboards to visualize spending by tag
  • Share reports with stakeholders based on their tags

Tag Enforcement

Ensure consistent tagging across your organization:

  • Implement Azure Policy or OCI policies to require tags
  • Set up alerts for non-compliant resources
  • Create automated remediation for missing tags

Was this documentation helpful?

Have suggestions for improving this documentation? Contact us.