Reputation: 1562
Concerning: Ansible-Playbooks
Is it possible to run a command on the remote machine and store the resulting output into a variable? I am trying to get the kernel version and install the matching headers like this:
---
- hosts: all
tasks:
- name: install headers
become: yes
become_method: sudo
apt:
name: "{{ packages }}"
vars:
packages:
- linux-headers-`uname -r`
#- a lot of other packages here
Unfortunately uname -r
is not executed here.
I am aware of this question: Ansible: Store command's stdout in new variable? But it looks like this is another topic.
Upvotes: 0
Views: 1241
Reputation: 1954
By definition:
Ansible facts are data related to your remote systems, including operating systems, IP addresses, attached filesystems, and more.
In this link you can see all ansible facts that you can use. https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html
One of those variables is ansible_kernel
, this is the version of the kernel of your remote system. By default ansible gets this variables, but if you want to be sure that ansible will get this variables you have to use gather_facts: yes
.
---
- hosts: all
gather_facts: yes
tasks:
- name: install
become: yes
become_method: sudo
apt:
name: "{{ packages }}"
vars:
packages:
- linux-headers-{{ ansible_kernel }}
Upvotes: 3
Reputation: 1562
I found a solution but I am not sure if this is really elegant
---
- hosts: all
tasks:
- name: Getting Kernel Version
command: "uname -r"
register: kernel_version
- name: install
become: yes
become_method: sudo
apt:
name: "{{ packages }}"
vars:
packages:
- linux-headers-{{ kernel_version.stdout }}
Upvotes: 0