Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically register variables with Ansible?

Tags:

yaml

ansible

I want to define an Ansible role and register dynamic variables:

---
- name: Check for {{ package }}
  stat: path=/opt/packages/{{ package }}
  register: "{{ package | regex_replace('-', '_') }}"
- name: Install {{ package }} {{ package_version }}
  command: "custom-package-installer {{ package }} {{ package_version }}"
  when: "not {{ package | regex_replace('-', '_') }}.stat.exists"

Usage looks like this:

- include: install_package.yml package=foo package_version=1.2.3

However, Ansible doesn't recognise the conditional:

TASK: [example | Install foo 1.2.3] *********************************** 
fatal: [my-server] => error while evaluating conditional: not foo.stat.exists

FATAL: all hosts have already failed -- aborting

How can I define variables dynamically, expanding the {{ }}?

like image 864
Wilfred Hughes Avatar asked Jan 02 '15 18:01

Wilfred Hughes


2 Answers

There is no way to register a dynamic variable. There is no way for a placeholder {{ var }} in register. However there is a much cleaner way to perform what I think you are trying to achieve: Ansible: it's a fact.

Short summary:

You can write a simple script which prints JSON like:

#!/bin/python #or /bin/bash or any other executable
....

print """{ "ansible_facts": {
              "available_packages": ["a", "b", "c"]
               }
          }"""

and put it into your local facts folder on the machine (as executable script with .fact ending):

Your second task would then look like:

- name: Install {{ package }} {{ package_version }}
  command: "custom-package-installer {{ package }} {{ package_version }}"
  when: "not package in ansible_facts['available_packages']"

Ansible docs on facts.

like image 166
ProfHase85 Avatar answered Oct 04 '22 02:10

ProfHase85


You don't need a dynamic variable in this case, doing:

---
- name: Check for {{ package }}
  stat: path=/opt/packages/{{ package }}
  register: current_package

- name: Install {{ package }} {{ package_version }}
  command: "custom-package-installer {{ package }} {{ package_version }}"
  when: not current_package.stat.exists

is perfectly fine...

like image 30
Mathias Henze Avatar answered Oct 04 '22 03:10

Mathias Henze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!