- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How can I write variables inside the tasks file in ansible
I have this play.yml
My apache.yml file looks like this:
This is giving me an error.
If I remove vars then it works. But, I want to keep the variable inside the included tasks file, so that I can keep different variables for different tasks separate.
6 Answers 6
NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.
Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.
ORIGINAL ANSWER
Use set_fact before your task to set facts which seem interchangeable with variables:
See http://docs.ansible.com/set_fact_module.html for the official word.

- 1 It seems to be a better solution since you can use the fact as a variable. – douglaslps Feb 13, 2015 at 12:29
- 14 Note this subtle difference compared with variables: This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will survive between plays. – rrauenza Oct 7, 2015 at 16:13
- 9 Sidenote: it seems, that you can't change a variable in place using set_fact ... so if the the name is already taken by a variable it won't modify that... which can be error prone to setting a variable to the same name on a higher level of a playbook. So be sure you won't do that (e.g. use a potentially unique name for example, not 'item'). – masu Jun 30, 2016 at 10:38
- 4 Note on your note... Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set. -- This isn't strictly true. You can overwrite a fact created with set_fact in an earlier task, you just can't overwrite a variable set in any other way... As an example, if you loop through a set of tasks, and at the start of each loop iteration you use set_fact: loop_item='{{ item }}' , then use debug: msg='{{ loop_item }}' , you'll see the fact changes with each loop iteration. – Jack_Hu Mar 28, 2019 at 2:46
Just move the variable definition inside inside your task:
Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:
You can also look at roles as a way of separating tasks depending on the different roles roles . This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2 .
- 1 I thought register only worked with output from a command? How can I make a static variable in a role's roles/<role>/tasks/main.yml ? – ThorSummoner Mar 5, 2015 at 22:15
- @ThorSummoner you mean this like a regular variable? docs.ansible.com/… and maybe this? docs.ansible.com/playbooks_roles.html#role-default-variables – Rico Mar 10, 2015 at 22:04
- 1 This solution is a total overkill. U send the var value over ssh to the remote host then retrieve it back, to use it locally on the control node!! – Samha' Nov 5, 2019 at 2:53
In Your example, apache.yml is tasklist, but not playbook
In depends on desired architecture, You can do one of:
Convert apache.yml to role. Then define tasks in roles/apache/tasks/mail.yml and variables in roles/apache/defaults/mail.yml (vars in defaults can be overriden when role applied)
Set vars in play.yml playbook
If you need to have local variables that only persist through specific task, you can do this:
This can be useful, when you want to have more reusable roles, where it expects some generic variables (arguments). For example:
my_debug_role/main.yml :
Then in your playbook, you can reuse it with more specific variable, like:
my_playbook.yml :
- For ansible 2.9.6 these approach - name: My Task vars: my_var: 123 gives me an error: ERROR! no module/action detected in task. – Vasiliy Fateev Aug 12, 2022 at 12:22
Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:
The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.
So you must quote the argument like so:

- 1 This is true, but it doesn't answer the question. – james.garriss Nov 8, 2019 at 12:25
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged ansible or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Surly Straggler vs. other types of steel frames
- Copyright issues when journal is defunct
- Knocking Out Zombies
- What did Ctrl+NumLock do?
- Do roots of these polynomials approach the negative of the Euler-Mascheroni constant?
- Recovering from a blunder I made while emailing a professor
- Counting Letters in a String
- Did this satellite streak past the Hubble Space Telescope so close that it was out of focus? If so, how close was it?
- How can I check before my flight that the cloud separation requirements in VFR flight rules are met?
- Is the God of a monotheism necessarily omnipotent?
- Minimising the environmental effects of my dyson brain
- Tips for golfing in SVG
- Can I tell police to wait and call a lawyer when served with a search warrant?
- Why are all monasteries human?
- Rolling cube on an infinite chessboard
- Is there a solution to add special characters from software and how to do it
- Linear regulator thermal information missing in datasheet
- base table view not found
- Seal script identification/translation
- Does there exist a square root of Euler-Lagrange equations of a field? (Factorization)
- Are there tables of wastage rates for different fruit and veg?
- Trying to understand how to get this basic Fourier Series
- How to tell which packages are held back due to phased updates
- Identify those arcade games from a 1983 Brazilian music video
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- AnsibleFest
- Webinars & Training

- Docs »
- User Guide »
- Working With Playbooks »
- Using Variables
- Edit on GitHub
For community users, you are reading an unmaintained version of the Ansible documentation. Unmaintained Ansible versions can contain unfixed security vulnerabilities (CVE). Please upgrade to a maintained version. See the latest Ansible community documentation . For Red Hat customers, see the Red Hat AAP platform lifecycle .
Using Variables ¶
Creating valid variable names
Defining variables in inventory
Defining variables in a playbook
Defining variables in included files and roles
Using variables with Jinja2
Transforming variables with Jinja2 filters
Hey wait, a YAML gotcha
Variables discovered from systems: Facts
Disabling facts
Local facts (facts.d)
Ansible version
Caching Facts
Registering variables
Accessing complex variable data
Accessing information about other hosts with magic variables
Defining variables in files
Passing variables on the command line
Variable precedence: Where should I put a variable?
Scoping variables
Examples of where to set a variable
Using advanced variable syntax
While automation exists to make it easier to make things repeatable, all systems are not exactly alike; some may require configuration that is slightly different from others. In some instances, the observed behavior or state of one system might influence how you configure other systems. For example, you might need to find out the IP address of a system and use it as a configuration value on another system.
Ansible uses variables to help deal with differences between systems.
To understand variables you’ll also want to read Conditionals and Loops . Useful things like the group_by module and the when conditional can also be used with variables, and to help manage differences between systems.
The ansible-examples github repository contains many examples of how variables are used in Ansible.
Creating valid variable names ¶
Before you start using variables, it’s important to know what are valid variable names.
Variable names should be letters, numbers, and underscores. Variables should always start with a letter.
foo_port is a great variable. foo5 is fine too.
foo-port , foo port , foo.port and 12 are not valid variable names.
YAML also supports dictionaries which map keys to values. For instance:
You can then reference a specific field in the dictionary using either bracket notation or dot notation:
These will both reference the same value (“one”). However, if you choose to use dot notation be aware that some keys can cause problems because they collide with attributes and methods of python dictionaries. You should use bracket notation instead of dot notation if you use keys which start and end with two underscores (Those are reserved for special meanings in python) or are any of the known public attributes:
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 .
Defining variables in inventory ¶
Often you’ll want to set variables for an individual host, or for a group of hosts in your inventory. For instance, machines in Boston may all use ‘boston.ntp.example.com’ as an NTP server. The How to build your inventory page has details on setting Assigning a variable to one machine: host variables and Assigning a variable to many machines: group variables in inventory.
Defining variables in a playbook ¶
You can define variables directly in a playbook:
This can be nice as it’s right there when you are reading the playbook.
Defining variables in included files and roles ¶
As described in Roles , variables can also be included in the playbook via include files, which may or may not be part of an Ansible Role. Usage of roles is preferred as it provides a nice organizational system.
Using variables with Jinja2 ¶
Once you’ve defined variables, you can use them in your playbooks using the Jinja2 templating system. Here’s a simple Jinja2 template:
This expression provides the most basic form of variable substitution.
You can use the same syntax in playbooks. For example:
Here the variable defines the location of a file, which can vary from one system to another.
Inside a template you automatically have access to all variables that are in scope for a host. Actually it’s more than that – you can also read variables about other hosts. We’ll show how to do that in a bit.
ansible allows Jinja2 loops and conditionals in templates, but in playbooks, we do not use them. Ansible playbooks are pure machine-parseable YAML. This is a rather important feature as it means it is possible to code-generate pieces of files, or to have other ecosystem tools read Ansible files. Not everyone will need this but it can unlock possibilities.
More information about Jinja2 templating
Transforming variables with Jinja2 filters ¶
Jinja2 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 and Ansible supplies many more filters .
Hey wait, a YAML gotcha ¶
YAML syntax requires that if you start a value with {{ foo }} you quote the whole line, since it wants to be sure you aren’t trying to start a YAML dictionary. This is covered on the YAML Syntax documentation.
This won’t work:
Do it like this and you’ll be fine:
Variables discovered from systems: Facts ¶
There are other places where variables can come from, but these are a type of variable that are discovered, not set by the user.
Facts are information derived from speaking with your remote systems. You can find a complete set under the ansible_facts variable, most facts are also ‘injected’ as top level variables preserving the ansible_ prefix, but some are dropped due to conflicts. This can be disabled via the INJECT_FACTS_AS_VARS setting.
An example of this might be the IP address of the remote host, or what the operating system is.
To see what information is available, try the following in a play:
To see the ‘raw’ information as gathered:
This will return a large amount of variable data, which may look like this on Ansible 2.7:
In the above the model of the first disk may be referenced in a template or playbook as:
Similarly, the hostname as the system reports it is:
Facts are frequently used in conditionals (see Conditionals ) and also in templates.
Facts can be also used to create dynamic groups of hosts that match particular criteria, see the Importing Modules documentation on group_by for details, as well as in generalized conditional statements as discussed in the Conditionals chapter.
Disabling facts ¶
If you know you don’t need any fact data about your hosts, and know everything about your systems centrally, you can turn off fact gathering. This has advantages in scaling Ansible in push mode with very large numbers of systems, mainly, or if you are using Ansible on experimental platforms. In any play, just do this:
Local facts (facts.d) ¶
New in version 1.3.
As discussed in the playbooks chapter, Ansible facts are a way of getting data about remote systems for use in playbook variables.
Usually these are discovered automatically by the setup module in Ansible. Users can also write custom facts modules, as described in the API guide. However, what if you want to have a simple way to provide system or user provided data for use in Ansible variables, without writing a fact module?
“Facts.d” is one mechanism for users to control some aspect of how their systems are managed.
Perhaps “local facts” is a bit of a misnomer, it means “locally supplied user values” as opposed to “centrally supplied user values”, or what facts are – “locally dynamically determined values”.
If a remotely managed system has an /etc/ansible/facts.d directory, any files in this directory ending in .fact , can be JSON, INI, or executable files returning JSON, and these can supply local facts in Ansible. An alternate directory can be specified using the fact_path play keyword.
For example, assume /etc/ansible/facts.d/preferences.fact contains:
This will produce a hash variable fact named general with asdf and bar as members. To validate this, run the following:
And you will see the following fact added:
And this data can be accessed in a template/playbook as:
The local namespace prevents any user supplied fact from overriding system facts or variables defined elsewhere in the playbook.
The key part in the key=value pairs will be converted into lowercase inside the ansible_local variable. Using the example above, if the ini file contained XYZ=3 in the [general] section, then you should expect to access it as: {{ ansible_local['preferences']['general']['xyz'] }} and not {{ ansible_local['preferences']['general']['XYZ'] }} . This is because Ansible uses Python’s ConfigParser which passes all option names through the optionxform method and this method’s default implementation converts option names to lower case.
If you have a playbook that is copying over a custom fact and then running it, making an explicit call to re-run the setup module can allow that fact to be used during that particular play. Otherwise, it will be available in the next play that gathers fact information. Here is an example of what that might look like:
In this pattern however, you could also write a fact module as well, and may wish to consider this as an option.
Ansible version ¶
New in version 1.8.
To adapt playbook behavior to specific version of ansible, a variable ansible_version is available, with the following structure:
Caching Facts ¶
As shown elsewhere in the docs, it is possible for one server to reference variables about another, like so:
With “Fact Caching” disabled, in order to do this, Ansible must have already talked to ‘asdf.example.com’ in the current play, or another play up higher in the playbook. This is the default configuration of ansible.
To avoid this, Ansible 1.8 allows the ability to save facts between playbook runs, but this feature must be manually enabled. Why might this be useful?
With a very large infrastructure with thousands of hosts, fact caching could be configured to run nightly. Configuration of a small set of servers could run ad-hoc or periodically throughout the day. With fact caching enabled, it would not be necessary to “hit” all servers to reference variables and information about them.
With fact caching enabled, it is possible for machine in one group to reference variables about machines in the other group, despite the fact that they have not been communicated with in the current execution of /usr/bin/ansible-playbook.
To benefit from cached facts, you will want to change the gathering setting to smart or explicit or set gather_facts to False in most plays.
Currently, Ansible ships with two persistent cache plugins: redis and jsonfile.
To configure fact caching using redis, enable it in ansible.cfg as follows:
To get redis up and running, perform the equivalent OS commands:
Note that the Python redis library should be installed from pip, the version packaged in EPEL is too old for use by Ansible.
In current embodiments, this feature is in beta-level state and the Redis plugin does not support port or password configuration, this is expected to change in the near future.
To configure fact caching using jsonfile, enable it in ansible.cfg as follows:
fact_caching_connection is a local filesystem path to a writeable directory (ansible will attempt to create the directory if one does not exist).
fact_caching_timeout is the number of seconds to cache the recorded facts.
Registering variables ¶
Another major use of variables is running a command and registering the result of that command as a variable. When you execute a task and save the return value in a variable for use in later tasks, you create a registered variable. There are more examples of this in the Conditionals chapter.
For example:
Results will vary from module to module. Each module’s documentation includes a RETURN section describing that module’s return values. To see the values for a particular task, run your playbook with -v .
Registered variables are similar to facts, with a few key differences. Like facts, registered variables are host-level variables. However, registered variables are only stored in memory. (Ansible facts are backed by whatever cache plugin you have configured.) Registered variables are only valid on the host for the rest of the current playbook run. Finally, registered variables and facts have different precedence levels .
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 Loops section on using register with a loop.
If a task fails or is skipped, the variable still is registered with a failure or skipped status, the only way to avoid registering a variable is using tags.
Accessing complex variable data ¶
We already described facts a little higher up in the documentation.
Some provided facts, like networking information, are made available as nested data structures. To access them a simple {{ foo }} is not sufficient, but it is still easy to do. Here’s how we get an IP address:
OR alternatively:
Similarly, this is how we access the first element of an array:
Accessing information about other hosts with magic variables ¶
Whether or not you define any variables, you can access information about your hosts with the Special Variables Ansible provides, including “magic” variables, facts, and connection variables. Magic variable names are reserved - do not set variables with these names. The variable environment is also reserved.
The most commonly used magic variables are hostvars , groups , group_names , and inventory_hostname .
hostvars lets you access variables for another host, including facts that have been gathered about that host. You can access host variables at any point in a playbook. Even if you haven’t connected to that host yet in any play in the playbook or set of playbooks, you can still get the variables, but you will not be able to see the facts.
If your database server wants to use the value of a ‘fact’ from another node, or an inventory variable assigned to another node, it’s easy to do so within a template or even an action line:
groups is a list of all the groups (and hosts) in the inventory. This can be used to enumerate all hosts within a group. For example:
A frequently used idiom is walking a group to find all IP addresses in that group.
You can use this idiom to point a frontend proxy server to all of the app servers, to set up the correct firewall rules between servers, etc. You need to make sure that the facts of those hosts have been populated before though, for example by running a play against them if the facts have not been cached recently (fact caching was added in Ansible 1.8).
group_names is a list (array) of all the groups the current host is in. This can be used in templates using Jinja2 syntax to make template source files that vary based on the group membership (or role) of the host:
inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful when you’ve disabled fact-gathering, or you don’t want to rely on the discovered hostname ansible_hostname . If you have a long FQDN, you can use inventory_hostname_short , which contains the part up to the first period, without the rest of the domain.
Other useful magic variables refer to the current play or playbook, including:
New in version 2.2.
ansible_play_hosts is the full list of all hosts still active in the current play.
ansible_play_batch is available as a list of hostnames that are in scope for the current ‘batch’ of the play. The batch size is defined by serial , when not set it is equivalent to the whole play (making it the same as ansible_play_hosts ).
New in version 2.3.
ansible_playbook_python is the path to the python executable used to invoke the Ansible command line tool.
These vars may be useful for filling out templates with multiple hostnames or for injecting the list into the rules for a load balancer.
Also available, inventory_dir is the pathname of the directory holding Ansible’s inventory host file, inventory_file is the pathname and the filename pointing to the Ansible’s inventory host file.
playbook_dir contains the playbook base directory.
We then have role_path which will return the current role’s pathname (since 1.8). This will only work inside a role.
And finally, ansible_check_mode (added in version 2.1), a boolean magic variable which will be set to True if you run Ansible with --check .
Defining variables in files ¶
It’s a great idea to keep your playbooks under source control, but you may wish to make the playbook source public while keeping certain important variables private. Similarly, sometimes you may just want to keep certain information in different files, away from the main playbook.
You can do this by using an external variables file, or files, just like this:
This removes the risk of sharing sensitive data with others when sharing your playbook source with them.
The contents of each variables file is a simple YAML dictionary, like this:
It’s also possible to keep per-host and per-group variables in very similar files, this is covered in Organizing host and group variables .
Passing variables on the command line ¶
In addition to vars_prompt and vars_files , it is possible to set variables at the command line using the --extra-vars (or -e ) argument. Variables can be defined using a single quoted string (containing one or more variables) using one of the formats below
key=value format:
Values passed in using the key=value syntax are interpreted as strings. Use the JSON format if you need to pass in anything that shouldn’t be a string (Booleans, integers, floats, lists etc).
JSON string format:
vars from a JSON or YAML file:
This is useful for, among other things, setting the hosts group or the user for the playbook.
Escaping quotes and other special characters:
Ensure you’re escaping quotes appropriately for both your markup (e.g. JSON), and for the shell you’re operating in.:
In these cases, it’s probably best to use a JSON or YAML file containing the variable definitions.
Variable precedence: Where should I put a variable? ¶
A lot of folks may ask about how variables override another. Ultimately it’s Ansible’s philosophy that it’s better you know where to put a variable, and then you have to think about it a lot less.
Avoid defining the variable “x” in 47 places and then ask the question “which x gets used”. Why? Because that’s not Ansible’s Zen philosophy of doing things.
There is only one Empire State Building. One Mona Lisa, etc. Figure out where to define a variable, and don’t make it complicated.
However, let’s go ahead and get precedence out of the way! It exists. It’s a real thing, and you might have a use for it.
If multiple variables of the same name are defined in different places, they get overwritten in a certain order.
Here is the order of precedence from least to greatest (the last listed variables winning prioritization):
command line values (eg “-u user”) role defaults 1 inventory file or script group vars 2 inventory group_vars/all 3 playbook group_vars/all 3 inventory group_vars/* 3 playbook group_vars/* 3 inventory file or script host vars 2 inventory host_vars/* 3 playbook host_vars/* 3 host facts / cached set_facts 4 play vars play vars_prompt play vars_files role vars (defined in role/vars/main.yml) block vars (only for tasks in block) task vars (only for the task) include_vars set_facts / registered vars role (and include_role) params include params extra vars (always win precedence)
Basically, anything that goes into “role defaults” (the defaults folder inside the role) is the most malleable and easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in namespace. The idea here to follow is that the more explicit you get in scope, the more precedence it takes with command line -e extra vars always winning. Host and/or inventory variables can win over role defaults, but not explicit includes like the vars directory or an include_vars task.
Tasks in each role will see their own role’s defaults. Tasks defined outside of a role will see the last role’s defaults.
Variables defined in inventory file or provided by dynamic inventory.
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.
When created with set_facts’s cacheable option, variables will have the high precedence in the play, but will be the same as a host facts precedence when they come from the cache.
Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the second one wins.
The previous describes the default config hash_behaviour=replace , switch to merge to only partially overwrite.
Group loading follows parent/child relationships. Groups of the same ‘parent/child’ level are then merged following alphabetical order. This last one can be superseded by the user via ansible_group_priority , which defaults to 1 for all groups. This variable, ansible_group_priority , can only be set in the inventory source and not in group_vars/ as the variable is used in the loading of group_vars/.
Another important thing to consider (for all versions) is that connection variables override config, command line and play/role/task specific options and keywords. See Controlling how Ansible behaves: precedence rules for more details. For example, if your inventory specifies ansible_user: ramon and you run:
This will still connect as ramon because the value from the variable takes priority (in this case, the variable came from the inventory, but the same would be true no matter where the variable was defined).
For plays/tasks this is also true for remote_user . Assuming the same inventory config, the following play:
will have the value of remote_user overwritten by ansible_user in the inventory.
This is done so host-specific settings can override the general settings. These variables are normally defined per host or group in inventory, but they behave like other variables.
If you want to override the remote user globally (even over inventory) you can use extra vars. For instance, if you run:
the lola value is still ignored, but ansible_user=maria takes precedence over all other places where ansible_user (or remote_user ) might be set.
A connection-specific version of a variable takes precedence over more generic versions. For example, ansible_ssh_user specified as a group_var would have a higher precedence than ansible_user specified as a host_var.
You can also override as a normal variable in a play:
Scoping variables ¶
You can decide where to set a variable based on the scope you want that value to have. Ansible has three main scopes:
Global: this is set by config, environment variables and the command line Play: each play and contained structures, vars entries (vars; vars_files; vars_prompt), role defaults and vars. Host: variables directly associated to a host, like inventory, include_vars, facts or registered task outputs
Examples of where to set a variable ¶
Let’s show some examples and where you would choose to put what based on the kind of control you might want over values.
First off, group variables are powerful.
Site-wide defaults should be defined as a group_vars/all setting. Group variables are generally placed alongside your inventory file. They can also be returned by a dynamic inventory script (see Working with dynamic inventory ) or defined in things like Red Hat Ansible Tower from the UI or API:
Regional information might be defined in a group_vars/region variable. If this group is a child of the all group (which it is, because all groups are), it will override the group that is higher up and more general:
If for some crazy reason we wanted to tell just a specific host to use a specific NTP server, it would then override the group variable!:
So that covers inventory and what you would normally set there. It’s a great place for things that deal with geography or behavior. Since groups are frequently the entity that maps roles onto hosts, it is sometimes a shortcut to set variables on the group instead of defining them on a role. You could go either way.
Remember: Child groups override parent groups, and hosts always override their groups.
Next up: learning about role variable precedence.
We’ll pretty much assume you are using roles at this point. You should be using roles for sure. Roles are great. You are using roles aren’t you? Hint hint.
If you are writing a redistributable role with reasonable defaults, put those in the roles/x/defaults/main.yml file. This means the role will bring along a default value but ANYTHING in Ansible will override it. See Roles for more info about this:
If you are writing a role and want to ensure the value in the role is absolutely used in that role, and is not going to be overridden by inventory, you should put it in roles/x/vars/main.yml like so, and inventory values cannot override it. -e however, still will:
This is one way to plug in constants about the role that are always true. If you are not sharing your role with others, app specific behaviors like ports is fine to put in here. But if you are sharing roles with others, putting variables in here might be bad. Nobody will be able to override them with inventory, but they still can by passing a parameter to the role.
Parameterized roles are useful.
If you are using a role and want to override a default, pass it as a parameter to the role like so:
This makes it clear to the playbook reader that you’ve made a conscious choice to override some default in the role, or pass in some configuration that the role can’t assume by itself. It also allows you to pass something site-specific that isn’t really part of the role you are sharing with others.
This can often be used for things that might apply to some hosts multiple times. For example:
In this example, the same role was invoked multiple times. It’s quite likely there was no default for name supplied at all. Ansible can warn you when variables aren’t defined – it’s the default behavior in fact.
There are a few other things that go on with roles.
Generally speaking, variables set in one role are available to others. This means if you have a roles/common/vars/main.yml you can set variables in there and make use of them in other roles and elsewhere in your playbook:
There are some protections in place to avoid the need to namespace variables. In the above, variables defined in common_settings are most definitely available to ‘something’ and ‘something_else’ tasks, but if “something’s” guaranteed to have foo set at 12, even if somewhere deep in common settings it set foo to 20.
So, that’s precedence, explained in a more direct way. Don’t worry about precedence, just think about if your role is defining a variable that is a default, or a “live” variable you definitely want to use. Inventory lies in precedence right in the middle, and if you want to forcibly override something, use -e .
If you found that a little hard to understand, take a look at the ansible-examples repo on GitHub for a bit more about how all of these things can work together.
Using advanced variable syntax ¶
For information about advanced YAML syntax used to declare variables and have more control over the data placed in YAML files used by Ansible, see Advanced Syntax .
An introduction to playbooks
Conditional statements in playbooks
Jinja2 filters and their uses
Looping in playbooks
Playbook organization by roles
Best practices in playbooks
List of special variables
Have a question? Stop by the google group!
#ansible IRC chat channel
Ansible: Set Variable In Task
Variables in Ansible can be defined in many different places, such as in inventory, in playbooks, in reusable files, in roles, and at the command-line.
Ansible also allows to set variables directly in a task by using the set_fact module.
Variables defined using the set_fact become associated with the host that the task is running against, that makes them available across subsequent tasks for the entire duration of the play.
Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →
Set Variable In Task
Variable Precedence: Per the standard Ansible variable precedence rules , other types of variables have a higher priority, so a variable defined using the set_fact module may be overridden.
Below you will find an example of how to set and use variables in Ansible tasks using the set_fact module:
Sample output:
Cool Tip: How to set default values for variables in Ansible! Read more →
Leave a Reply Cancel reply

How to use different Ansible variables with examples
Table of Contents
Ansible is not a full-fledged programming language, but it does have several programming language features, and one of the most important of these is variable substitution.
There are different types of variables available in Ansible (you can click on individual link which will take you to the respective official documentation page from docs.ansible.org :
- Special variables
- Inventory variables
Host variables
- Group variables
- Facts and local facts
- Connection variables
- and so on..
Creating valid variable names
- Before you start using variables, it’s important to know what are valid variable names.
- The name of the variable must only include letters, underscores, and numbers—spaces are not allowed.
- The name of the variable can only begin with a letter—they can contain numbers, but cannot start with one.
For example, the following are good variable names:
The following examples are all invalid, however, and cannot be used :
Built-in variables
Ansible defines several variables that are always available in a playbook
Defining variables in inventory
There are two types of variables which you can define in an inventory i.e. host variables and group variables. Let us understand about each of them individually:
We will use our default inventory from /etc/ansible/hosts which has below entries
In this inventory I will define 2 variables for server2 in the following format
So here I have defined two custom variables which are applicable only for server2 . Now we will use this variable with ansible playbook. Here I have written a small playbook host_vars.yml which will use those variables from the inventory so we can know where the variables are working or not:
Let us execute this playbook:
In the output from TASK you can see that the variable http_port is replaced with 8080 and pkg is replaced with httpd .
Group Variables
I have already explained you about groups in an inventory. So group variables can be assigned to a complete group and all the hosts part of that group instead of individual hosts. To demonstrate the let me modify my inventory file and divide the list of hosts into group
Here I have divided my managed nodes into two groups and have assigned the variables to db group using db:vars . I will make some changes to our playbook file i.e. replace server2 with the group name db and some minor text changes:
Let us execute the group_vars.yml playbook and verify the group_vars :
Defining variable in project
If you are using ansible playbook under some project then it is not recommended to modify the inventory file. We have a cleaner solution available to define host and group variables in Project.
To define host variable we can create a sub-directory host_vars and similarly to define group variable we can create a sub-directory group_vars inside the main project directory.
For example I will create a project " lab1 " and copy the ansible.cfg from default directory /etc/ansible/
Copy /etc/ansible/ansible.cfg to the project directory
Create an inventory file, I will just add server2 in my inventory file as that is enough to demonstrate the example here:
Now we will create host_vars directory inside lab1
Inside host_vars we will create a new file with the same name as of the server i.e. server2 in my case and define the variables:
Now we copy our existing host_vars.yml to this project's home folder:
and then execute the playbook:
So ansible was able to fetch the variable from server2 file inside host_vars directory.
Similarly we can create group_vars directory under lab1 and use the name of the group to create a new file which will contain the list of variables. Next modify the hosts: entry with the group name instead of server name in the playbook file.

Defining variables in playbook
The simplest way to define variables is to put a vars section in your playbook with the names and values of variables.
In this example playbook-vars.yml I have defined two custom variables under vars and I am using them with debug module. Additionally I am also using to built-in variables
So the ansible has successfully fetched the values of the variables.
Defining variables using command line
Variables set by passing -e or --extra-vars with var=value to ansible-playbook have the highest precedence, which means you can use this to override variables that are already defined
Here I have a sample playbook variable-with-cmd-line.yml where I have defined a variable username with a value as deepak . I am then using debug module to print the value of username variable
Now additionally since this section is about using command line variables we will define the same variable using username and assign a different value:
As you see from the TASK section output, the command line variable value which we gave with -e has taken precedence compared to the value given by vars inside the playbook.
Accessing Variables
There are different ways using which you can access the content of the variable. We have used double curly braces to access all our variables in the examples above. This curly braces syntax is part of Jinja2 template.
Now inside these curly braces we have simply defined the name of the variable and the mapping value was printed on the console. But sometimes the variables can be in complex structure such as the output of "Gathering Facts"
We can access the facts of a system using setup module which gives us a long list of output. Some provided facts, like networking information, are made available as nested data structures. To access them a simple {{ foo }} is not sufficient, but it is still easy to do. Here’s how we get an IP address:
Here in this playbook access-variables.yml I have combined multiple methods using which you can capture the IPv4 address of eth0 using the Ansible Facts
As you can see under debug module section there are couple of methods using which we can collect the IPv4 address from the facts. Let us execute this playbook:
So we get the same value using all the methods.
Accessing dictionary keys in a variable
When we execute the setup module it gives us a long bunch of output with system information. This information is by default stored into ansible_facts variable. Individually you can also search for other variables with stores different values of your system, to get this list of variables from setup module you can execute:
So you can use any of these variables to collect system information.
If a variable contains a dictionary, you can access the keys of the dictionary by using either a dot ( . ) or a subscript ( [] ). This is the trimmed sample output of setup module which contains the interface and IP address information which we have used to get the data in previous example:
Here the output is in dictionary format and we need to access the Keys of this dictionary. So we first take the variable name ansible_eth0 followed by the key so using dot notation the variable becomes ansible_eth0.ipv4.addess
Now instead of dot you can also use subscript [] and modify the variable to ansible_eth0['ipv4']['address']
Finally to access the variable inside the ansible playbook we use Jinja2 template using double curly braces {{}}
Using register module to store output of any command
Registered variables are similar to facts, with a few key differences. Like facts, registered variables are host-level variables. However, registered variables are only stored in memory. (Ansible facts are backed by whatever cache plugin you have configured.) Registered variables are only valid on the host for the rest of the current playbook run. Finally, registered variables and facts have different precedence levels.
I have a sample playbook file register_variable.yml with following content:
This playbook will execute " ifconfig eth0 " on localhost .
But here our intention is to get the IP Address used by eth1 interface so we must capture the output of "ifconfig eth1"
To capture the output we use register module. The value of a variable set using the register clause is always a dictionary, but the specific keys of the dictionary are different, depending on the module that was invoked.
So we will update our playbook to use register module and store the output of " ifconfig eth0 " into ip_addr variable
Next we will execute our playbook which now contains a long list of output:
In this output we are only interested in stdout key value so to access stdout without variable we will use ip_addr.stdout (which we had learned in our last chapter "Accessing dictionary keys in a variable"
We will update our playbook with the following entry:
and re-run the playbook:
So now we get the content of stdout only. But this needs formatting and we will perform some additional strip to get the value we want i.e. the IP address of eth0. I will split the content with " \n " (new line) and get the first index value i.e. the second line
Let us re-run the playbook:
Now we have much cleaner output but we still need some more formatting to get the IP address of eth0. So we will add another split based on whitespace character and then print the first index value i.e. the second line:
Let us check the output:
Now we get the IP Address of eth0.
Using set_fact module to create a new variable
How can we assign this IP address we are getting from all these split operation to a new variable ?
vars can be used only when we are statically defining a variable inside the playbook but for dynamic values which are collected runtime we can use set_fact
Ansible also allows you to set a fact (effectively the same as defining a new variable) in a task by using the set_fact module. So we will use set_fact module and define a new variable ip_addr inside our playbook which will perform all the split operations and then store the final value inside ip_addr
I have updated my playbook to use set_fact module:
Here we are performing the same split operation but instead of performing with debug module we do this wit set_fact so that we can store the output into ip_addr variable. Now we can use this variable across playbook when ever required
So we are properly getting the IP Address value of eth0 interface.
Prompt for user input with vars_prompt
When running a playbook, there may be information that you need to collect at runtime. This may be sensitive information, such as passwords. At other times, this is information that can only be provided by the end user at runtime, such as the password to use for the root user when bootstrapping a system.
You can collect this information from the end user by specifying a vars_prompt section in your playbook. When you run the playbook, it will ask the questions you’ve specified and record the answers, ready to be used as variables.
We will write another playbook prompt-variable.yml which will prompt the user for the USERNAME and PASSWORD using vars_prompt module and then print these values on the console using debug module. The prompt for user_name is set to private: no so the operator can see the text while for password we have set private: yes so the operator will not see anything while typing the password.
Let us execute this playbook and observe the output:
Read and access variables from separate YAML or JSON file
In all the examples above we have defined variable inside inventory, playbook or host_vars / group_vars folder. Now in this section we will create a separate YAML or JSON file which will only contain a bunch of variables and using playbook we will refer this YAML or JSON file to read and access the variable value.
This can help you reduce the length of the playbook when working with multiple variables:
Using YAML File
We will create a separate YAML file variables.yml with following content:
Here I have defined 3 variables and we will access these variables using our playbook read-from-yml-file.yml
Here we have defined our variables.yml file with vars_files module. Since this file exists in my current working directory I have not given any path or you must give t he full absolute path of the variable file .
Output from this playbook:
So the playbook has successfully collected the values from our YAML file.
Using JSON File
Similarly we can also create a variable file custom_vars.json using JSON format
Next we will update our playbook file to refer both the variables file. We can place the path and variable file name using separate line and mention multiple files.
Let us execute this script:
So our playbook is able to read from both the variables file.
Understanding variable precedence
We’ve covered several ways of defining variables, and it can happen that you define the same variable multiple times for a host, using different values. Avoid this when you can, but if you can’t, then keep in mind Ansible’s precedence rules. When the same variable is defined in multiple ways, the precedence rules determine which value wins. For updated list of precedence rules, you can refer Understanding variable precedence
The basic rules of precedence are as follows:
- (Lowest) command line values (for example, -u my_user, these are not variables)
- role defaults (defined in role/defaults/main.yml) 1
- inventory file or script group vars 2
- inventory group_vars /all
- playbook group_vars /all
- inventory group_vars /*
- playbook group_vars /*
- inventory file or script host vars
- inventory host_vars /*
- playbook host_vars /*
- host facts / cached set_facts
- play vars_prompt
- play vars_files
- role vars (defined in role/vars/main.yml )
- block vars (only for tasks in block)
- task vars (only for the task)
- include_vars
- set_facts / registered vars
- role (and include_role ) params
- include params
- (Highest) extra vars (for example, -e "user=my_user" )
What’s Next
Next in our Ansible Tutorial we will learn about YAML syntax which is used in writing Ansible Playbooks.
Didn't find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
6 thoughts on “How to use different Ansible variables with examples”
Under access-variables the playbook is listed as register-variables.yml vice access-veriables.yml. So far, that is the only issue I have seen while working through the tutorial.
Thank you for following this tutorial and sharing your feedback through out the course. I have corrected the highlighted typo.
please correct the “basic rules of precedence”
Updated, Thanks!
Thanks, nice and valuable overview covering many needed use cases. Best, Frank
Hi, I have set of hosts present in hosts.ini file and respective services to be started/stopped. Currently respective services yml files that I kept in vars folder. Instead I want to group them in hosts.ini file itself so it will be specific to those hosts. How can I achieve this ? Thanks for your help !!!
Sample hosts.ini in DEV folder
Leave a Comment Cancel reply
Save my name and email in this browser for the next time I comment.
Notify me via e-mail if anyone answers my comment.
- Articles Automation Career Cloud Containers Kubernetes Linux Programming Security
- About About Enable Sysadmin Email newsletter Join the community Sudoers program Meet the team FAQs
How to use variables as arguments in Ansible
%t min read | by Seth Kenlon (Editorial Team, Red Hat)

Image by Chuk Yong from Pixabay
When you write an Ansible playbook , you sometimes need to pass data into your play at runtime. To do that, you can use a variable , a sort of placeholder for data that's meant to be determined at some point in the future.
There are lots of places to create variables for your playbooks, such as an inventory file, included files, or even dynamically in your playbook itself. However, you can also pass variables in the terminal when you launch your playbook.
[ Download now: A system administrator's guide to IT automation . ]
Using a variable
To use a variable in a playbook, you reference it in curly braces ( {{ }} ). For example, this simple playbook uses the debug module to print the value of a variable to the terminal:
Because the variable hasn't been defined, the play results in an error:
[ Get started with IT automation with the Ansible Automation Platform beginner's guide . ]
To define a variable dynamically when you run a playbook, use the --extra-vars option along with the key and value of the variable you want to define. In this example, the key is my_var because that's the string referenced in the playbook, and the value is any string you want the variable to contain.

This time, the variable's value is passed into Ansible through the command option and successfully printed to the terminal.
Variables and Ansible
Ansible supports many ways of passing variables into scripts, generating variables within scripts, and even processing variables as part of a playbook's tasks. For more information on how to process variables in a playbook using filters, read 2 practical ways to use filters to manipulate data in Ansible and Network configuration with Ansible filters .
Check out these related articles on Enable Sysadmin

Seth Kenlon
Seth Kenlon is a UNIX geek and free software enthusiast. More about me
Try Red Hat Enterprise Linux
Download it at no charge from the red hat developer program., related content.

OUR BEST CONTENT, DELIVERED TO YOUR INBOX
Privacy Statement

Ansible Variables

Introduction to Ansible Variables
In Ansible, variables play a very important role, as these are the reference points which your playbooks will refer to contain data. This is like any programming language. Also, in most ways’ variable behaves the same in Ansible as in some other programming language. In Ansible, variables can be defined at various places and in many ways. Variables have specifications also like valid name, defining variables, calling a variable, Ansible special variable, array of variable and importing from another file. We will try to explore a few of these in this article.
Variables in Ansible
First, we need to understand what valid names for a variable in Ansible are. So, for this you must remember below:
Start Your Free Software Development Course
Web development, programming languages, Software testing & others

- Variable name must start with a
- Variable name should contain characters, numbers or underscore
- Some of the valid variable names are like abc1,
- Some of the invalid variable names are like abc-1, abc%1, 12, abc xyz, xyz
Now, Let’s discuss the ways to define variables in Ansible. In Ansible, Variables can be defined in the following places: –
1. Inventory file
You can add Variables in inventory file which can have a scope limited to a specific host, group or all hosts in the file. This is helpful if you want to use the same variable to contain different values for different hosts defined in the same inventory
[host_list] test1 ansible_connection=ssh ansible_user=my_user test2 ansible_connection=ssh ansible_user=my_user1
Also, you can try to define variables for the whole group like below: –
[Host_List] host1 host2 [Host_List:vars] ansible_connection=ssh ansible_user=my_user ntp_server=ntp.test.com
2. Playbook
In Playbooks, you can define variables which are referred in same playbook’s tasks. The position of defined variables also decides the scope of variables.
Take a simple like below: –
- hosts: web vars: http_port: 80
- hosts: app vars: http_port: 8080
3. Imported files and Roles
In production environments, you will be dealing with this, as using roles is more organized and In role structure, you can define your variable in a file and include in playbook.
Now take an example, where you have a variable file named as var_name.yaml with the below contents.
name1: test1
We can include this file in a playbook and use the variable name1 as below
--- name: writing something hosts: all tasks: - include_vars: yaml - debug: msg="My name is {{ name1 }}"
4. Variables passed on command line
Variables can also be passed on command line like below using — extra-vars argument or -e in key=value format and variable separated by space.
ansible-playbook test.yaml --extra-vars "one_var=test1 other_var=test2"
Also note that all values passed in above way will be treated as strings. If you have some values in Integer, Booleans etc. then better way is to define these in JSON format, like below:
ansible-playbook test.yml --extra-vars '{"one_var":"test1","other_var":"test2"}'
Adding to above, if you have a JSON or YAML file then also you can import it in your playbook like below during run time.
ansible-playbook test.yaml --extra-vars "@file1.json"
5. Variables via Jinja2 templates
Once you have your variables defined you can use them in a playbook using Jinja2 templating system. Jinja2 provides many filter which you can use along with variable to get more tasks done on Control server end, So that Hosts not need to send unwanted information one end to another.
Like see below filter and variable use, where the variable test_var have will be passed and if no value is given to it a default value equal to 9 will be assigned to it.
{{ test_var | default(9) }}
Similarly, when passing the value of a variable is mandatory
{{ test_var | mandatory }}
In above locations, you can mention user defined variables. So now let’s discuss about the type of variable in Ansible: –
6. User Defined Variables
The variables which you define in your playbooks simply in key-value pair. These can be any value which is going to be used in your
An example is below, here we defined a variable colour and then used it later in a task simply where command module is running a command.
--- - hosts: all vars: colour: blue tasks: - name: this is just a test command: /bin/echo "{{ colour }}"
7. System Facts
These are the default variables in which Ansible Control Server stores information after discovering from nodes. By default, ansible_facts contain all the information in JSON format after setup runs to gather a lot of information in the form of facts from remote nodes. Then you can use this information like below variable in your plays.
{{ ansible_facts['devices']['xvda']['model'] }} {{ ansible_facts['nodename'] }}
8. Registered Variables
These are the variables in which the output of your task will be stored on Ansible Control Server. In simple word, when you want to run a command on remote computer and then store the output in a variable and use a piece of information from the output later in your plays. This kind of usage is possible by registered variables.
In fact, it is somehow like the system Facts which are discovered and fetched by setup module. Here whatever command you run its output will be saved in JSON format and then you use that information as same as you used facts.
Let’s take an example, where you run a command service https status and register its output value in a variable apache_status. Now, when you debug the variable. It will give you a lot of information about the target system and the output it received in JSON format.
--- hosts: all gather_facts: no tasks: name: Get web server status command: service httpd status register: apache_status name: web server status only debug: var: apache_status
The JSON output will have fields like stdout, stdin, changed, rc etc. Using these fields we can get use a specific value, like below, where a variable apache_status[‘stdout_lines’] contains a specific piece of information that gives only service status.
debug: var:apache_status.stdout_lines
9. Special Variable
These are the variables which is default to the system and can not be set by the user directly. But these will contain the data related to System’s internal state like version, forks, connection method etc. Some examples of these variables are inventory_file, inventory_dir, ansible_connection, ansible_host,
Using Ansible variables efficiently makes you easily work with loops, in multi hosts environments, multi connection type scenarios and many more setups where the hard coding a value is adding more difficulties. Understanding variables and usage is very important and you can learn more about the Ansible variables concept from Ansible community documentation.
Recommended Articles
This is a guide to Ansible Variables. Here we discuss the introduction to Ansible variables concept along with 9 different valid variables. You may also have a look at the following articles to learn more –
- Ansible Interview Questions
- Ansible Architecture
- Is Ansible free?
- Ansible Commands

Related Courses

*Please provide your correct email id. Login details for this Free course will be emailed to you
By signing up, you agree to our Terms of Use and Privacy Policy .
Forgot Password?
This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Explore 1000+ varieties of Mock tests View more
Submit Next Question

- Coding Ground
- Corporate Training

- Ansible Tutorial
- Ansible - Home
- Ansible - Introduction
- Ansible - Environment Setup
- Ansible - YAML Basics
- Ansible - Ad hoc Commands
- Ansible - Playbooks
- Ansible - Roles
Ansible - Variables
- Ansible - Advanced Execution
- Ansible - Troubleshooting
- Ansible Useful Resources
- Ansible - Quick Guide
- Ansible - Useful Resources
- Ansible - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook.
In the above example, we have defined a variable name tomcat_port and assigned the value 8080 to that variable and can use that in your playbook wherever needed.
Now taking a reference from the example shared. The following code is from one of the roles (install-tomcat) −
Here, the output is the variable used.
Let us walk through all the keywords used in the above code −
block − Ansible syntax to execute a given block.
name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed.
action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml.
register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output.
always − Again a Ansible keyword , it states that below will always be executed.
msg − Displays the message.
Usage of variable - {{Output}}
This will read the value of variable Output. Also as it is used in the msg tab, it will print the value of the output variable.
Additionally, you can use the sub properties of the variable as well. Like in the case checking {{Output.changed}} whether the output got changed and accordingly use it.
Exception Handling in Playbooks
Exception handling in Ansible is similar to exception handling in any programming language. An example of the exception handling in playbook is shown below.
Following is the syntax for exception handling.
rescue and always are the keywords specific to exception handling.
Block is where the code is written (anything to be executed on the Unix machine).
If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed.
Always gets executed in all cases.
So if we compare the same with java, then it is similar to try, catch and finally block.
Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally .
Below is the example to demonstrate the usage of Loops in Ansible.
The tasks is to copy the set of all the war files from one directory to tomcat webapps folder.
Most of the commands used in the example below are already covered before. Here, we will concentrate on the usage of loops.
Initially in the 'shell' command we have done ls *.war. So, it will list all the war files in the directory.
Output of that command is taken in a variable named output.
To loop, the 'with_items' syntax is being used.
with_items: "{{output.stdout_lines}}" --> output.stdout_lines gives us the line by line output and then we loop on the output with the with_items command of Ansible.
Attaching the example output just to make one understand how we used the stdout_lines in the with_items command.

The playbook in totality is broken into blocks. The smallest piece of steps to execute is written in block. Writing the specific instruction in blocks helps to segregate functionality and handle it with exception handling if needed.
Example of blocks is covered in variable usage,exception handling and loops above.
Conditionals
Conditionals are used where one needs to run a specific step based on a condition.
In this case, Equals will be printed as the test1 variable is equal as mentioned in the when condition. when can be used with a logical OR and logical AND condition as in all the programming languages.

Just change the value of test1 variable from Hello Vivek to say Hello World and see the output.

Ansible prompt a variable in a task
There is the pause module to prompt for an input inside a task.
For example
gives (abridged)
- This part of the code from the question can't work because there is no module in the task
Running such code would produce
- A variable can be used in any task after it has been prompted for, registered, and declared with set_fact .
i'm trying to add a value in inline module in sysctl.conf file, how can i achieve that? once i enter the value in the prompt it should be updated in the sysctl.conf file.

当条件符合 azure devops 管道的 ansible 任务中的主机名时
[英]when condition as per hostname in ansible task of azure devops pipeline
提示: 本站为国内 最大 中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可 显示英文原文 。

1楼 Vladimir Botka 1 已采纳 2020-06-16 05:22:07
声明 :本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:[email protected]
- azure-devops
- azure-pipelines
- azure-pipelines-release-pipeline
- azure-pipelines-yaml
- azure-data-factory
- database-restore
- azure-devops-server

IMAGES
VIDEO
COMMENTS
Ansible 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.
Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this: - name: Define variable in task. shell: echo "http://www.my.url.com" register: url - name: Download apache shell: wget { { item }} with_items: url.stdout
Ansible uses variables to help deal with differences between systems. To understand variables you'll also want to read Conditionals and Loops . Useful things like the group_by module and the when conditional can also be used with variables, and to help manage differences between systems.
Ansible also allows to set variables directly in a task by using the set_fact module. Variables defined using the set_fact become associated with the host that the task is running against, that makes them available across subsequent tasks for the entire duration of the play. Cool Tip: Ansible Playbook - Print Variable & List All Variables!
There are different types of variables available in Ansible (you can click on individual link which will take you to the respective official documentation page from docs.ansible.org: Special variables Inventory variables Host variables Group variables Facts and local facts Connection variables and so on.. Creating valid variable names
The use of variables simplifies the management of dynamic values throughout an Ansible project and can potentially reduce the number of human errors. We have a convenient way to handle variations and differences between different environments and systems with variables.
To define a variable dynamically when you run a playbook, use the --extra-vars option along with the key and value of the variable you want to define. In this example, the key is my_var because that's the string referenced in the playbook, and the value is any string you want the variable to contain. $ ansible-playbook --extra-vars my_var=foo ...
Introduction to Ansible environment variables. Ansible Environment variables are used to set the environment variable for action on the remote host using environment keyword, which can be set at the playbook level or the task level and which doesn't affect the ansible configuration file or the environment set for the user and it doesn't include automatically to the facts gathered by gather ...
Variable name must start with a. Variable name should contain characters, numbers or underscore. Some of the valid variable names are like abc1, Some of the invalid variable names are like abc-1, abc%1, 12, abc xyz, xyz. Now, Let's discuss the ways to define variables in Ansible. In Ansible, Variables can be defined in the following places ...
Here, the output is the variable used. block − Ansible syntax to execute a given block. name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed. action − The code next to action tag is the task to be executed.
Ansible prompt a variable in a task. ansible. 8,632 There is the pause module to prompt for an input inside a task. For example - hosts: localhost tasks: - pause: prompt: "Please enter the value for kernel.shmmax " echo: yes register: result - set_fact: shmmax: "{{ result.user_input }}" - debug: var: shmmax ...
相关问题 Azure 插件的 devops 管道条件 - Azure devops pipeline condition of plugin Azure DevOps 管道 - 带管道变量的条件表达式 - Azure DevOps Pipeline - condition expression with pipeline variable 在 Azure DevOps 管道中运行 ansible 脚本 - Running ansible script in Azure DevOps pipeline 如何在 Azure Devops Pipeline 中使用 PowerShell 根据条件触发代理 ...