Create/Update only one variable without overwrite all variables by API

,

Hello everyone,

I’m trying to update just one variable of an AWX host through the API, but the request is overwriting all variables. Can anyone confirm if this is possible or guide me on the best approach?

The request I’m sending is:

URL: http://awx.ozmap.com.br/api/v2/hosts/{hostId}/variable_data?search=test
Method: PATCH
body: {“variables”: JSON.stringify({“teste”: “123”})}

Getting all host variables before editing to then send all in the request is not an option because the YAML to JSON conversion ends up altering other variables, hence the need to update just one.

Thank you all.

#!/usr/bin/env python3
import requests
import yaml
from requests.auth import HTTPBasicAuth

# AWX API configuration
AWX_URL = "http://awx.ozmap.com.br"
AWX_USERNAME = "admin"  # Replace with your username
AWX_PASSWORD = "your_password"  # Replace with your password
HOST_ID = "1"  # Replace with your host ID

# API endpoints
HOST_VARIABLES_URL = f"{AWX_URL}/api/v2/hosts/{HOST_ID}/variable_data/"

# Headers for JSON requests
HEADERS = {"Content-Type": "application/json"}

def get_current_variables():
    """Fetch current host variables."""
    response = requests.get(
        HOST_VARIABLES_URL,
        auth=HTTPBasicAuth(AWX_USERNAME, AWX_PASSWORD),
        headers=HEADERS
    )
    response.raise_for_status()
    # Variables are returned as a JSON dict with a 'variables' key containing YAML string
    variables_yaml = response.json().get("variables", "")
    return yaml.safe_load(variables_yaml) or {}

def update_single_variable(key, value):
    """Update a single variable and PATCH back to AWX."""
    # Get current variables
    current_vars = get_current_variables()

    # Update the specific key
    current_vars[key] = value

    # Convert back to YAML string
    updated_yaml = yaml.safe_dump(current_vars, default_flow_style=False)

    # Prepare PATCH payload
    payload = {"variables": updated_yaml}

    # Send PATCH request
    response = requests.patch(
        HOST_VARIABLES_URL,
        auth=HTTPBasicAuth(AWX_USERNAME, AWX_PASSWORD),
        headers=HEADERS,
        json=payload
    )
    response.raise_for_status()
    return response.json()

def main():
    # Variable to update
    key = "teste"
    value = "123"

    try:
        # Update the variable
        result = update_single_variable(key, value)
        print(f"Successfully updated variable '{key}':\n{yaml.safe_dump(result['variables'])}")
    except requests.RequestException as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()