przeqpiciel
przeqpiciel

Reputation: 328

Ansible, default variable

I am creating a new role. In the default directory of role I created main.yml with below content

asterisk:
  install: yes
  branch: 16
  user: pbx
  group: pbx
  srcdir: /usr/src/asterisk/
  url: "http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-{{ asterisk.branch }}-current.tar.gz"
  url_sounds: http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-en-ulaw-current.tar.gz
  path_sound: /var/lib/asterisk/sounds/en
  mysql_support: no

Then in host_vars I create hostname.yml file which defined specific variables for this hosts with belowed content

asterisk:
  install: no

Ansible show to me error that aterisk.mysql_support is not defined. So question is, how to properly use defaults variables ?

Upvotes: 0

Views: 418

Answers (2)

KevinLH
KevinLH

Reputation: 338

In your defaults, you are defining an asterisk variable containing a structure with various key/value pairs inside. In host_vars you define a new value for that variable. It is asterisk as a whole that is replaced, not just the install property it contains. As a consequence, if you have tasks that use the other properties within asterisk without checking that they are defined first, they will fail.

So it is important when defining default values in a role to structure them in a way that makes using them easy. Is it coherent, even suitable, to force playbooks that use the role to redefine asterisk as a whole when they do not use the default value? If so, your current design is good. Otherwise, you may want to split it as define several distinct variables.

One thing that may also happen in your case (but it'd be necessary to see the tasks in the role to be sure of that), is that you do not care about the values in the other properties held by asterisk when install = no, because in that case these operations should not be performed. Make sure if that is not already the case that you use when: asterisk.install for these tasks (I think name may be evaluated even when the task is not to be executed, so beware). You could even put all the tasks to be executed when the value is yes in a separate tasks file that is conditionally included/imported.

Upvotes: 0

error404
error404

Reputation: 2823

In roles you can define the common variables in the main.yml file which will be sourced by default. All non common variables you can define in their respective yml file

Upvotes: 0

Related Questions