Setting up Azure VM Swap using Ansible

Long story short, I was reviewing my bootstrap playbooks and realized that I could make swapfile creation a bit more generic by leveraging waagent (the Azure Linux agent).

So here’s a task file that will reconfigure waagent to set up the swap file on the local hypervisor volume (the volatile device you get for temporary data) and restart it – but ideally you should reboot the machine afterwards, which is what I do as part of my bootstrapping anyway since I usually update the kernel as well.

---

- name: set up swap
  vars:
    waagent:
      ResourceDisk.Format: y                   # Format if unformatted
      ResourceDisk.Filesystem: ext4            # Typically ext3 or ext4
      ResourceDisk.MountPoint: /mnt/resource   #
      ResourceDisk.EnableSwap: y               # Create and use swapfile
      ResourceDisk.SwapSizeMB: 2048            # Size of the swapfile
  sudo: yes
  lineinfile: dest=/etc/waagent.conf line="{{ item.key }}={{ item.value }}"
  with_dict: "{{ waagent }}"
  tags:
    - setup

- name: unmount device
  mount: 
    path: /mnt
    state: unmounted
  tags:
    - setup

- name: restart agent
  service:
    name: walinuxagent
    state: restarted
  sudo: yes
  tags:
    - setup

In the meantime, I moved this site to a new, smaller VM (an Azure B-series “burstable” VM, which costs around €3.75/m) as a sort of experiment – Cloudflare makes it trivial to deal with peak loads, but I want to stress-test a few things and test custom Azure metrics, so tightening resources makes it easier to get meaningful numbers.