1.. _playbooks_variables: 2 3*************** 4Using Variables 5*************** 6 7Ansible uses variables to manage differences between systems. With Ansible, you can execute tasks and playbooks on multiple different systems with a single command. To represent the variations among those different systems, you can create variables with standard YAML syntax, including lists and dictionaries. You can define these variables in your playbooks, in your :ref:`inventory <intro_inventory>`, in re-usable :ref:`files <playbooks_reuse>` or :ref:`roles <playbooks_reuse_roles>`, or at the command line. You can also create variables during a playbook run by registering the return value or values of a task as a new variable. 8 9After you create variables, either by defining them in a file, passing them at the command line, or registering the return value or values of a task as a new variable, you can use those variables in module arguments, in :ref:`conditional "when" statements <playbooks_conditionals>`, in :ref:`templates <playbooks_templating>`, and in :ref:`loops <playbooks_loops>`. The `ansible-examples github repository <https://github.com/ansible/ansible-examples>`_ contains many examples of using variables in Ansible. 10 11Once you understand the concepts and examples on this page, read about :ref:`Ansible facts <vars_and_facts>`, which are variables you retrieve from remote systems. 12 13.. contents:: 14 :local: 15 16.. _valid_variable_names: 17 18Creating valid variable names 19============================= 20 21Not all strings are valid Ansible variable names. A variable name can only include letters, numbers, and underscores. `Python keywords`_ or :ref:`playbook keywords<playbook_keywords>` are not valid variable names. A variable name cannot begin with a number. 22 23Variable names can begin with an underscore. In many programming languages, variables that begin with an underscore are private. This is not true in Ansible. Variables that begin with an underscore are treated exactly the same as any other variable. Do not rely on this convention for privacy or security. 24 25This table gives examples of valid and invalid variable names: 26 27.. table:: 28 :class: documentation-table 29 30 ====================== ==================================================================== 31 Valid variable names Not valid 32 ====================== ==================================================================== 33 ``foo`` ``*foo``, `Python keywords`_ such as ``async`` and ``lambda`` 34 35 ``foo_env`` :ref:`playbook keywords<playbook_keywords>` such as ``environment`` 36 37 ``foo_port`` ``foo-port``, ``foo port``, ``foo.port`` 38 39 ``foo5``, ``_foo`` ``5foo``, ``12`` 40 ====================== ==================================================================== 41 42.. _Python keywords: https://docs.python.org/3/reference/lexical_analysis.html#keywords 43 44Simple variables 45================ 46 47Simple variables combine a variable name with a single value. You can use this syntax (and the syntax for lists and dictionaries shown below) in a variety of places. For details about setting variables in inventory, in playbooks, in reusable files, in roles, or at the command line, see :ref:`setting_variables`. 48 49Defining simple variables 50------------------------- 51 52You can define a simple variable using standard YAML syntax. For example:: 53 54 remote_install_path: /opt/my_app_config 55 56Referencing simple variables 57---------------------------- 58 59After you define a variable, use Jinja2 syntax to reference it. Jinja2 variables use double curly braces. For example, the expression ``My amp goes to {{ max_amp_value }}`` demonstrates the most basic form of variable substitution. You can use Jinja2 syntax in playbooks. For example:: 60 61 ansible.builtin.template: 62 src: foo.cfg.j2 63 dest: '{{ remote_install_path }}/foo.cfg' 64 65In this example, the variable defines the location of a file, which can vary from one system to another. 66 67.. note:: 68 69 Ansible allows Jinja2 loops and conditionals in :ref:`templates <playbooks_templating>` but not in playbooks. You cannot create a loop of tasks. Ansible playbooks are pure machine-parseable YAML. 70 71.. _yaml_gotchas: 72 73When to quote variables (a YAML gotcha) 74======================================= 75 76If you start a value with ``{{ foo }}``, you must quote the whole expression to create valid YAML syntax. If you do not quote the whole expression, the YAML parser cannot interpret the syntax - it might be a variable or it might be the start of a YAML dictionary. For guidance on writing YAML, see the :ref:`yaml_syntax` documentation. 77 78If you use a variable without quotes like this:: 79 80 - hosts: app_servers 81 vars: 82 app_path: {{ base_path }}/22 83 84You will see: ``ERROR! Syntax Error while loading YAML.`` If you add quotes, Ansible works correctly:: 85 86 - hosts: app_servers 87 vars: 88 app_path: "{{ base_path }}/22" 89 90.. _list_variables: 91 92List variables 93============== 94 95A list variable combines a variable name with multiple values. The multiple values can be stored as an itemized list or in square brackets ``[]``, separated with commas. 96 97Defining variables as lists 98--------------------------- 99 100You can define variables with multiple values using YAML lists. For example:: 101 102 region: 103 - northeast 104 - southeast 105 - midwest 106 107Referencing list variables 108-------------------------- 109 110When you use variables defined as a list (also called an array), you can use individual, specific fields from that list. The first item in a list is item 0, the second item is item 1. For example:: 111 112 region: "{{ region[0] }}" 113 114The value of this expression would be "northeast". 115 116.. _dictionary_variables: 117 118Dictionary variables 119==================== 120 121A dictionary stores the data in key-value pairs. Usually, dictionaries are used to store related data, such as the information contained in an ID or a user profile. 122 123Defining variables as key:value dictionaries 124-------------------------------------------- 125 126You can define more complex variables using YAML dictionaries. A YAML dictionary maps keys to values. For example:: 127 128 foo: 129 field1: one 130 field2: two 131 132Referencing key:value dictionary variables 133------------------------------------------ 134 135When you use variables defined as a key:value dictionary (also called a hash), you can use individual, specific fields from that dictionary using either bracket notation or dot notation:: 136 137 foo['field1'] 138 foo.field1 139 140Both of these examples reference the same value ("one"). Bracket notation always works. Dot notation can cause problems because some keys collide with attributes and methods of python dictionaries. Use bracket notation if you use keys which start and end with two underscores (which are reserved for special meanings in python) or are any of the known public attributes: 141 142``add``, ``append``, ``as_integer_ratio``, ``bit_length``, ``capitalize``, ``center``, ``clear``, ``conjugate``, ``copy``, ``count``, ``decode``, ``denominator``, ``difference``, ``difference_update``, ``discard``, ``encode``, ``endswith``, ``expandtabs``, ``extend``, ``find``, ``format``, ``fromhex``, ``fromkeys``, ``get``, ``has_key``, ``hex``, ``imag``, ``index``, ``insert``, ``intersection``, ``intersection_update``, ``isalnum``, ``isalpha``, ``isdecimal``, ``isdigit``, ``isdisjoint``, ``is_integer``, ``islower``, ``isnumeric``, ``isspace``, ``issubset``, ``issuperset``, ``istitle``, ``isupper``, ``items``, ``iteritems``, ``iterkeys``, ``itervalues``, ``join``, ``keys``, ``ljust``, ``lower``, ``lstrip``, ``numerator``, ``partition``, ``pop``, ``popitem``, ``real``, ``remove``, ``replace``, ``reverse``, ``rfind``, ``rindex``, ``rjust``, ``rpartition``, ``rsplit``, ``rstrip``, ``setdefault``, ``sort``, ``split``, ``splitlines``, ``startswith``, ``strip``, ``swapcase``, ``symmetric_difference``, ``symmetric_difference_update``, ``title``, ``translate``, ``union``, ``update``, ``upper``, ``values``, ``viewitems``, ``viewkeys``, ``viewvalues``, ``zfill``. 143 144.. _registered_variables: 145 146Registering variables 147===================== 148 149You can create variables from the output of an Ansible task with the task keyword ``register``. You can use registered variables in any later tasks in your play. For example:: 150 151 - hosts: web_servers 152 153 tasks: 154 155 - name: Run a shell command and register its output as a variable 156 ansible.builtin.shell: /usr/bin/foo 157 register: foo_result 158 ignore_errors: true 159 160 - name: Run a shell command using output of the previous task 161 ansible.builtin.shell: /usr/bin/bar 162 when: foo_result.rc == 5 163 164For more examples of using registered variables in conditions on later tasks, see :ref:`playbooks_conditionals`. Registered variables may be simple variables, list variables, dictionary variables, or complex nested data structures. The documentation for each module includes a ``RETURN`` section describing the return values for that module. To see the values for a particular task, run your playbook with ``-v``. 165 166Registered variables are stored in memory. You cannot cache registered variables for use in future plays. Registered variables are only valid on the host for the rest of the current playbook run. 167 168Registered variables are host-level variables. When you register a variable in a task with a loop, the registered variable contains a value for each item in the loop. The data structure placed in the variable during the loop will contain a ``results`` attribute, that is a list of all responses from the module. For a more in-depth example of how this works, see the :ref:`playbooks_loops` section on using register with a loop. 169 170.. note:: If a task fails or is skipped, Ansible still registers a variable with a failure or skipped status, unless the task is skipped based on tags. See :ref:`tags` for information on adding and using tags. 171 172.. _accessing_complex_variable_data: 173 174Referencing nested variables 175============================ 176 177Many registered variables (and :ref:`facts <vars_and_facts>`) are nested YAML or JSON data structures. You cannot access values from these nested data structures with the simple ``{{ foo }}`` syntax. You must use either bracket notation or dot notation. For example, to reference an IP address from your facts using the bracket notation:: 178 179 {{ ansible_facts["eth0"]["ipv4"]["address"] }} 180 181To reference an IP address from your facts using the dot notation:: 182 183 {{ ansible_facts.eth0.ipv4.address }} 184 185.. _about_jinja2: 186.. _jinja2_filters: 187 188Transforming variables with Jinja2 filters 189========================================== 190 191Jinja2 filters let you transform the value of a variable within a template expression. For example, the ``capitalize`` filter capitalizes any value passed to it; the ``to_yaml`` and ``to_json`` filters change the format of your variable values. Jinja2 includes many `built-in filters <https://jinja.palletsprojects.com/templates/#builtin-filters>`_ and Ansible supplies many more filters. To find more examples of filters, see :ref:`playbooks_filters`. 192 193.. _setting_variables: 194 195Where to set variables 196====================== 197 198You can define variables in a variety of places, such as in inventory, in playbooks, in reusable files, in roles, and at the command line. Ansible loads every possible variable it finds, then chooses the variable to apply based on :ref:`variable precedence rules <ansible_variable_precedence>`. 199 200.. _define_variables_in_inventory: 201 202Defining variables in inventory 203------------------------------- 204 205You can define different variables for each individual host, or set shared variables for a group of hosts in your inventory. For example, if all machines in the ``[Boston]`` group use 'boston.ntp.example.com' as an NTP server, you can set a group variable. The :ref:`intro_inventory` page has details on setting :ref:`host variables <host_variables>` and :ref:`group variables <group_variables>` in inventory. 206 207.. _playbook_variables: 208 209Defining variables in a play 210---------------------------- 211 212You can define variables directly in a playbook play:: 213 214 - hosts: webservers 215 vars: 216 http_port: 80 217 218When you define variables in a play, they are only visible to tasks executed in that play. 219 220.. _included_variables: 221.. _variable_file_separation_details: 222 223Defining variables in included files and roles 224---------------------------------------------- 225 226You can define variables in reusable variables files and/or in reusable roles. When you define variables in reusable variable files, the sensitive variables are separated from playbooks. This separation enables you to store your playbooks in a source control software and even share the playbooks, without the risk of exposing passwords or other sensitive and personal data. For information about creating reusable files and roles, see :ref:`playbooks_reuse`. 227 228This example shows how you can include variables defined in an external file:: 229 230 --- 231 232 - hosts: all 233 remote_user: root 234 vars: 235 favcolor: blue 236 vars_files: 237 - /vars/external_vars.yml 238 239 tasks: 240 241 - name: This is just a placeholder 242 ansible.builtin.command: /bin/echo foo 243 244The contents of each variables file is a simple YAML dictionary. For example:: 245 246 --- 247 # in the above example, this would be vars/external_vars.yml 248 somevar: somevalue 249 password: magic 250 251.. note:: 252 You can keep per-host and per-group variables in similar files. To learn about organizing your variables, see :ref:`splitting_out_vars`. 253 254.. _passing_variables_on_the_command_line: 255 256Defining variables at runtime 257----------------------------- 258 259You can define variables when you run your playbook by passing variables at the command line using the ``--extra-vars`` (or ``-e``) argument. You can also request user input with a ``vars_prompt`` (see :ref:`playbooks_prompts`). When you pass variables at the command line, use a single quoted string, that contains one or more variables, in one of the formats below. 260 261key=value format 262^^^^^^^^^^^^^^^^ 263 264Values passed in using the ``key=value`` syntax are interpreted as strings. Use the JSON format if you need to pass non-string values such as Booleans, integers, floats, lists, and so on. 265 266.. code-block:: text 267 268 ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo" 269 270JSON string format 271^^^^^^^^^^^^^^^^^^ 272 273.. code-block:: text 274 275 ansible-playbook release.yml --extra-vars '{"version":"1.23.45","other_variable":"foo"}' 276 ansible-playbook arcade.yml --extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}' 277 278When passing variables with ``--extra-vars``, you must escape quotes and other special characters appropriately for both your markup (for example, JSON), and for your shell:: 279 280 ansible-playbook arcade.yml --extra-vars "{\"name\":\"Conan O\'Brien\"}" 281 ansible-playbook arcade.yml --extra-vars '{"name":"Conan O'\\\''Brien"}' 282 ansible-playbook script.yml --extra-vars "{\"dialog\":\"He said \\\"I just can\'t get enough of those single and double-quotes"\!"\\\"\"}" 283 284If you have a lot of special characters, use a JSON or YAML file containing the variable definitions. 285 286vars from a JSON or YAML file 287^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 288 289.. code-block:: text 290 291 ansible-playbook release.yml --extra-vars "@some_file.json" 292 293 294.. _ansible_variable_precedence: 295 296Variable precedence: Where should I put a variable? 297=================================================== 298 299You can set multiple variables with the same name in many different places. When you do this, Ansible loads every possible variable it finds, then chooses the variable to apply based on variable precedence. In other words, the different variables will override each other in a certain order. 300 301Teams and projects that agree on guidelines for defining variables (where to define certain types of variables) usually avoid variable precedence concerns. We suggest that you define each variable in one place: figure out where to define a variable, and keep it simple. For examples, see :ref:`variable_examples`. 302 303Some behavioral parameters that you can set in variables you can also set in Ansible configuration, as command-line options, and using playbook keywords. For example, you can define the user Ansible uses to connect to remote devices as a variable with ``ansible_user``, in a configuration file with ``DEFAULT_REMOTE_USER``, as a command-line option with ``-u``, and with the playbook keyword ``remote_user``. If you define the same parameter in a variable and by another method, the variable overrides the other setting. This approach allows host-specific settings to override more general settings. For examples and more details on the precedence of these various settings, see :ref:`general_precedence_rules`. 304 305Understanding variable precedence 306--------------------------------- 307 308Ansible does apply variable precedence, and you might have a use for it. Here is the order of precedence from least to greatest (the last listed variables override all other variables): 309 310 #. command line values (for example, ``-u my_user``, these are not variables) 311 #. role defaults (defined in role/defaults/main.yml) [1]_ 312 #. inventory file or script group vars [2]_ 313 #. inventory group_vars/all [3]_ 314 #. playbook group_vars/all [3]_ 315 #. inventory group_vars/* [3]_ 316 #. playbook group_vars/* [3]_ 317 #. inventory file or script host vars [2]_ 318 #. inventory host_vars/* [3]_ 319 #. playbook host_vars/* [3]_ 320 #. host facts / cached set_facts [4]_ 321 #. play vars 322 #. play vars_prompt 323 #. play vars_files 324 #. role vars (defined in role/vars/main.yml) 325 #. block vars (only for tasks in block) 326 #. task vars (only for the task) 327 #. include_vars 328 #. set_facts / registered vars 329 #. role (and include_role) params 330 #. include params 331 #. extra vars (for example, ``-e "user=my_user"``)(always win precedence) 332 333In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope. Variables in the defaults folder inside a role are easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in the namespace. Host and/or inventory variables override role defaults, but explicit includes such as the vars directory or an ``include_vars`` task override inventory variables. 334 335Ansible merges different variables set in inventory so that more specific settings override more generic settings. For example, ``ansible_ssh_user`` specified as a group_var is overridden by ``ansible_user`` specified as a host_var. For details about the precedence of variables set in inventory, see :ref:`how_we_merge`. 336 337.. rubric:: Footnotes 338 339.. [1] Tasks in each role see their own role's defaults. Tasks defined outside of a role see the last role's defaults. 340.. [2] Variables defined in inventory file or provided by dynamic inventory. 341.. [3] Includes vars added by 'vars plugins' as well as host_vars and group_vars which are added by the default vars plugin shipped with Ansible. 342.. [4] When created with set_facts's cacheable option, variables have the high precedence in the play, 343 but are the same as a host facts precedence when they come from the cache. 344 345.. note:: Within any section, redefining a var overrides the previous instance. 346 If multiple groups have the same variable, the last one loaded wins. 347 If you define a variable twice in a play's ``vars:`` section, the second one wins. 348.. note:: The previous describes the default config ``hash_behaviour=replace``, switch to ``merge`` to only partially overwrite. 349 350.. _variable_scopes: 351 352Scoping variables 353----------------- 354 355You can decide where to set a variable based on the scope you want that value to have. Ansible has three main scopes: 356 357 * Global: this is set by config, environment variables and the command line 358 * Play: each play and contained structures, vars entries (vars; vars_files; vars_prompt), role defaults and vars. 359 * Host: variables directly associated to a host, like inventory, include_vars, facts or registered task outputs 360 361Inside a template, you automatically have access to all variables that are in scope for a host, plus any registered variables, facts, and magic variables. 362 363.. _variable_examples: 364 365Tips on where to set variables 366------------------------------ 367 368You should choose where to define a variable based on the kind of control you might want over values. 369 370Set variables in inventory that deal with geography or behavior. Since groups are frequently the entity that maps roles onto hosts, you can often set variables on the group instead of defining them on a role. Remember: child groups override parent groups, and host variables override group variables. See :ref:`define_variables_in_inventory` for details on setting host and group variables. 371 372Set common defaults in a ``group_vars/all`` file. See :ref:`splitting_out_vars` for details on how to organize host and group variables in your inventory. Group variables are generally placed alongside your inventory file, but they can also be returned by dynamic inventory (see :ref:`intro_dynamic_inventory`) or defined in AWX or on :ref:`ansible_platform` from the UI or API:: 373 374 --- 375 # file: /usr/local/etc/ansible/group_vars/all 376 # this is the site wide default 377 ntp_server: default-time.example.com 378 379Set location-specific variables in ``group_vars/my_location`` files. All groups are children of the ``all`` group, so variables set here override those set in ``group_vars/all``:: 380 381 --- 382 # file: /usr/local/etc/ansible/group_vars/boston 383 ntp_server: boston-time.example.com 384 385If one host used a different NTP server, you could set that in a host_vars file, which would override the group variable:: 386 387 --- 388 # file: /usr/local/etc/ansible/host_vars/xyz.boston.example.com 389 ntp_server: override.example.com 390 391Set defaults in roles to avoid undefined-variable errors. If you share your roles, other users can rely on the reasonable defaults you added in the ``roles/x/defaults/main.yml`` file, or they can easily override those values in inventory or at the command line. See :ref:`playbooks_reuse_roles` for more info. For example:: 392 393 --- 394 # file: roles/x/defaults/main.yml 395 # if no other value is supplied in inventory or as a parameter, this value will be used 396 http_port: 80 397 398Set variables in roles to ensure a value is used in that role, and is not overridden by inventory variables. If you are not sharing your role with others, you can define app-specific behaviors like ports this way, in ``roles/x/vars/main.yml``. If you are sharing roles with others, putting variables here makes them harder to override, although they still can by passing a parameter to the role or setting a variable with ``-e``:: 399 400 --- 401 # file: roles/x/vars/main.yml 402 # this will absolutely be used in this role 403 http_port: 80 404 405Pass variables as parameters when you call roles for maximum clarity, flexibility, and visibility. This approach overrides any defaults that exist for a role. For example:: 406 407 roles: 408 - role: apache 409 vars: 410 http_port: 8080 411 412When you read this playbook it is clear that you have chosen to set a variable or override a default. You can also pass multiple values, which allows you to run the same role multiple times. See :ref:`run_role_twice` for more details. For example:: 413 414 roles: 415 - role: app_user 416 vars: 417 myname: Ian 418 - role: app_user 419 vars: 420 myname: Terry 421 - role: app_user 422 vars: 423 myname: Graham 424 - role: app_user 425 vars: 426 myname: John 427 428Variables set in one role are available to later roles. You can set variables in a ``roles/common_settings/vars/main.yml`` file and use them in other roles and elsewhere in your playbook:: 429 430 roles: 431 - role: common_settings 432 - role: something 433 vars: 434 foo: 12 435 - role: something_else 436 437.. note:: There are some protections in place to avoid the need to namespace variables. 438 In this example, variables defined in 'common_settings' are available to 'something' and 'something_else' tasks, but tasks in 'something' have foo set at 12, even if 'common_settings' sets foo to 20. 439 440Instead of worrying about variable precedence, we encourage you to think about how easily or how often you want to override a variable when deciding where to set it. If you are not sure what other variables are defined, and you need a particular value, use ``--extra-vars`` (``-e``) to override all other variables. 441 442Using advanced variable syntax 443============================== 444 445For information about advanced YAML syntax used to declare variables and have more control over the data placed in YAML files used by Ansible, see :ref:`playbooks_advanced_syntax`. 446 447.. seealso:: 448 449 :ref:`about_playbooks` 450 An introduction to playbooks 451 :ref:`playbooks_conditionals` 452 Conditional statements in playbooks 453 :ref:`playbooks_filters` 454 Jinja2 filters and their uses 455 :ref:`playbooks_loops` 456 Looping in playbooks 457 :ref:`playbooks_reuse_roles` 458 Playbook organization by roles 459 :ref:`playbooks_best_practices` 460 Tips and tricks for playbooks 461 :ref:`special_variables` 462 List of special variables 463 `User Mailing List <https://groups.google.com/group/ansible-devel>`_ 464 Have a question? Stop by the google group! 465 `irc.libera.chat <https://libera.chat/>`_ 466 #ansible IRC chat channel 467