Share this post on:

Introduction

In this post, I’ll show you how to connect to Azure and run first Ansible playbook.

Required keys

On the Azure end, we need gather following keys:

  • subscription ID
  • service principal ID
  • tenant ID
  • service principal password

Login to Azure, open a console, select Powershell and run following commands:

$subscriptionId = (Get-AzSubscription -SubscriptionName 'NameOfSubscriptionHere').id 
$servicePrincipalAppId = (Get-AzADServicePrincipal -DisplayName 'sp-cs-ansible').ApplicationId 
$servicePrincipalPassword = 'password' $tenantId = (Get-AzSubscription -SubscriptionName 'NameOfSubscriptionHere').TenantId

Install Ansible and Azure modules

I’m using Centos 8 64bit server; installing Ansible along with Azure modules is dead easy:

[root@centos /]# yum install pip -y
[root@centos /]# pip install 'ansible[azure]'

Ansible looks in .azure/credentials file by default. Let’s put our credentials into the file.

mkdir ~/.azure
vi ~/.azure/credentials
[default]
subscription_id=<subscription_id>
client_id=<security-principal-appid>
secret=<security-principal-password>
tenant=<security-principal-tenant>

First playbook

Let’s create our first playbook that creates a new resource group.

mkdir /etc/ansible/playbooks 
vi /etc/ansible/playbooks/new_rg.yaml
--- 
- hosts: localhost 
  connection: local 
  tasks: 
    - name: Create resource group 
      azure_rm_resourcegroup: 
        name: myfirst_ansible_rg 
        location: uksouth 
      register: rg 
    - debug: 
        var: rg

Please note, YAML format requires very specific indentation and separation. You can verify formatting of your playbooks here: http://www.yamllint.com

Executing Playbook

Executing Ansible playbook is easy:

ansible-playbook [playbook.yaml]
[root@centos playbooks]# ansible-playbook rg.yaml

As we can see above, playbook executed properly. Let’s verify if the resource group exist in the actual Azure portal:

pawel@Azure:~$ az group list | grep name
"name": "PavstaRG",
"name": "NetworkWatcherRG",
"name": "Site-recovery-vault-RG",
"name": "PavstaRG-asr",
"name": "myResourceGroup",
"name": "cloud-shell-storage-northeurope",
"name": "LAB_group",
"name": "myfirst_ansible_rg",

Perfect, as desired our new resource group is there.

Leave a Comment

Your email address will not be published. Required fields are marked *