Connecting to Azure with Ansible

joshduffney

Josh Duffney

Posted on December 18, 2019

Connecting to Azure with Ansible

Introduction

Learn how to connect an Ansible to Azure using an Azure Service Principal account.

Prerequisites


1. Create an Azure Service Principal

Use the PowerShell cmdlet New-AzADServicePrincipal to create an Azure Service Principal account.



$credentials = New-Object Microsoft.Azure.Commands.ActiveDirectory.PSADPasswordCredential `
-Property @{ StartDate=Get-Date; EndDate=Get-Date -Year 2024; Password='<PASSWORD>'};

$spSplat = @{
    DisplayName = 'sp-cs-ansible'
    PasswordCredential = $credentials
}

$sp = New-AzAdServicePrincipal @spSplat
```

Replace `<PASSWORD>` with your password.

## 2. Assign a Role to the Service Principal

By default, service principals are created without any permissions. And without permissions, your service principal will not be authorized to connect to Azure.

Use the `New-AzRoleAssignment` cmdlet to assign the _Contributor_ role to your service principal.

```powershell
$subId = (Get-AzSubscription -SubscriptionName 'NameOfSubscriptionHere').id

$roleAssignmentSplat = @{
    ObjectId = $sp.id
    RoleDefinitionName = 'Contributor'
    Scope = "/subscriptions/$subId"
}

New-AzRoleAssignment @roleAssignmentSplat
```

> NOTE: _To improve security, change the scope of the role assignment to a resource group instead of a subscription._

## 3. Authenticating with Azure

You will need the following information to connect to Azure.

* `SubscriptionId`
* `ApplicationId`
* `Service Principal Password`
* `TenantId`

(Optional) Use PowerShell to get the required information.

```powershell
@{
    subscriptionId = (Get-AzContext).Subscription.Id
    clientid = (Get-AzADServicePrincipal -DisplayName 'sp-cs-ansible').ApplicationId.Guid
    tenantid = (Get-AzContext).Tenant.Id
}
```

### 3.1 Authenticate using a Credentials File

The Ansible uses the path `~/.azure/credentials` to look for credentials to autoload. 

Placing a file in this location with the proper values will result in Ansible being able to connect to Azure.

**Create a credentials file**

```bash
mkdir ~/.azure
vi ~/.azure/credentials
```

**Populate the required Ansible variables**

```bash
[default]
subscription_id=<subscription_id>
client_id=<security-principal-appid>
secret=<security-principal-password>
tenant=<security-principal-tenant>
```
Replace values within `<  >` with your Azure information.

> _Important: Credential files are for development usage ONLY._

### 3.2 Authenticate using Environment Variables

An alternate method of authentication is the usage of environment variables.

Use the bash command `export` to define the required Ansible environment variables.

```bash
export AZURE_SUBSCRIPTION_ID=<subscription_id>
export AZURE_CLIENT_ID=<security-principal-appid>
export AZURE_SECRET=<security-principal-password>
export AZURE_TENANT=<security-principal-tenant>
```

 Replace values within `<  >` with your Azure information.

> NOTE: _Read more about [Providing Credentials to Azure Modules](https://docs.ansible.com/ansible/latest/scenario_guides/guide_azure.html#providing-credentials-to-azure-modules)._

## 4. Run an Ansible Playbook

Write and execute an Ansible playbook to confirm Ansible can connect to Azure.

**Create** a file named `playbook.yml`

```bash
  vi playbook.yml
```

**Copy and paste** the contents below to into the playbook.

```yaml
---
- hosts: localhost
  connection: local
  tasks:
    - name: Create resource group
      azure_rm_resourcegroup:
        name: rg-cs-ansible
        location: eastus
      register: rg
    - debug:
        var: rg
```

The Ansible playbook will create an Azure resource group named `rg-cs-ansible` in the `eastus` region. 

It registers the output to an Ansible variable that is will be displayed in the terminal using the `debug` module.

### Run the playbook using ansible-playbook

To execute the playbook use the ansible command `ansible-playbook playbook.yml` 

```bash
ansible-playbook playbook.yaml
```

You now have a newly created resource group called `rg-cs-ansible` in Azure!

![Create Resource Group Ansible Playbook Output](https://thepracticaldev.s3.amazonaws.com/i/ug3q82y4ori976h29lcp.png)


### Sources <a name="Sources"></a>

- [Using Ansible with Azure](https://docs.microsoft.com/en-us/azure/ansible/ansible-overview)
- [Quickstart: Install Ansible on Linux virtual machines in Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ansible-install-configure?toc=%2Fazure%2Fansible%2Ftoc.json&bc=%2Fazure%2Fbread%2Ftoc.json#install-ansible-on-an-azure-linux-virtual-machine)
- [Create an Azure service principal with Azure PowerShell](https://docs.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-3.1.0)
- [New-AzRoleAssignment](https://docs.microsoft.com/en-us/powershell/module/az.resources/new-azroleassignment?view=azps-3.1.0)

_Originally posted on [CloudSkills.io](https://cloudskills.io/blog/connect-to-azure-with-ansible)_
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
joshduffney
Josh Duffney

Posted on December 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related