首页 > 解决方案 > 尽管在 Postman 中工作,Python PUT 请求总是返回 401 错误

问题描述

所以我试图调用一个 PUT 请求来创建一个库存策略:https ://docs.microsoft.com/en-us/rest/api/storagerp/blob-inventory-policies/create-or-update

我正在使用 Ansible 自定义模块和 Python 来创建它。

Python

def create_inventory_rule(bearer_token,azure_subscription, azure_storage_account, azure_resource_group):
management_url = "https://management.azure.com/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/inventoryPolicies/default?api-version=2021-04-01".format(azure_subscription,azure_resource_group,azure_storage_account)
body= get_body()

headers = {
    'Authorization':  bearer_token
}

try:
  request = requests.put(management_url, headers= headers, data = body)
  request.raise_for_status()
except requests.exceptions.RequestException as e:
    raise

我可以确认我能够获取 management_url 中的所有变量以及 Bearer 令牌。我在 ansible 运行中获取了创建的 management_url 和承载令牌,在 Postman 中使用它,它返回了 200 OK。我只是想知道我是否在这里遗漏了什么。

- name: Create Access Token
create_token:
  azure_resource : "{{ azure_resource }}"
  azure_tenant_id: "{{ azure_tenant_id }}"
  azure_client_id: "{{ azure_client_id }}"
  azure_client_secret: "{{ azure_client_secret }}"
register: c_access_token

- name: Create Inventory Policy Rule
create_inventory_rules:
  bearer_token: "{{ c_access_token }}"
  azure_subscription: "{{ azure_subscription }}"
  azure_storage_account: "{{ azure_storage_account }}"
  azure_resource_group: "{{ azure_resource_group }}"

谁能帮我在这里检查一下我真的迷路了。可能只是我忽略的东西。

获取正文:

def get_body():
body = {
  "properties": {
"policy": {
  "enabled": "True",
  "type": "Inventory",
  "rules": [
    {
      "enabled": "True",
      "name": "inventoryPolicyRule",
      "destination": "inventory-report",
      "definition": {
        "filters": {
          "blobTypes": [
            "blockBlob",
            "appendBlob"
          ],
          "prefixMatch": [
            "raw",
            "refined",
            "produced"
          ],
          "includeSnapshots": "True",
          "includeBlobVersions": "True"
        },
        "format": "Csv",
        "schedule": "Daily",
        "objectType": "Blob",
        "schemaFields": [
          "Name",
          "Creation-Time",
          "Last-Modified",
          "Content-Length",
          "Content-MD5",
          "BlobType",
          "AccessTier",
          "AccessTierChangeTime",
          "Snapshot",
          "VersionId",
          "IsCurrentVersion",
          "Metadata"
        ]
      }
    }
  ]
}
 }
  }
    return body

标签: pythonansibleansible-module

解决方案


注册 c_access_token 后尝试添加调试。当您在 ansible 中注册时,会有一个对象,因此您需要准确定义令牌的位置。

- debug: var=c_access_token

我怀疑您在注册变量中传递的任务应该是这样的

bearer_token: "{{ c_access_token.results.someOtherObjectKey }}"

推荐阅读