這篇文章主要介紹如何通過Ansible的Playbook,來批量更改Azure中的資源.這里先聲明,選擇Ansible的起因完全是自己不會寫復雜的Shell腳本,如果有大神看到這篇文章,請自動右轉哈哈.
本次實驗,其實做了一個比較簡單,但比較實用的事情,將所有未設置HttpsOnly的Storage Account,設置成HttpsOnly,僅支持Https訪問,讓訪問更加安全.
當我們環(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
由于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