使用凭据文件和azure_rm_resource模块时,Ansible访问Azure凭据

时间:2018-08-29 22:15:15

标签: azure ansible

虽然我使用ansible在Azure上创建一些基础结构,但是我尝试在ansible运行期间访问subscritpion_id。我按照 Ansible文档https://docs.ansible.com/ansible/2.6/scenario_guides/guide_azure.html

中的Azure指南

当我运行ansible剧本时,我添加了以下参数-e ANSIBLE_PROFILE="new-env",该参数将执行所需的操作并为运行提供正确的凭据以正确执行模块。

但是我试图通过azure_rm_resource模块使用Azure REST API,并且我想在请求的正文中发送JSON表示形式,其中包括subscription_id来格式化a的ID Azure中的资源。 https://docs.ansible.com/ansible/2.6/modules/azure_rm_resource_module.html

可以说Azure中的VNet ID看起来像"id": "/subscriptions/<subscription_id>/resourceGroups/myresourcegroup/providers/Microsoft.Network/virtualNetworks/my-vnet", 我可以格式化vnet的名称,但是我需要获取订阅ID的信息,该信息在剧本运行期间由~/.azure/credentials文件的ansible读取。

如何访问此信息?有一个特殊的变量吗?我查看了lookup env功能,但变量AZURE_SUBSCRIPTION_ID不存在。

这不是我尝试使用以下命令AZURE_PROFILE="new-env" ansible localhost -m setup

揭露事实的事实

凭据文件示例

    cat ~/.azure/credentials

    [new-env]
    subscription_id=****************************
    client_id=****************************
    secret=****************************
    tenant=****************************

谢谢

更新#1

我最终使用了ansible ini查找功能。

     "{{ lookup('ini',  'subscription_id section={{ azure_profile }}  file={{ ansible_env.HOME }}/.azure/credentials') }}" 

这将返回我一直在寻找的确切值,我使用set_fact来通过我的敏感运行设置它。

1 个答案:

答案 0 :(得分:0)

使用ini查找,我直接在凭据文件中搜索,然后将其设置为一个事实,以便以后再次使用。

tasks:

    - name: set fact to reduce the verbosity of the variables
      set_fact:
        azure_profile: "{{ AZURE_PROFILE }}"
        azure_subscription_id: "{{ lookup('ini',  'subscription_id section={{ azure_profile }}  file={{ ansible_env.HOME }}/.azure/credentials') }}"