Ansible: installing linux-headers matching kernel for Ubuntu

For Ubuntu, there are a couple of ways you can install the linux-headers package matching the kernel version.  You can either explicitly specify the version, or use the meta package as shown below.

# specify kernel version using subshell
sudo apt-get install -y linux-headers-$(uname -r)

# OR meta package that auto-matches kernel
sudo apt-get install linux-headers-generic

If you want to specify this in Ansible:

# specify kernel version (needs facts gathered)
- name: install headers matching kernel
  apt:
    pkg:
    - linux-headers-{{ansible_kernel}}

# OR use meta package that auto-matches kernel
- name: install headers using meta package
  apt:
    pkg:
    - linux-headers-generic

You can find my playbook in git at playbook-kernel-headers.yaml

REFERENCES

reddit.com, apt-get install for linux-headers