😀

Mac で Ansible を使って Azure をいじる環境を整えてみた

に公開

背景と目的

https://learn.microsoft.com/ja-jp/dotnet/architecture/cloud-native/infrastructure-as-code

https://learn.microsoft.com/ja-jp/devops/deliver/what-is-infrastructure-as-code

https://learn.microsoft.com/ja-JP/azure/architecture/framework/devops/automation-infrastructure

IaC コードとしてのインフラストラクチャですが、マイクロソフトのドキュメントの色んなところに説明が書かれている通り、沢山のメリットがあります。宣言型の IaC には、ARM テンプレート、Bicep、Terraform、Ansible 等があります。命令型の IaC には、Bash、PowerShell 等があり、CLI でも反復可能で信頼性の高い Azure リソース作成ができます。それなのに未だに Azure ポータルのスクショの手順書とパラメーターシートを見ながら構築する方法が多いなぁと個人的に感じます。私個人は普段は Azure CLI を使うことが多く、Terraform も必要に応じて使いますが、Ansible は Python との絡みや実行環境を整えるのに苦労するので、一つの例として Mac で Ansible を使って Azure をいじる環境を整えてみました。

Ansible 実行環境の情報

bash
# Mac のバージョン
$ sw_vers
ProductName:            macOS
ProductVersion:         13.0.1
BuildVersion:           22A400

# Python のバージョン
$ python3 --version
Python 3.9.1

# PIP のバージョン
$ pip --version
pip 22.3.1 from /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip (python 3.9)

Ansible と Azure の Python パッケージをインストール

bash
# Ansible をインストールします
pip install ansible

# Ansible のバージョンを確認します
ansible --version

ansible [core 2.13.6]

# azcollection をインストールします
ansible-galaxy collection install azure.azcollection

# Azure の Python パッケージをインストールします
pip install -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements-azure.txt

Ansible で Azure リソースを作成できるか試してみる

bash
# 環境変数をセットします
export AZURE_AD_USER=$(az account show --query user.name -o tsv)
export AZURE_PASSWORD="<your password here>"
export AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv)

# リソースグループを作成します
ansible localhost \
  -m azure.azcollection.azure_rm_resourcegroup \
  -a "name=ansible-rg location=japaneast"

# リソースグループが作成されたか確認します
az group show -n ansible-rg -o table

Location    Name
----------  ----------
japaneast   ansible-rg

# リソースグループを削除します
az group delete -n ansible-rg --yes

参考

https://learn.microsoft.com/ja-jp/azure/developer/ansible/install-on-linux-vm?tabs=azure-cli

https://galaxy.ansible.com/azure/azcollection

https://docs.ansible.com/ansible/latest/scenario_guides/guide_azure.html

https://learn.microsoft.com/ja-jp/azure/developer/ansible/vm-configure?tabs=ansible

https://docs.ansible.com/ansible/latest/collections/azure/azcollection/index.html#plugins-in-azure-azcollection

Discussion