Professional Documents
Culture Documents
Ansible On Azure PDF
Ansible On Azure PDF
Ansible is an open-source product that automates cloud provisioning, configuration management, and application
deployments. Using Ansible you can provision virtual machines, containers, and network and complete cloud
infrastructures. Also, Ansible allows you to automate the deployment and configuration of resources in your
environment.
This article gives a basic overview of some of the benefits of using Ansible with Azure.
Ansible playbooks
Ansible playbooks allow you to direct Ansible to configure your environment. Playbooks are coded using YAML so
as to be human-readable. The Tutorials section gives many examples of using playbooks to install and configure
Azure resources.
Ansible modules
Ansible includes a suite of Ansible modules that are run directly on remote hosts or via playbooks. Users can create
their own modules. Modules are used to control system resources - such as services, packages, or files - or execute
system commands.
For interacting with Azure services, Ansible includes a suite of Ansible cloud modules. These modules enable you
to create and orchestrate your infrastructure on Azure.
Next steps
Quickstart: Deploy the Ansible solution template for Azure to CentOS
Quickstart: Configure Linux virtual machines in Azure using Ansible
Quickstart: Deploy the Ansible solution template for
Azure to CentOS
5/7/2019 • 3 minutes to read • Edit Online
The Ansible solution template for Azure is designed to configure an Ansible instance on a CentOS virtual machine
along with Ansible and a suite of tools configured to work with Azure. The tools include:
Ansible modules for Azure - The Ansible modules for Azure are a suite of modules that enable you to create
and manage your infrastructure on Azure. The latest version of these modules is deployed by default. However,
during the solution-template deployment process, you can specify a version number that is appropriate for your
environment.
Azure Command-Line Interface (CLI ) 2.0 - The Azure CLI 2.0 is a cross-platform command-line experience
for managing Azure resources.
managed identities for Azure resources - The managed identities for Azure resources feature addresses the
issue of keeping cloud application credentials secure.
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
6. Select OK.
7. In the Additional Settings tab, enter the required information:
Size - The Azure portal defaults to a standard size. To specify a different size that accommodates
your specific scenario, select the arrow to display a list of different sizes.
VM disk type - Select either SSD (Premium Solid-State Drive) or HDD (Hard Disk Drive). For
demo purposes, SSD is selected for its performance benefits. For more information on each these
types of disk storage, see the following articles:
High-performance Premium Storage and managed disks for VMs
Standard SSD Managed Disks for Azure Virtual machine workloads
Public IP Address - Specify this setting if you want to communicate with the virtual machine from
outside the virtual machine. The default is a new public IP address that has the name ansible-pip . To
specify a different IP address, select the arrow specify the attributes - such as name, SKU, and
Assignment, of that IP address.
Domain name label - Enter the public-facing domain name of the virtual machine. The name must
be unique and meet naming requirements. For more information about specifying a name for the
virtual machine, see Naming conventions for Azure resources.
Ansible version - Specify either a version number or the value latest to deploy the latest version.
Select the information icon next to Ansible version to see more information about available
versions.
8. Select OK.
9. In the Ansible Integration Settings tab, specify the authentication type. For more information about
securing Azure resources, see What is managed identities for Azure resources?.
15. On the resource group page, get the IP address of your Ansible host and sign in to manage your Azure
resources using Ansible.
Next steps
Quickstart: Configure a Linux virtual machine in Azure using Ansible
Quickstart: Run Ansible playbooks via Bash in Azure
Cloud Shell
5/7/2019 • 2 minutes to read • Edit Online
Azure Cloud Shell is an interactive, browser-accessible shell for managing Azure resources. Cloud Shell provides
enables you to use either a Bash or Powershell command line. In this article, you use Bash within Azure Cloud
Shell to run an Ansible playbook.
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Configure Azure Cloud Shell - If you're new to Azure Cloud Shell, see Quickstart for Bash in Azure Cloud
Shell.
OPTION EXAMPLE/LINK
az account list
export AZURE_SUBSCRIPTION_ID=<your-subscription-id>
code rg.yml
---
- hosts: localhost
connection: local
tasks:
- name: Create resource group
azure_rm_resourcegroup:
name: ansible-rg
location: eastus
register: rg
- debug:
var: rg
ansible-playbook rg.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost] *********************************************************************************
Next steps
Quickstart: Configure virtual machine in Azure using Ansible
Tutorial: Manage web traffic with Azure Application
Gateway using Ansible
5/7/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure Application Gateway is a web traffic load balancer that enables you to manage traffic to your web
applications. Based on the source IP address and port, traditional load balancers route traffic to a destination IP
address and port. Application Gateway gives you a finer level of control where traffic can be routed based on the
URL. For example, you could define that if images is URL's path, traffic is routed to a specific set of servers (known
as a pool) configured for images.
In this tutorial, Ansible is used to:
Set up a network
Create two Azure container instances with HTTPD images
Create an application gateway that works with the Azure container instances in the server pool
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
vars:
resource_group: myResourceGroup
location: eastus
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook rg.yml
- hosts: localhost
vars:
resource_group: myResourceGroup
location: eastus
vnet_name: myVNet
subnet_name: myAGSubnet
publicip_name: myAGPublicIPAddress
publicip_domain: mydomain
tasks:
- name: Create a virtual network
azure_rm_virtualnetwork:
name: "{{ vnet_name }}"
resource_group: "{{ resource_group }}"
address_prefixes_cidr:
- 10.1.0.0/16
- 172.100.0.0/16
dns_servers:
- 127.0.0.1
- 127.0.0.2
ansible-playbook vnet_create.yml
Create servers
The playbook code in this section creates two Azure container instances with HTTPD images to be used as web
servers for the application gateway.
Save the following playbook as aci_create.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
location: eastus
aci_1_name: myACI1
aci_2_name: myACI2
tasks:
- name: Create a container with httpd image
azure_rm_containerinstance:
resource_group: "{{ resource_group }}"
name: "{{ aci_1_name }}"
os_type: linux
ip_address: public
location: "{{ location }}"
ports:
- 80
containers:
- name: mycontainer
image: httpd
memory: 1.5
ports:
- 80
ansible-playbook aci_create.yml
- hosts: localhost
connection: local
vars:
resource_group: myResourceGroup
vnet_name: myVNet
subnet_name: myAGSubnet
location: eastus
publicip_name: myAGPublicIPAddress
appgw_name: myAppGateway
aci_1_name: myACI1
aci_2_name: myACI2
tasks:
tasks:
- name: Get info of Subnet
azure_rm_resource_facts:
api_version: '2018-08-01'
resource_group: "{{ resource_group }}"
provider: network
resource_type: virtualnetworks
resource_name: "{{ vnet_name }}"
subresource:
- type: subnets
name: "{{ subnet_name }}"
register: subnet
ansible-playbook appgw_create.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
Next steps
Ansible on Azure
Tutorial: Configure apps in Azure App Service using
Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure App Service enables you to build and host code. This code can be in the form of web apps, mobile backends,
and RESTful APIs. Using App Service, you can develop you code using the programming language of your choice
without managing infrastructure. App Service supports both Windows and Linux. Automated deployments from
any Git repo are supported, including GitHub and Azure DevOps.
In this tutorial, Ansible is used to:
Create an app in Azure App Service with Java 8 and the Tomcat container runtime
Create an Azure Traffic Manager profile
Define a Traffic Manager endpoint using the created app
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
ansible-playbook firstwebapp.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
changed: [localhost]
PLAY RECAP
localhost : ok=3 changed=2 unreachable=0 failed=0
- hosts: localhost
connection: local
vars:
resource_group_webapp: myResourceGroupWebapp
resource_group: myResourceGroup
webapp_name: myLinuxWebApp
plan_name: myAppServicePlan
location: eastus
traffic_manager_profile_name: myTrafficManagerProfile
traffic_manager_endpoint_name: myTrafficManagerEndpoint
tasks:
- name: Create resource group
azure_rm_resourcegroup:
name: "{{ resource_group_webapp }}"
location: "{{ location }}"
- name: Add endpoint to traffic manager profile, using created web site
azure_rm_trafficmanagerendpoint:
resource_group: "{{ resource_group_webapp }}"
profile_name: "{{ traffic_manager_profile_name }}"
name: "{{ traffic_manager_endpoint_name }}"
type: azure_endpoints
location: "{{ location }}"
target_resource_id: "{{ webapp.webapps[0].id }}"
ansible-playbook webapp.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
changed: [localhost]
changed: [localhost]
TASK [Add endpoint to traffic manager profile, using the web site created above]
changed: [localhost]
PLAY RECAP
localhost : ok=9 changed=6 unreachable=0 failed=0
Next steps
Tutorial: Scale apps in Azure App Service using Ansible
Tutorial: Scale apps in Azure App Service using
Ansible
5/7/2019 • 2 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure App Service enables you to build and host code. This code can be in the form of web apps, mobile backends,
and RESTful APIs. Using App Service, you can develop you code using the programming language of your choice
without managing infrastructure. App Service supports both Windows and Linux. Automated deployments from
any Git repo are supported, including GitHub and Azure DevOps.
In this tutorial, Ansible is used to:
Get facts of an existing App Service plan
Scale up the App Service plan to S2 with three workers
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Azure App Service app - If you don't have an Azure App Service app, configure an app in Azure App Service
using Ansible.
Scale up an app
There are two workflows for scaling: scale up and scale out.
Scale up: To scale up means to acquire more resources. These resources include CPU, memory, disk space, VMs,
and more. You scale up an app by changing the pricing tier of the App Service plan to which the app belongs. Scale
out: To scale out means to increase the number of VM instances that run your app. Depending on your App
Service plan pricing tier, you can scale out to as many as 20 instances. Autoscaling allows you to scale instance
count automatically based on predefined rules and schedules.
The playbook code in this section defines following operation:
Get facts of an existing App Service plan
Update the App service plan to S2 with three workers
Save the following playbook as webapp_scaleup.yml :
- hosts: localhost
connection: local
vars:
resource_group: myResourceGroup
plan_name: myAppServicePlan
location: eastus
tasks:
- name: Get facts of existing App service plan
azure_rm_appserviceplan_facts:
resource_group: "{{ resource_group }}"
name: "{{ plan_name }}"
register: facts
- debug:
var: facts.appserviceplans[0].sku
- debug:
var: facts.appserviceplans[0].sku
ansible-playbook webapp_scaleup.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
ok: [localhost]
TASK [debug]
ok: [localhost] => {
"facts.appserviceplans[0].sku": {
"capacity": 1,
"family": "S",
"name": "S1",
"size": "S1",
"tier": "Standard"
}
}
TASK [debug]
ok: [localhost] => {
"facts.appserviceplans[0].sku": {
"capacity": 3,
"family": "S",
"name": "S2",
"size": "S2",
"tier": "Standard"
}
}
PLAY RECAP
localhost : ok=6 changed=1 unreachable=0 failed=0
Next steps
Ansible on Azure
Tutorial: Configure labs in Azure DevTest Labs using
Ansible
5/7/2019 • 7 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure DevTest Labs allows developers to automate the creation of VM environments for their apps. These
environments can be configured for app developing, testing, and training.
In this tutorial, Ansible is used to:
Create a lab
Set the lab policies
Set the lab schedules
Create the lab virtual network
Define an artifact source for the lab
Create a VM within the lab
List the lab's artifact sources and artifacts
Get Azure Resource Manager information for the artifact sources
Create the lab environment
Create the lab image
Delete the lab
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
And the following task retrieves details of a specific Azure Resource Manager template from the repository:
---
- hosts: localhost
#roles:
# - azure.azure_preview_modules
vars:
resource_group: "{{ resource_group_name }}"
lab_name: myLab
vn_name: myLabVirtualNetwork
vm_name: myLabVm
artifacts_name: myArtifacts
github_token: "{{ lookup('env','GITHUB_ACCESS_TOKEN') }}"
location: eastus
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
- name:
set_fact:
artifact_source:
- source_name: "{{ artifacts_name }}"
source_path: "/Artifacts/linux-install-mongodb"
when: "github_token | length > 0"
- name:
set_fact:
artifact_source: null
when: "github_token | length == 0"
ansible-playbook devtestlab-create.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
force_delete_nonempty: yes
state: absent
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure Azure Kubernetes Service (AKS)
clusters in Azure using Ansible
5/7/2019 • 3 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Kubernetes Service (AKS ) makes it simple to deploy a managed Kubernetes cluster in Azure. AKS reduces
the complexity and operational overhead of managing Kubernetes by offloading much of that responsibility to
Azure. As a hosted Kubernetes service, Azure handles critical tasks like health monitoring and maintenance for you.
The Kubernetes masters are managed by Azure. You only manage and maintain the agent nodes. As a managed
Kubernetes service, AKS is free - you pay only for the agent nodes within your clusters; not for the masters.
AKS can be configured to use Azure Active Directory (AD ) for user authentication. Once configured, you use your
Azure AD authentication token to sign into the AKS cluster. The RBAC can be based on a user's identity or
directory group membership.
In this tutorial, Ansible is used to:
Create an AKS cluster
Configure an AKS cluster
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
ansible-playbook azure_create_aks.yml
PLAY RECAP
localhost : ok=3 changed=2 unreachable=0 failed=0
ansible-playbook azure_configure_aks.yml
PLAY RECAP
localhost : ok=2 changed=1 unreachable=0 failed=0
ansible-playbook azure_delete_aks.yml
TASK [azure_rm_aks]
PLAY RECAP
localhost : ok=2 changed=1 unreachable=0 failed=0
Next steps
Tutorial: Scale application in Azure Kubernetes Service (AKS )
Tutorial: Configure Azure CNI networking in Azure
Kubernetes Service (AKS) using Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Kubernetes Service (AKS ) makes it simple to deploy a managed Kubernetes cluster in Azure. AKS reduces
the complexity and operational overhead of managing Kubernetes by offloading much of that responsibility to
Azure. As a hosted Kubernetes service, Azure handles critical tasks like health monitoring and maintenance for you.
The Kubernetes masters are managed by Azure. You only manage and maintain the agent nodes. As a managed
Kubernetes service, AKS is free - you pay only for the agent nodes within your clusters; not for the masters.
Using AKS, you can deploy a cluster using the following network models:
Kubenet networking - Network resources are typically created and configured as the AKS cluster is deployed.
Azure CNI networking - AKS cluster is connected to existing virtual network (VNET) resources and
configurations.
For more information about networking to your applications in AKS, see Network concepts for applications in
AKS.
In this tutorial, Ansible is used to:
Create an AKS cluster
Configure Azure CNI networking
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Here are some key notes to consider when working with the sample playbook:
Use the azure_rm_aks_version module to find the supported version.
The vnet_subnet_id is the subnet created in the previous section.
The playbook loads ssh_key from ~/.ssh/id_rsa.pub . If you modify it, use the single-line format - starting
with "ssh-rsa" (without the quotes).
The client_id and client_secret values are loaded from ~/.azure/credentials , which is the default
credential file. You can set these values to your service principal or load these values from environment
variables:
---
- hosts: localhost
vars:
resource_group: aksansibletest
name: aksansibletest
location: eastus
tasks:
- name: Ensure resource group exists
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
Here are some key notes to consider when working with the sample playbook:
Change the aksansibletest value to your resource group name.
Change the aksansibletest value to your AKS name.
Change the eastus value to your resource group location.
ansible-playbook aks-azure-cni.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
ok: [localhost]
Clean up resources
When no longer needed, delete the resources created in this article.
The sample playbook code in this section is used to:
Delete a resource group referred to in the vars section.
---
- hosts: localhost
vars:
resource_group: {{ resource_group_name }}
tasks:
- name: Clean up resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
force: yes
Here are some key notes to consider when working with the sample playbook:
Replace the {{ resource_group_name }} placeholder with the name of your resource group.
All resources within the specified resource group will be deleted.
Run the playbook using the ansible-playbook command:
ansible-playbook cleanup.yml
Next steps
Tutorial: Configure Azure Active Directory in AKS using Ansible
Tutorial: Configure kubenet networking in Azure
Kubernetes Service (AKS) using Ansible
5/7/2019 • 6 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Kubernetes Service (AKS ) makes it simple to deploy a managed Kubernetes cluster in Azure. AKS reduces
the complexity and operational overhead of managing Kubernetes by offloading much of that responsibility to
Azure. As a hosted Kubernetes service, Azure handles critical tasks like health monitoring and maintenance for you.
The Kubernetes masters are managed by Azure. You only manage and maintain the agent nodes. As a managed
Kubernetes service, AKS is free - you pay only for the agent nodes within your clusters; not for the masters.
Using AKS, you can deploy a cluster using the following network models:
Kubenet networking - Network resources are typically created and configured as the AKS cluster is deployed.
Azure Container Networking Interface (CNI) networking - AKS cluster is connected to existing virtual network
resources and configurations.
For more information about networking to your applications in AKS, see Network concepts for applications in AKS.
In this tutorial, Ansible is used to:
Create an AKS cluster
Configure Azure kubenet networking
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Here are some key notes to consider when working with the sample playbook:
Use azure_rm_aks_version module to find the supported version.
The vnet_subnet_id is the subnet created in the previous section.
The network_profile defines the properties for the kubenet network plugin.
The service_cidr is used to assign internal services in the AKS cluster to an IP address. This IP address
range should be an address space that isn't used elsewhere in your network.
The dns_service_ip address should be the ".10" address of your service IP address range.
The pod_cidr should be a large address space that isn't in use elsewhere in your network environment. The
address range must be large enough to accommodate the number of nodes that you expect to scale up to.
You can't change this address range once the cluster is deployed.
The pod IP address range is used to assign a /24 address space to each node in the cluster. In the following
example, the pod_cidr of 192.168.0.0/16 assigns the first node 192.168.0.0/24, the second node
192.168.1.0/24, and the third node 192.168.2.0/24.
As the cluster scales or upgrades, Azure continues to assign a pod IP address range to each new node.
The playbook loads ssh_key from ~/.ssh/id_rsa.pub . If you modify it, use the single-line format - starting
with "ssh-rsa" (without the quotes).
The client_id and client_secret values are loaded from ~/.azure/credentials , which is the default
credential file. You can set these values to your service principal or load these values from environment
variables:
Here are some key notes to consider when working with the sample playbook:
The node_resource_group is the resource group name in which the AKS nodes are created.
The vnet_subnet_id is the subnet created in previous section.
---
- hosts: localhost
vars:
resource_group: aksansibletest
name: aksansibletest
location: eastus
tasks:
- name: Ensure resource group exist
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook aks-kubenet.yml
PLAY [localhost]
ok: [localhost]
PLAY RECAP
localhost : ok=15 changed=2 unreachable=0 failed=0 skipped=0 rescued=0
ignored=0
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
---
- hosts: localhost
vars:
resource_group: aksansibletest
tasks:
- name: Clean up resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
force: yes
In the vars section, replace the {{ resource_group_name }} placeholder with the name of your resource group.
Run the playbook using the ansible-playbook command:
ansible-playbook cleanup.yml
Next steps
Tutorial - Configure Azure Container Networking Interface (CNI) networking in AKS using Ansible
Tutorial: Configure role-based access control (RBAC)
roles in Azure Kubernetes Service (AKS) using Ansible
7/10/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Kubernetes Service (AKS ) makes it simple to deploy a managed Kubernetes cluster in Azure. AKS reduces
the complexity and operational overhead of managing Kubernetes by offloading much of that responsibility to
Azure. As a hosted Kubernetes service, Azure handles critical tasks like health monitoring and maintenance for
you. The Kubernetes masters are managed by Azure. You only manage and maintain the agent nodes. As a
managed Kubernetes service, AKS is free - you pay only for the agent nodes within your clusters; not for the
masters.
AKS can be configured to use Azure Active Directory (AD ) for user authentication. Once configured, you use your
Azure AD authentication token to sign into the AKS cluster. The RBAC can be based on a user's identity or
directory group membership.
In this tutorial, Ansible is used to:
Create an Azure AD -enabled AKS cluster
Configure an RBAC role in the cluster
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Install the RedHat OpenShift library - pip install openshift
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cluster-admins
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: <your-aad-account>
Replace the <your-aad-account> placeholder with your Azure AD tenant Object ID.
Save the following playbook - that deploys your new role to AKS - as aks-kube-deploy.yml :
In the vars section, replace the following placeholders with your Azure AD information:
<client id>
<server id>
<server secret>
<tenant id>
ansible-playbook aks-rbac.yml
The command will direct you to an authentication page. Sign in with your Azure account.
Once authenticated, kubectl lists the nodes in similar fashion to the following results:
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXX
to authenticate.
NAME STATUS ROLES AGE VERSION
aks-nodepool1-33413200-0 Ready agent 49m v1.12.6
aks-nodepool1-33413200-1 Ready agent 49m v1.12.6
aks-nodepool1-33413200-2 Ready agent 49m v1.12.6
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
---
- hosts: localhost
vars:
name: aksansibletest
resource_group: aksansibletest
tasks:
- name: Clean up resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
force: yes
- name: Remove kubeconfig
file:
state: absent
path: "aks-{{ name }}-kubeconfig"
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure a cluster in Azure HDInsight using
Ansible
5/7/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure HDInsight is a Hadoop-based analytics service for processing data. HDInsight is an ETL (extract, transform,
load) tool used to work with big data - either structured or unstructured. HDInsight supports several cluster types
where each type supports a different set of components.
In this tutorial, Ansible is used to:
Create a storage account for HDInsight
Configure a HDInsight Spark cluster.
Resize a cluster
Delete a cluster
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
vars:
resource_group: "{{ resource_group_name }}"
tasks:
- name: Prepare random prefix
set_fact:
rpfx: "{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
run_once: yes
- debug:
var: storage_output
---
- hosts: localhost
vars:
vars:
resource_group: "{{ resource_group_name }}"
tasks:
- name: Prepare random prefix
set_fact:
rpfx: "{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
run_once: yes
- hosts: localhost
#roles:
# - azure.azure_preview_modules
vars:
resource_group: "{{ resource_group_name }}"
location: eastus2
vnet_name: myVirtualNetwork
subnet_name: mySubnet
cluster_name: mycluster{{ rpfx }}
storage_account_name: mystorage{{ rpfx }}
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook hdinsight.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
force_delete_nonempty: yes
state: absent
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure queues in Azure Service Bus using
Ansible
5/7/2019 • 3 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Service Bus is an enterprise integration message broker. Service bus supports two types of communication:
queues and topics.
Queues support asynchronous communications between applications. An app sends messages to a queue, which
stores the messages. The receiving application then connects to and reads the messages from the queue.
Topics support the publish-subscribe pattern, which enables a one-to-many relationship between the message
originator and the messager receiver(s).
In this tutorial, Ansible is used to:
Create a queue
Create a SAS plicy
Retrieve namespace information
Retrieve queue information
Revoke the queue SAS policy
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
ansible-playbook servicebus_queue.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
queue: servicebustestqueue
tasks:
- name: Create a policy with send and listen priviledge
azure_rm_servicebussaspolicy:
name: "{{ queue }}-policy"
queue: "{{ queue }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
rights: listen_send
register: policy
- debug:
var: policy
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
tasks:
- name: Get a namespace's information
azure_rm_servicebus_facts:
type: namespace
name: "{{ namespace }}"
resource_group: "{{ resource_group }}"
show_sas_policies: yes
register: ns
- debug:
var: ns
ansible-playbook servicebus_namespace_info.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
queue: servicebustestqueue
tasks:
- name: Get a queue's information
azure_rm_servicebus_facts:
type: queue
name: "{{ queue }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
show_sas_policies: yes
register: queue
- debug:
var: queue
ansible-playbook servicebus_queue_info.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
queue: servicebustestqueue
tasks:
- name: Create a policy with send and listen priviledge
azure_rm_servicebussaspolicy:
name: "{{ queue }}-policy"
queue: "{{ queue }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
state: absent
ansible-playbook servicebus_queue_policy_delete.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
queue: servicebustestqueue
tasks:
- name: Delete queue
azure_rm_servicebusqueue:
name: "{{ queue }}"
resource_group: "{{ resource_group }}"
namespace: "{{ namespace }}"
state: absent
- name: Delete namespace
azure_rm_servicebus:
name: "{{ namespace }}"
resource_group: "{{ resource_group }}"
state: absent
- name: Delete resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
force_delete_nonempty: yes
ansible-playbook cleanup.yml
Next steps
Tutorial: Configure a topic in Azure Service Bus using Ansible
Tutorial: Configure topics in Azure Service Bus using
Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Service Bus is an enterprise integration message broker. Service bus supports two types of communication:
queues and topics.
Queues support asynchronous communications between applications. An app sends messages to a queue, which
stores the messages. The receiving application then connects to and reads the messages from the queue.
Topics support the publish-subscribe pattern, which enables a one-to-many relationship between the message
originator and the messager receiver(s).
In this tutorial, Ansible is used to:
Create a topic
Create a subscription
Create a SAS policy
Retrieve namespace information
Retrieve topic and subscription information
Revoke a SAS policy
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
ansible-playbook servicebus_topic.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
location: eastus
namespace: servicebustestns
topic: servicebustesttopic
subscription: servicebustestsubs
tasks:
- name: Create a subscription
azure_rm_servicebustopicsubscription:
name: "{{ subscription }}"
topic: "{{ topic }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
register: subs
- debug:
var: subs
ansible-playbook servicebus_subscription.yml
Create the SAS policy
A Shared Access Signature (SAS ) is a claims-based authorization mechanism using tokens.
The sample playbook code creates two SAS policies for a Service Bus queue with different privileges.
Save the following playbook as servicebus_topic_policy.yml :
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
topic: servicebustesttopic
tasks:
- name: Create a policy with send and listen privilege
azure_rm_servicebussaspolicy:
name: "{{ topic }}-{{ item }}"
topic: "{{ topic }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
rights: "{{ item }}"
with_items:
- send
- listen
register: policy
- debug:
var: policy
ansible-playbook servicebus_topic_policy.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
tasks:
- name: Get a namespace's information
azure_rm_servicebus_facts:
type: namespace
name: "{{ namespace }}"
resource_group: "{{ resource_group }}"
show_sas_policies: yes
register: ns
- debug:
var: ns
ansible-playbook servicebus_namespace_info.yml
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
topic: servicebustesttopic
tasks:
- name: Get a topic's information
azure_rm_servicebus_facts:
type: topic
name: "{{ topic }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
show_sas_policies: yes
register: topic_fact
- name: "List subscriptions under topic {{ topic }}"
azure_rm_servicebus_facts:
type: subscription
topic: "{{ topic }}"
namespace: "{{ namespace }}"
resource_group: "{{ resource_group }}"
register: subs_fact
- debug:
var: "{{ item }}"
with_items:
- topic_fact.servicebuses[0]
- subs_fact.servicebuses
ansible-playbook servicebus_list.yml
ansible-playbook servicebus_topic_policy_delete.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
---
- hosts: localhost
vars:
resource_group: servicebustest
namespace: servicebustestns
topic: servicebustesttopic
subscription: servicebustestsubs
tasks:
- name: Delete subscription
azure_rm_servicebustopicsubscription:
name: "{{ subscription }}"
topic: "{{ topic }}"
resource_group: "{{ resource_group }}"
namespace: "{{ namespace }}"
state: absent
- name: Delete topic
azure_rm_servicebustopic:
name: "{{ topic }}"
resource_group: "{{ resource_group }}"
namespace: "{{ namespace }}"
state: absent
- name: Delete namespace
azure_rm_servicebus:
name: "{{ namespace }}"
resource_group: "{{ resource_group }}"
state: absent
- name: Delete resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
force_delete_nonempty: yes
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure databases in Azure Database for
MySQL using Ansible
5/7/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure Database for MySQL is a relational database service based on the MySQL Community Edition. Azure
Database for MySQL enables you to manage MySQL databases in your web apps.
In this tutorial, Ansible is used to:
Create a MySql server
Create a MySql database
Configure a filewall rule so that an external app can connect to your server
Connect to your MySql server from the Azure cloud shell
Query your available MySQL servers
List all databases in your connected servers
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
vars:
resource_group: myResourceGroup
location: eastus
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook rg.yml
- hosts: localhost
vars:
resource_group: myResourceGroup
location: eastus
mysqlserver_name: mysqlserveransible
mysqldb_name: mysqldbansible
admin_username: mysqladmin
admin_password: <server_admin_password>
tasks:
- name: Create MySQL Server
azure_rm_mysqlserver:
resource_group: "{{ resource_group }}"
name: "{{ mysqlserver_name }}"
sku:
name: B_Gen5_1
tier: Basic
location: "{{ location }}"
version: 5.6
enforce_ssl: True
admin_username: "{{ admin_username }}"
admin_password: "{{ admin_password }}"
storage_mb: 51200
- name: Create instance of MySQL Database
azure_rm_mysqldatabase:
resource_group: "{{ resource_group }}"
server_name: "{{ mysqlserver_name }}"
name: "{{ mysqldb_name }}"
ansible-playbook mysql_create.yml
- hosts: localhost
vars:
resource_group: myResourceGroup
mysqlserver_name: mysqlserveransible
tasks:
- name: Open firewall to access MySQL Server from outside
azure_rm_resource:
api_version: '2017-12-01'
resource_group: "{{ resource_group }}"
provider: dbformysql
resource_type: servers
resource_name: "{{ mysqlserver_name }}"
subresource:
- type: firewallrules
name: externalaccess
body:
properties:
startIpAddress: "0.0.0.0"
endIpAddress: "255.255.255.255"
ansible-playbook mysql_firewall.yml
2. At the prompt, enter the following command to query the server status:
mysql> status
If everything goes well, you see output similar to the following results:
demo@Azure:~$ mysql -h mysqlserveransible.mysql.database.azure.com -u mysqladmin@mysqlserveransible -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 65233
Server version: 5.6.39.0 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> status
--------------
mysql Ver 14.14 Distrib 5.7.23, for Linux (x86_64) using EditLine wrapper
Threads: 5 Questions: 559 Slow queries: 0 Opens: 96 Flush tables: 3 Open tables: 10 Queries per
second avg: 0.256
--------------
ansible-playbook mysql_query.yml
After running the playbook, you see output similar to the following results:
"servers": [
{
"admin_username": "mysqladmin",
"enforce_ssl": false,
"fully_qualified_domain_name": "mysqlserveransible.mysql.database.azure.com",
"id": "/subscriptions/685ba005-af8d-4b04-8f16-
a7bf38b2eb5a/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/mysqlserveransible",
"location": "eastus",
"name": "mysqlserveransible",
"resource_group": "myResourceGroup",
"sku": {
"capacity": 1,
"family": "Gen5",
"name": "B_Gen5_1",
"tier": "Basic"
},
"storage_mb": 5120,
"user_visible_state": "Ready",
"version": "5.6"
}
]
You also see the following output for the MySQL database:
"databases": [
{
"charset": "utf8",
"collation": "utf8_general_ci",
"name": "information_schema",
"resource_group": "myResourceGroup",
"server_name": "mysqlserveransible"
},
{
"charset": "latin1",
"collation": "latin1_swedish_ci",
"name": "mysql",
"resource_group": "myResourceGroup",
"server_name": "mysqlserveransibler"
},
{
"charset": "latin1",
"collation": "latin1_swedish_ci",
"name": "mysqldbansible",
"resource_group": "myResourceGroup",
"server_name": "mysqlserveransible"
},
{
"charset": "utf8",
"collation": "utf8_general_ci",
"name": "performance_schema",
"resource_group": "myResourceGroup",
"server_name": "mysqlserveransible"
}
]
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following playbook as cleanup.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure Azure Cosmos DB accounts using
Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Cosmos DB is a database service that supports several database types. These databases types include
document, key-value, wide-column, and graph. Using Ansible, you can automate the deployment and configuration
of resources in your environment.
In this tutorial, Ansible is used to:
Create an account
Retrieve the account keys
Delete the account
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
tasks:
- name: Prepare random postfix
set_fact:
rpfx: "{{ 1000 | random }}"
run_once: yes
---
- hosts: localhost
tasks:
- name: Prepare random postfix
set_fact:
rpfx: "{{ 1000 | random }}"
run_once: yes
- hosts: localhost
# roles:
# - azure.azure_preview_modules
vars:
resource_group: "{{ resource_group_name }}"
location: eastus
vnet_name: myVirtualNetwork
subnet_name: mySubnet
cosmosdbaccount_name: cosmos{{ rpfx }}
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook cosmosdb.yml
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
- hosts: localhost
vars:
resource_group: myResourceGroup
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
force_delete_nonempty: yes
state: absent
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure caches in Azure Cache for Redis
using Ansible
5/7/2019 • 6 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure Cache for Redis is an open-source compatible service that allows you to build responsive apps by providing
fast access to data.
In this tutorial, Ansible is used to:
Create a cache
Scale a cache
Reboot a cache
Add a firewall rule to a cache
Delete a cache
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Create a cache
Create an Azure Cache for Redis within a new resource group.
It can take several minutes to provision a cache. The following code tells Ansible wait for the operation to complete:
- name: Wait for Redis provisioning to complete
azure_rm_rediscache_facts:
resource_group: "{{ resource_group }}"
name: "{{ redis_name }}"
register: facts
until: "{{ facts.rediscaches[0]['provisioning_state'] == 'Succeeded' }}"
retries: 100
delay: 60
During the lengthy provisioning process, several "error" messages will be displayed. These messages can safely be
ignored. The important message is the last message. In the following example, there are many error messages until
the final ("ok") message.
It can take several minutes to scale a cache. The following code tells Ansible wait for the operation to complete:
Similar to the task to provision Azure Cache for Redis, output like the following message is normal:
roles:
- azure.azure_preview_modules
tasks:
- name: Create resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
ansible-playbook rediscache.yml
changed: [localhost]
PLAY RECAP
localhost : ok=10 changed=4 unreachable=0 failed=0 skipped=1 rescued=0
ignored=0
ignored=0
Clean up resources
When no longer needed, delete the resources created in this article.
Save the following code as cleanup.yml :
- hosts: localhost
vars:
resource_group: "{{ resource_group_name }}"
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
state: absent
In the vars section, replace the {{ resource_group_name }} placeholder with the name of your resource group.
Run the playbook using the ansible-playbook command:
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure dynamic inventories of your Azure
resources using Ansible
5/7/2019 • 5 minutes to read • Edit Online
Ansible can be used to pull inventory information from various sources (including cloud sources such as Azure)
into a dynamic inventory.
In this tutorial, Ansible is used to:
Configure two test virtual machines.
Tag one of the virtual machines
Install Nginx on the tagged virtual machines
Configure a dynamic inventory that includes the configured Azure resources
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Azure service principal: Create a service principal, making note of the following values: appId,
displayName, password, and tenant.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
IMPORTANT
The Azure resource group you create in this step must have a name that is entirely lower-case. Otherwise, the
generation of the dynamic inventory will fail.
4. Create two Linux virtual machines on Azure using one of the following techniques:
Ansible playbook - The article, Create a basic virtual machine in Azure with Ansible illustrates how
to create a virtual machine from an Ansible playbook. If you use a playbook to define one or both of
the virtual machines, ensure that the SSH connection is used instead of a password.
Azure CLI - Issue each of the following commands in the Cloud Shell to create the two virtual
machines:
az vm create --resource-group ansible-inventory-test-rg \
--name ansible-inventory-test-vm1 \
--image UbuntuLTS --generate-ssh-keys
Tag a VM
You can use tags to organize your Azure resources by user-defined categories.
Enter the following az resource tag command to tag the virtual machine ansible-inventory-test-vm1 with the key
nginx :
wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/azure_rm.py
2. Use the chmod command to change the access permissions to the azure_rm.py script. The following
command uses the +x parameter to allow for execution (running) of the specified file ( azure_rm.py ):
chmod +x azure_rm.py
plugin: azure_rm
include_vm_resource_groups:
- ansible-inventory-test-rg
auth_source: auto
3. When running the preceding command, you could receive the following error:
Failed to connect to the host via ssh: Host key verification failed.
If you do receive the "host-key verification" error, add the following line to the Ansible configuration file. The
Ansible configuration file is located at /etc/ansible/ansible.cfg .
host_key_checking = False
4. When you run the playbook, you see results similar to the following output:
export AZURE_TAGS=nginx
You now see only one virtual machine (the one whose tag matches the value exported into the AZURE_TAGS
environment variable):
code nginx.yml
---
- name: Install and start Nginx on an Azure virtual machine
hosts: all
become: yes
tasks:
- name: install nginx
apt: pkg=nginx state=installed
notify:
- start nginx
handlers:
- name: start nginx
service: name=nginx state=started
PLAY RECAP
ansible-inventory-test-vm1 : ok=3 changed=1 unreachable=0 failed=0
2. While connected to the ansible-inventory-test-vm1 virtual machine, run the nginx -v command to
determine if Nginx is installed.
nginx -v
3. Once you run the nginx -v command, you see the Nginx version (second line) that indicates that Nginx is
installed.
tom@ansible-inventory-test-vm1:~$ nginx -v
tom@ansible-inventory-test-vm1:~$
tom@ansible-inventory-test-vm2:~$ nginx -v
The program 'nginx' can be found in the following packages:
* nginx-core
* nginx-extras
* nginx-full
* nginx-lightTry: sudo apt install <selected package>
tom@ansible-inventory-test-vm2:~$
Next steps
Quickstart: Configure Linux virtual machines in Azure using Ansible
Tutorial: Configure virtual machine scale sets in Azure
using Ansible
5/7/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure virtual machine scale sets is an Azure feature that lets you configure a group of identical, load balanced
VMs. There's no additional cost to scale sets and they're built from virtual machines. You pay only for the
underlying compute resources such as the VM instances, load balancers, or Managed Disk storage. With scale sets,
the management and automation layers are provided to run and scale your applications. You could instead
manually create and manage individual VMs. However, there are two key benefits to using scale sets. They're built
into Azure and they automatically scale your virtual machines to meet application needs.
In this tutorial, Ansible is used to:
Configure the resources for a VM
Configure a scale set
Scale the scale set by increasing it's VM instances
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
vars:
vars:
resource_group: myResourceGroup
vmss_name: myScaleSet
vmss_lb_name: myScaleSetLb
location: eastus
admin_username: azureuser
admin_password: "{{ admin_password }}"
tasks:
- name: Create a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
- name: Create virtual network
azure_rm_virtualnetwork:
resource_group: "{{ resource_group }}"
name: "{{ vmss_name }}"
address_prefixes: "10.0.0.0/16"
- name: Add subnet
azure_rm_subnet:
resource_group: "{{ resource_group }}"
name: "{{ vmss_name }}"
address_prefix: "10.0.1.0/24"
virtual_network: "{{ vmss_name }}"
- name: Create public IP address
azure_rm_publicipaddress:
resource_group: "{{ resource_group }}"
allocation_method: Static
name: "{{ vmss_name }}"
- name: Create Network Security Group that allows SSH
azure_rm_securitygroup:
resource_group: "{{ resource_group }}"
name: "{{ vmss_name }}"
rules:
- name: SSH
protocol: Tcp
destination_port_range: 22
access: Allow
priority: 1001
direction: Inbound
ansible-playbook vmss-create.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
PLAY RECAP
localhost : ok=8 changed=7 unreachable=0 failed=0
View the number of VM instances
The configured scale set currently has two instances. The following steps are used to confirm that value:
1. Sign in to the Azure portal.
2. Navigate to the scale set you configured.
3. You see the scale set name with the number of instances in parenthesis: Standard_DS1_v2 (2 instances)
4. You can also verify the number of instances with the Azure Cloud Shell by running the following command:
The results of running the Azure CLI command in Cloud Shell show that three instances now exist:
{
"capacity": 3,
}
- hosts: localhost
vars:
resource_group: myResourceGroup
vmss_name: myScaleSet
tasks:
- name: Get scaleset info
azure_rm_virtualmachine_scaleset_facts:
resource_group: "{{ resource_group }}"
name: "{{ vmss_name }}"
format: curated
register: output_scaleset
ansible-playbook vmss-scale-out.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
PLAY RECAP
localhost : ok=5 changed=1 unreachable=0 failed=0
4. You can also verify the change with the Azure Cloud Shell by running the following command:
The results of running the Azure CLI command in Cloud Shell show that three instances now exist:
{
"capacity": 3,
}
Next steps
Tutorial: Deploy apps to virtual machine scale sets in Azure using Ansible
Tutorial: Deploy apps to virtual machine scale sets in
Azure using Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure virtual machine scale sets is an Azure feature that lets you configure a group of identical, load balanced
VMs. There's no additional cost to scale sets and they're built from virtual machines. You pay only for the
underlying compute resources such as the VM instances, load balancers, or Managed Disk storage. With scale sets,
the management and automation layers are provided to run and scale your applications. You could instead
manually create and manage individual VMs. However, there are two key benefits to using scale sets. They're built
into Azure and they automatically scale your virtual machines to meet application needs.
In this tutorial, Ansible is used to:
Retrieve host information for a group of Azure VMs
Clone and build the sample app
Install the JRE (Java Runtime Environment) on a scale set
Deploy the Java application to a scale set
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Virtual machine scale set: If you don't already have a scale set, you can configure a scale set with Ansible.
git - git is used to download a Java sample used in this tutorial.
Java SE Development Kit (JDK) - The JDK is used to build the sample Java project.
Apache Maven - Apache Maven is used to build the sample Java project.
- hosts: localhost
vars:
repo_url: https://github.com/spring-guides/gs-spring-boot.git
workspace: ~/src/helloworld
tasks:
- name: Git Clone sample app
git:
repo: "{{ repo_url }}"
dest: "{{ workspace }}"
ansible-playbook app.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
PLAY RECAP
localhost : ok=3 changed=2 unreachable=0 failed=0
- hosts: localhost
vars:
resource_group: myResourceGroup
scaleset_name: myScaleSet
loadbalancer_name: myScaleSetLb
admin_username: azureuser
admin_password: "{{ admin_password }}"
tasks:
- include: get-hosts-tasks.yml
tasks:
- name: Install JRE
apt:
name: default-jre
update_cache: yes
CentOS:
In some environments, you may see an error about using an SSH password instead of a key. If you do
receive that error, you can disable host key checking by adding the following line to
/etc/ansible/ansible.cfg or ~/.ansible.cfg :
[defaults]
host_key_checking = False
ansible-playbook vmss-setup-deploy.yml
The output from running the ansible-playbook command indicates that the sample Java application has been
installed to the host group of the scale set:
PLAY [localhost]
TASK [Get facts for all Public IPs within a resource groups]
ok: [localhost]
PLAY RECAP
40.114.30.145_50000 : ok=4 changed=3 unreachable=0 failed=0
40.114.30.145_50003 : ok=4 changed=3 unreachable=0 failed=0
localhost : ok=4 changed=1 unreachable=0 failed=0
Next steps
Tutorial: Autoscale virtual machine scale sets in Azure using Ansible
Tutorial: Autoscale virtual machine scale sets in Azure
using Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.7 (or later) is required to run the sample playbooks in this article.
Azure virtual machine scale sets is an Azure feature that lets you configure a group of identical, load balanced
VMs. There's no additional cost to scale sets and they're built from virtual machines. You pay only for the
underlying compute resources such as the VM instances, load balancers, or Managed Disk storage. With scale sets,
the management and automation layers are provided to run and scale your applications. You could instead
manually create and manage individual VMs. However, there are two key benefits to using scale sets. They're built
into Azure and they automatically scale your virtual machines to meet application needs.
The feature of automatically adjusting the number of VM instances is called autoscale. The benefit of autoscale is
that it reduces the management overhead to monitor and optimize the performance of your application. Autoscale
can be configured in response to demand or on a defined schedule. Using Ansible, you can specify the autoscale
rules that define the acceptable performance for a positive customer experience.
In this tutorial, Ansible is used to:
Define an autoscale profile
Autoscale based on a recurring schedule
Autoscale based on app performance
Retrieve autoscale settings information
Disable an autoscale setting
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
Virtual machine scale set: If you don't already have a scale set, you can configure a scale set with Ansible.
---
- hosts: localhost
vars:
resource_group: myResourceGroup
vmss_name: myScaleSet
name: autoscalesetting
tasks:
- name: Create autoscaling
azure_rm_autoscale:
resource_group: "{{ resource_group }}"
name: "{{ name }}"
target:
namespace: "Microsoft.Compute"
types: "virtualMachineScaleSets"
name: "{{ vmss_name }}"
enabled: true
profiles:
- count: '3'
min_count: '3'
max_count: '3'
name: Auto created scale condition
recurrence_timezone: Pacific Standard Time
recurrence_frequency: Week
recurrence_days:
- Monday
recurrence_mins:
- '0'
recurrence_hours:
- '10'
ansible-playbook vmss-auto-scale.yml
---
- hosts: localhost
vars:
resource_group: myResourceGroup
vmss_name: myScaleSet
name: autoscalesetting
tasks:
tasks:
- name: Get facts of the resource group
azure_rm_resourcegroup_facts:
name: "{{ resource_group }}"
register: rg
ansible-playbook vmss-auto-scale-metrics.yml
- hosts: localhost
vars:
resource_group: myResourceGroup
name: autoscalesetting
tasks:
- name: Retrieve autoscale settings information
azure_rm_autoscale_facts:
resource_group: "{{ resource_group }}"
name: "{{ name }}"
register: autoscale_query
- debug:
var: autoscale_query.autoscales[0]
ansible-playbook vmss-auto-scale-get-settings.yml
- hosts: localhost
vars:
resource_group: myResourceGroup
name: autoscalesetting
tasks:
- name: Delete autoscaling
azure_rm_autoscale:
resource_group: "{{ resource_group }}"
name: "{{ name }}"
state: absent
vmss-auto-scale-delete-setting.yml
Next steps
Tutorial: Update custom image of Azure virtual machine scale sets using Ansible
Tutorial: Update the custom image of Azure virtual
machine scale sets using Ansible
5/7/2019 • 8 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure virtual machine scale sets is an Azure feature that lets you configure a group of identical, load balanced
VMs. There's no additional cost to scale sets and they're built from virtual machines. You pay only for the
underlying compute resources such as the VM instances, load balancers, or Managed Disk storage. With scale sets,
the management and automation layers are provided to run and scale your applications. You could instead
manually create and manage individual VMs. However, there are two key benefits to using scale sets. They're built
into Azure and they automatically scale your virtual machines to meet application needs.
After a VM is deployed, you configure the VM with the software your app needs. Instead of doing this
configuration task for each VM, you can create a custom image. A custom image is a snapshot of an existing VM
that includes any installed software. When you configure a scale set, you specify the image to use for that scale
set's VMs. By using a custom image, each VM instance is identically configured for your app. Sometimes, you may
need to update your scale set's custom image. That task is the focus of this tutorial.
In this tutorial, Ansible is used to:
Configure two VMs with HTTPD
Create a custom image from an existing VM
Create a scale set from an image
Update the custom image
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- debug:
msg: "Public IP Address A: {{ pip_output.results[0].state.ip_address }}"
- debug:
msg: "Public IP Address B: {{ pip_output.results[1].state.ip_address }}"
Run the playbook using the ansible-playbook command, replacing myrg with your resource group name:
Because of the debug sections of the playbook, the ansible-playbook command will print the IP address of each
VM. Copy these IP addresses for later use.
Connect to the two VMs
In this section, you connect to each VM. As mentioned in the previous section, the strings Image A and Image B
mimic having two distinct VMs with different configurations.
Using the IP addresses from the previous section, connect to both VMs:
Run the playbook using the ansible-playbook command, replacing myrg with your resource group name:
tasks:
- debug:
msg: "Scale set public IP address: {{ pip_output.state.ip_address }}"
Run the playbook using the ansible-playbook command, replacing myrg with your resource group name:
ansible-playbook create-vmss.yml --extra-vars "resource_group=myrg"
Because of the debug section of the playbook, the ansible-playbook command will print the IP address of the
scale set. Copy this IP address for later use.
Leave your browser window open as you continue to the next section.
- debug:
var: instances
Run the playbook using the ansible-playbook command, replacing myrg with your resource group name:
- hosts: localhost
vars:
resource_group: myrg
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
force_delete_nonempty: yes
state: absent
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure Azure virtual network peering
using Ansible
5/7/2019 • 5 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Virtual network (VNet) peering allows you to seamlessly connect two Azure virtual networks. Once peered, the two
virtual networks appear as one for connectivity purposes.
Traffic is routed between VMs in the same virtual network through private IP addresses. Similarly, traffic between
VMs in a peered virtual network is routed through the Microsoft backbone infrastructure. As a result, VMs in
different virtual networks can communicate with each other.
In this tutorial, Ansible is used to:
Create two virtual networks
Peer the two virtual networks
Delete the peering between the two networks
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
tasks:
- name: Prepare random postfix
set_fact:
rpfx: "{{ 1000 | random }}"
run_once: yes
ansible-playbook vnet_peering.yml
After running the playbook, you see output similar to the following results:
PLAY [localhost]
PLAY RECAP
localhost : ok=12 changed=9 unreachable=0 failed=0 skipped=0 rescued=0
ignored=0
Clean up resources
When no longer needed, delete the resources created in this article.
The sample playbook code in this section is used to:
Delete the two resources groups created earlier
Save the following playbook as cleanup.yml :
- hosts: localhost
vars:
resource_group: "{{ resource_group_name-1 }}"
resource_group_secondary: "{{ resource_group_name-2 }}"
tasks:
- name: Delete a resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
force_delete_nonempty: yes
state: absent
Here are some key notes to consider when working with the sample playbook:
Replace the {{ resource_group_name-1 }} placeholder with the name of the first resource group created.
Replace the {{ resource_group_name-2 }} placeholder with the name of the second resource group created.
All resources within the two specified resource groups will be deleted.
Run the playbook using the ansible-playbook command:
ansible-playbook cleanup.yml
Next steps
Ansible on Azure
Tutorial: Configure Azure route tables using Ansible
5/7/2019 • 4 minutes to read • Edit Online
IMPORTANT
Ansible 2.8 (or later) is required to run the sample playbooks in this article.
Azure automatically routes traffic between Azure subnets, virtual networks, and on-premises networks. If you need
more control over your environment's routing, you can create a route table.
In this tutorial, Ansible is used to:
Create a route table Create a virtual network and subnet Associate a route table with a subnet Disassociate a route
table from a subnet Create and delete routes Query a route table Delete a route table
Prerequisites
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
Install and configure Ansible on a Linux virtual machine
Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual
machine with Ansible.
- hosts: localhost
vars:
route_table_name: myRouteTable
resource_group: myResourceGroup
tasks:
- name: Create a route table
azure_rm_routetable:
name: "{{ route_table_name }}"
resource_group: "{{ resource_group }}"
ansible-playbook route_table_create.yml
- hosts: localhost
vars:
subnet_name: mySubnet
virtual_network_name: myVirtualNetwork
route_table_name: myRouteTable
resource_group: myResourceGroup
tasks:
- name: Create virtual network
azure_rm_virtualnetwork:
name: "{{ virtual_network_name }}"
resource_group: "{{ resource_group }}"
address_prefixes_cidr:
- 10.1.0.0/16
- 172.100.0.0/16
dns_servers:
- 127.0.0.1
- 127.0.0.3
- name: Create a subnet with route table
azure_rm_subnet:
name: "{{ subnet_name }}"
virtual_network_name: "{{ virtual_network_name }}"
resource_group: "{{ resource_group }}"
address_prefix_cidr: "10.1.0.0/24"
route_table: "{ route_table_name }"
ansible-playbook route_table_associate.yml
ansible-playbook route_table_dissociate.yml
Create a route
The playbook code in this section a route within a route table.
Save the following playbook as route_create.yml :
- hosts: localhost
vars:
route_name: myRoute
route_table_name: myRouteTable
resource_group: myResourceGroup
tasks:
- name: Create route
azure_rm_route:
name: "{{ route_name }}"
resource_group: "{{ resource_group }}"
next_hop_type: virtual_network_gateway
address_prefix: "10.1.0.0/16"
route_table_name: "{{ route_table_name }}"
ansible-playbook route_create.yml
Delete a route
The playbook code in this section deletes a route from a route table.
Save the following playbook as route_delete.yml :
- hosts: localhost
vars:
route_name: myRoute
route_table_name: myRouteTable
resource_group: myResourceGroup
tasks:
- name: Remove route
azure_rm_route:
name: "{{ route_name }}"
resource_group: "{{ resource_group }}"
route_table_name: "{{ route_table_name }}"
state: absent
ansible-playbook route_delete.yml
- hosts: localhost
vars:
route_table_name: myRouteTable
resource_group: myResourceGroup
tasks:
- name: Get route table information
azure_rm_routetable_facts:
resource_group: "{{ resource_group }}"
name: "{{ route_table_name }}"
register: query
- debug:
var: query.route_tables[0]
ansible-playbook route_table_facts.yml
ansible-playbook route_table_delete.yml
Next steps
Ansible on Azure
Ansible module and version matrix
5/7/2019 • 6 minutes to read • Edit Online
Ansible includes a suite of modules for use in provisioning and configuring Azure resources. These resources
include virtual machines, scale sets, networking services, and container services. This article lists the various
Ansible modules for Azure and the Ansible versions in which they ship.
ANSIBLE
MODULE FOR
AZURE ANSIBLE 2.4 ANSIBLE 2.5 ANSIBLE 2.6 ANSIBLE 2.7 ANSIBLE 2.8 ANSIBLE ROLE
Compute
Networking
azure_rm_app - - - - - Yes
gwroute
azure_rm_app - - - - - Yes
gwroute_facts
azure_rm_app - - - - - Yes
gwroutetable
azure_rm_app - - - - - Yes
gwroutetable_
facts
Storage
Web
Containers
Databases
Analytics
Integration
Security
DevOps
Azure
Monitor
Next steps
For more information about playbook roles, see Creating reusable playbooks.