user2490003
user2490003

Reputation: 11900

Interpolating a shell command into an ansible command string

Say I have the following ansible command that adds the docker repository to apt

- name: Add Docker Repository
  apt_repository:
    repo: deb https://download.docker.com/linux/ubuntu xenial stable
    state: present

I'd love the command to automatically determine the version since I might not always run this on xenial. So I tried the following:

- name: Add Docker Repository
  apt_repository:
    repo: deb https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable
    state: present

But I get an error: E:Failed to fetch https://download.docker.com/linux/ubuntu/dists/$(lsb_release/-cs)/binary-amd64/Packages 404 Not Found

What's the right way to escape the$(..) so that it evaluates correctly in bash before the command is executed?

Upvotes: 1

Views: 384

Answers (2)

Mohamed Assaker
Mohamed Assaker

Reputation: 53

According to this collection link, you can use {{lookup('pipe', 'command')}}. It returns the stdout from command.

For example:

- name: Install Docker-Compose
  get_url:
    url: "https://github.com/docker/compose/releases/download/v2.24.7/docker-compose-{{lookup('pipe', 'uname -s')}}-{{lookup('pipe', 'uname -m')}}"
    dest: /usr/local/bin/docker-compose
    mode: +x

In your case:

- name: Add Docker Repository
  apt_repository:
    repo: deb https://download.docker.com/linux/ubuntu {{lookup('pipe', 'lsb_release -cs')}} stable
    state: present

Upvotes: 1

Bubzsan
Bubzsan

Reputation: 351

What you could do is have a previous task that registers the output from "lsb_release -cs" and saves that in a variable:

- name: Register Ubuntu version
  command: lsb_release -cs
  register: your_variable_name

To access the value simply look for the your_variable_name.stdout, like so:

- name: Add Docker Repository
  apt_repository:
    repo: deb https://download.docker.com/linux/ubuntu {{ your_variable_name.stdout }} stable
    state: present

If you'd like to see every detail about that variable:

- name: Inspect variable
  debug:
    var: your_variable_name

Edit: Just beware of the formatting on your url string, my answer is just an example, you may have to trim some whitespaces or add some "/" to achieve what you want ^^

Upvotes: 4

Related Questions