Azure 運維篇 通過 Ansible 批量更改 Azure 資源

來源: Microsoft云科技
作者:Microsoft云科技
時間:2020-09-01
17672
這篇文章主要介紹如何通過 Ansible 的 Playbook, 來批量更改 Azure 中的資源。

這篇文章主要介紹如何通過Ansible的Playbook,來批量更改Azure中的資源.這里先聲明,選擇Ansible的起因完全是自己不會寫復雜的Shell腳本,如果有大神看到這篇文章,請自動右轉哈哈.

本次實驗,其實做了一個比較簡單,但比較實用的事情,將所有未設置HttpsOnly的Storage Account,設置成HttpsOnly,僅支持Https訪問,讓訪問更加安全.

ia_2000000003.jpg

當我們環(huán)境中有很多個Storage Account時,一定是通過腳本來做.腳本實現(xiàn)方式很多,可以是Azure CLI&PowerShell&Python,也可以是Ansible或者Terraform.

搭建運行Ansible的環(huán)境

建議創(chuàng)建一臺VM,來完成今后的運維工作,這臺VM平時可以關掉,節(jié)省費用,需要的時候開啟執(zhí)行任務.機器上除了安裝Ansible,未來很多運維工具,甚至包括Grafana也可以放在這臺機器上,使這臺機器的利用效率更高.

# 創(chuàng)建一臺 Linux 虛擬機, 比如 Ubuntu 16.04, 并安裝相對應的依賴包及Ansible
sudo apt-get update && sudo apt-get install -y libssl-dev libffi-dev python-dev python-pip
sudo pip install ansible[azure]

# 登陸到 Linux 虛機上, 安裝 Azure CLI
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# 切換云環(huán)境, 執(zhí)行登陸Azure操作, 以后每次執(zhí)行Ansible之前, 執(zhí)行一次Azure登陸, 確保Ansible能夠使用Azure登陸信息. 當然有其他的Ansible登陸憑證方式, 可選擇嘗試
az cloud set -n "AzureChinaCloud"

準備Ansible Playbook,更改所有Storage Account的HttpsOnly

Ansible的一個概念叫做Playbook,執(zhí)行一組Task,完成一個事情.如果希望詳細學習Ansible知識及結構的同學,請自行查閱文末Ansible文檔.

本次示例中,用到的Playbook azure_storageaccount_ops.yml如下:

---
-  name: Setup All Storage Accounts to HttpsOnly
   hosts: localhost
   connection: localhost
   tasks:
   - name: List All Storage Accounts in a subscription
     command: az storage account list
     register: allStorageAccounts

   - name:  Update HttpsOnly to True for All Storage Accounts
     command: az storage account update -n {{ item.name }} -g {{ item.resourceGroup }} --https-only true
     with_items: "{{ allStorageAccounts.stdout | from_json}}"
     when: item.enableHttpsTrafficOnly == False

在LInux VM中創(chuàng)建一個文件夾azureops/ansible,并將azure_storageaccount_ops.yml放入其中.

#執(zhí)行Ansible Playbook非常簡單

ansible-playbook~/azureops/ansible/azure_storageaccount_ops.yml

ia_2000000547.jpg

ia_2000000005.jpg

ia_2000000006.jpg

由于Ansible是冪等的,所以當?shù)诙螆?zhí)行檢查到Storage Account的HttpsOnly的狀態(tài)已經(jīng)是True的話,就會跳過執(zhí)行.

這里面其實有兩個額外引申的話題,就留給大家了:

第一,其實我們可以把所有Storage Account相關的運維工作放在一個Playbook中,通過Tag進行區(qū)分,通過Tag進行執(zhí)行;

第二,其實我寫的Playbook非常的簡單,且不算優(yōu)美.Ansibel里面有很多針對于Azure不同服務的Module,大家也可以嘗試使用Module而非直接執(zhí)行Azure CLI,讓Playbook變得更加優(yōu)美.

參考資料

# 快速入門:在 Azure 中的 Linux 虛擬機上安裝 Ansible
https://docs.microsoft.com/zh-cn/azure/virtual-machines/linux/ansible-install-configure

# Ansible 的使用
https://docs.ansible.com/ansible/latest/user_guide/basic_concepts.html

# Ansible中支持的Azure Modules
https://docs.ansible.com/ansible/latest/scenario_guides/guide_azure.html

# Github Azure Resources Playbook Examples
https://github.com/Azure-Samples/ansible-playbooks

立即登錄,閱讀全文
版權說明:
本文內容來自于Microsoft云科技,本站不擁有所有權,不承擔相關法律責任。文章內容系作者個人觀點,不代表快出海對觀點贊同或支持。如有侵權,請聯(lián)系管理員(zzx@kchuhai.com)刪除!
掃碼登錄
打開掃一掃, 關注公眾號后即可登錄/注冊
加載中
二維碼已失效 請重試
刷新
賬號登錄/注冊
個人VIP
小程序
快出海小程序
公眾號
快出海公眾號
商務合作
商務合作
投稿采訪
投稿采訪
出海管家
出海管家