Alexandr
Alexandr

Reputation: 9525

Evaluation of bash commands as ansible variables

I want to create ansible equivalent of the command:

apt-get install linux-headers-$(uname -r)

Requirement: a linux-headers-$(uname -r) package must be configured via Ansible variable.

In external file a big list of packages is configured. Now packages, whose names are evaluated lazily like linux-headers-$(uname -r) must be handled via shell task individually.

I am looking for a way to get rid of such exceptions and store them in the variable list as the others.

Upvotes: 0

Views: 510

Answers (2)

Alexandr
Alexandr

Reputation: 9525

Thanks @Vladimir Botka for the pipe. Here is a solution I've implemnted based on variables, pipe and replace:

The package is described in external file as:

---
- packages:
    - name: Some Package Description,
      package: linux-headers-${pipe}
      pipe: uname -r

Playbook, we get result of pipe and replace in the package:

- name: test pipe
  debug:
    msg: "key: {{ item.package | replace('${pipe}', lookup('pipe', item.pipe)) }}"
  when: item.pipe is defined
  with_items: "{{ packages }}"

Output:

TASK [pipe] ********************************************************************
skipping: [default] => (item={u'packageList': [u'package1,', u'package2,', u'package3'], u'name': u'Some description 1,'}) 
ok: [default] => (item={u'pipe': u'uname -r', u'name': u'Some description 1,', u'package': u'linux-headers-${pipe}'}) => {
    "msg": "key: linux-headers-4.15.0-65-generic"
}

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 68144

Use pipe plugin. For example

- set_fact:
    linux_headers_pkg: "{{ 'linux-headers-' ~ lookup('pipe', 'uname -r') }}"
- debug:
    var: linux_headers_pkg

gives

"linux_headers_pkg": "linux-headers-5.0.0-31-generic"

Upvotes: 1

Related Questions