{"id":8704,"date":"2024-01-15T00:13:23","date_gmt":"2024-01-15T00:13:23","guid":{"rendered":"https:\/\/cheapwindowsvps.com\/blog\/mastering-ansible-variables-a-guide-with-practical-examples\/"},"modified":"2025-01-20T10:32:39","modified_gmt":"2025-01-20T10:32:39","slug":"mastering-ansible-variables-a-guide-with-practical-examples","status":"publish","type":"post","link":"https:\/\/cheapwindowsvps.com\/blog\/mastering-ansible-variables-a-guide-with-practical-examples\/","title":{"rendered":"Mastering Ansible Variables: A Guide with Practical Examples"},"content":{"rendered":"<p><div>Ansible variables store and manipulate data that can be accessed and utilized across playbooks, roles, and tasks. They allow for dynamic configurations and flexible automation by enabling the abstraction of values that may change based on different environments or use cases.<\/div>\n<\/p>\n<p><p>In this tutorial, I will introduce Ansible variables and explore their usage with examples.<\/p>\n<\/p>\n<p><h2>Prerequisites<\/h2>\n<\/p>\n<p><p>To proceed with this tutorial, you will need the following:<\/p>\n<\/p>\n<ul>\n<li>An Ansible management node with Ansible installed and configured<\/li>\n<li>An Ansible target node.<\/li>\n<li>SSH key-based authentication between the management node and the target node<\/li>\n<\/ul>\n<p><p>Check out our <a href=\"https:\/\/4sysops.com\/archives\/ansible-beginner-tutorial\/\" rel=\"nofollow noopener\" target=\"_blank\">introductory articles in this Ansible beginner&#8217;s tutorial<\/a>, where we explain how to configure the necessary prerequisites.<\/p>\n<\/p>\n<p><h2>Use variables in inventories<\/h2>\n<\/p>\n<p><p>You can use variables in inventory files to define properties specific to hosts or groups. This helps in making your playbooks more flexible and reusable.<\/p>\n<\/p>\n<p><p>Let&#8217;s create an<em> inventory.txt<\/em> file with the following content.<\/p>\n<\/p>\n<p><pre>[web]<\/p><p>webserver1 ansible_host=192.168.1.101<\/p><p>webserver2 ansible_host=192.168.1.102<\/p><p>[db]<\/p><p>dbserver1 ansible_host=192.168.1.201<\/p><p>[web:vars]<\/p><p>http_port=80<\/p><p>user=admin<\/p><p><\/pre>\n<\/p>\n<p><p>In this example, <em>http<\/em>port<em> and <\/em>user<em> are group variables defined under the <\/em>[web:vars]<em> section. These variables will apply to all hosts under the <\/em>[web]<em> group.<\/em><\/p>\n<\/p>\n<p><p>After defining variables in your inventory file, you can use them in your Ansible playbooks.<\/p>\n<\/p>\n<p><p>Create a <em>playbook.yaml <\/em>file and add the following content:<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- hosts: web<\/p><p>  tasks:<\/p><p>    - name: Print HTTP port<\/p><p>      debug:<\/p><p>        msg: \"HTTP Port is {{ http_port }}\"<\/p><p>    - name: Print username<\/p><p>      debug:<\/p><p>        msg: \"Username is {{ user }}\"<\/p><p><\/pre>\n<\/p>\n<p><p>In this playbook, <em>{{ http_port }} and {{ user }}<\/em> variables in the playbook will be substituted with the values defined in your inventory for the web hosts group<em>.<br \/> <\/em><\/p>\n<\/p>\n<p><p>Now, run the playbook using the following command.<\/p>\n<\/p>\n<p><pre>ansible-playbook -i inventory.txt playbook.yaml<\/pre>\n<\/p>\n<p><p>You will see the values of the <em>{{ httpport }} and {{ user }}<\/em> variables in the following screen.<\/p>\n<\/p>\n<p><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-variables-defined-in-an-inventory-file.png\" rel=\"nofollow noopener\" target=\"_blank\">Showing the value of variables defined in an inventory file<\/a><\/p>\n<p><h2>Use variables within a task in playbooks<\/h2>\n<\/p>\n<p><p>You can define variables directly within a task. Let&#8217;s create a <em>playbook.yaml<\/em> file with the following content:<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- hosts: db<\/p><p>  vars:<\/p><p>    db_port: 3306<\/p><p>    user: \"root\"<\/p><p>  tasks: <\/p><p>    - name: Print database port<\/p><p>      debug:<\/p><p>        msg: \"Database Port is {{ db_port }}\"<\/p><p>    - name: Print username<\/p><p>      debug:<\/p><p>        msg: \"Username is {{ user }}\"<\/p><p><\/pre>\n<\/p>\n<p><p>Now, run the playbook using the following command.<\/p>\n<\/p>\n<p><pre><\/p><p>ansible-playbook -i inventory.txt playbook.yaml<\/p><p><\/pre>\n<\/p>\n<p><p>You will see the values of variables <em>{{ dbport }} <\/em> and <em>{{ user }} <\/em> on the following screen.<em><br \/> <\/em><\/p>\n<\/p>\n<p><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-variables-defined-within-a-tasks.png\" rel=\"nofollow noopener\" target=\"_blank\">Showing the value of variables defined within a tasks<\/a><\/p>\n<p><h2>Use variables in files<\/h2>\n<\/p>\n<p><p>You can define variables in separate YAML files and include them in the playbook using the <em>vars_files<\/em> directive.<\/p>\n<\/p>\n<p><p>Let&#8217;s create a <em>playbook.yaml <\/em>file and add the following content.<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- name: Playbook with Variable Files<\/p><p>  hosts: db<\/p><p>  vars_files:<\/p><p>    - vars_file.yaml<\/p><p>  tasks:<\/p><p>    - name: Task using variable from file<\/p><p>      debug:<\/p><p>        msg: \"The value of variable is {{ var }}\"<\/p><p><\/pre>\n<\/p>\n<p><p>Next, create a <em>vars<\/em>file.yaml <em>in your current working directory and add the following content:<br \/> <\/em><\/p>\n<\/p>\n<p><pre><\/p><p>var: \"value from file\"<\/p><p><\/pre>\n<\/p>\n<p><p>Now, run the playbook using the following command.<\/p>\n<\/p>\n<p><pre>ansible-playbook -i inventory.txt playbook.yaml<\/pre>\n<\/p>\n<p><p>This will fetch the value of the var variable from the <em> varsfile.yaml <\/em> file and print it on the screen. <\/p>\n<\/p>\n<p><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-variables-defined-in-a-file.png\" rel=\"nofollow noopener\" target=\"_blank\">Showing the value of variables defined in a file<\/a><\/p>\n<p><h2>Use variables with prompts<\/h2>\n<\/p>\n<p><p>Ansible facilitates prompting for variable input during playbook execution with the help of the <em>vars_prompt<\/em> section.<\/p>\n<\/p>\n<p><p>Proceed by creating a <em>playbook.yaml<\/em> and include the subsequent content:<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- name: Playbook with Prompted Variables<\/p><p>  hosts: db<\/p><p>  vars_prompt:<\/p><p>    - name: user_input<\/p><p>      prompt: \"Enter a value:\"<\/p><p>  tasks:<\/p><p>    - name: Task using prompted variable<\/p><p>      debug:<\/p><p>        msg: \"You entered: {{ user_input }}\"<\/p><p><\/pre>\n<\/p>\n<p><p>Now, run the playbook using the following command.<\/p>\n<\/p>\n<p><pre>ansible-playbook -i inventory.txt playbook.yaml<\/p><p><\/pre>\n<\/p>\n<p><p>You will be prompted to enter a value, which will then appear on the screen.<\/p>\n<\/p>\n<p><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-input-variables.png\" rel=\"nofollow noopener\" target=\"_blank\">Showing the value of input variables<\/a><\/p>\n<p><p>Showing the value of input variables<\/p>\n<\/p>\n<p><h2>Pass variables via the command line<\/h2>\n<\/p>\n<p><p>You can pass variables via the command line using the <em>-e<\/em> option in Ansible. This lets you define or override variables when running your playbook or ad-hoc commands.<\/p>\n<\/p>\n<p><p>Create a <em>playbook.yaml<\/em> file and add the following content:<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- name: Example Playbook<\/p><p>  hosts: db<\/p><p>  vars:<\/p><p>    my_variable: \"{{ my_var | default('default_value_if_not_passed') }}\"<\/p><p>  tasks:<\/p><p>    - name: Display variable value<\/p><p>      debug:<\/p><p>        var: my_variable<\/p><p><\/pre>\n<\/p>\n<p><p>This playbook contains a vars section where the variable <em>my_variable <\/em>is defined using the value passed via the command line. It uses the default filter to set a default value <em>default_value_if_not_passed<\/em> if <em>my_var<\/em> is not provided via the command line.<\/p>\n<p>Now, run the playbook and pass a variable <em>my_var<\/em> with the value <em>hello<\/em>:<\/p>\n<pre>ansible-playbook -i inventory.txt -e \"my_var=hello\" playbook.yaml<\/p><p><\/pre>\n<p>You will see the value of <em>my_variable <\/em>based on the passed or default value<em>.<br \/><\/em><\/p>\n<\/p>\n<p><div><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-variables-pass-via-the-command-line.png\" rel=\"nofollow noopener\" target=\"_blank\"><\/a><\/p>\n<p>Showing the value of variables pass via the command line<\/p>\n<\/div>\n<p><h2>Register task output as a variable<\/h2>\n<\/p>\n<p><p>In Ansible, you can register the output of a task and save it as a variable using the <em>register<\/em> keyword. This allows you to capture the result of a task and then use that result in subsequent tasks within the playbook.<\/p>\n<\/p>\n<p><p>Create a <em>playbook.yaml<\/em> with the following content.<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- name: Register Task Output Example<\/p><p>  hosts: db<\/p><p>  tasks:<\/p><p>    - name: Run a command and register its output<\/p><p>      command: free -m<\/p><p>      register: command_output<\/p><p>    - name: Display registered output<\/p><p>      debug:<\/p><p>        var: command_output<\/p><p><\/pre>\n<p>In this playbook, the command task executes a <em>free -m <\/em>command. The outcome of this command is then saved in a variable named <em>command_output<\/em> using the register keyword. Subsequently, the debug task is used to present the value stored in the <em>command_output<\/em> variable.<\/p>\n<\/p>\n<p><p>Proceed by running the given playbook.<\/p>\n<\/p>\n<p><pre><\/p><p>ansible-playbook -i inventory.txt playbook.yaml<\/p><p><\/pre>\n<\/p>\n<p><p>You will see the output of the<em> free -m<\/em> command on the following screen.<\/p>\n<\/p>\n<p><a href=\"https:\/\/4sysops.com\/wp-content\/uploads\/2024\/01\/Showing-the-value-of-registered-output.png\" rel=\"nofollow noopener\" target=\"_blank\">Showing the value of registered output<\/a><\/p>\n<p><h2>Use a conditional variable<\/h2>\n<\/p>\n<p><p>In Ansible, you can use conditional statements to set variables dynamically based on certain conditions. Ansible allows for using the when statement to set conditions under which a variable should be defined or assigned a particular value.<\/p>\n<\/p>\n<p><p>Let&#8217;s create a <em>playbook.yaml<\/em> file with the following content.<\/p>\n<\/p>\n<p><pre><\/p><p>---<\/p><p>- name: Conditional Variable Example<\/p><p>  hosts: db<\/p><p>  gather_facts: false<\/p><p>  <\/p><p>  vars:<\/p><p>    my_condition: true<\/p><p>  tasks:<\/p><p>    - name: Set variable based on condition<\/p><p>      set_fact:<\/p><p>        my_variable: \"value_when_true\"<\/p><p>      when: my_condition == true<\/p><p>    - name: Set variable based on alternative condition<\/p><p>      set_fact:<\/p><p>        my_variable: \"value_when_false\"<\/p><p>      when: my_condition != true<\/p><p>    - name: Display variable value<\/p><p>      debug:<\/p><p>        var: my_variable<\/p><p><\/pre>\n<\/p>\n<p><p>Now, run the above playbook.<\/p>\n<\/p>\n<p><pre><\/p><p>ansible-playbook -i inventory.txt playbook.yaml<\/p><p><\/pre>\n<\/p>\n<p><p>This playbook sets a variable <em>my_condition<\/em> to <em>true<\/em>. The first task uses the <em>set_fact<\/em> module to set the variable <em>my_variable<\/em> to <em>value_when_true<\/em> only when <em>my_condition<\/em> is <em>true<\/em>. The second task uses <em>set_fact<\/em> to set <em>my_variable<\/em> to <em>value_when_false<\/em> when <em>my_condition<\/em> is not <em>true<\/em>. The debug task displays the value of <em>my_variable<\/em>. Depending on the value of <em>my_condition<\/em>, either <em>value_when_true<\/em> or <em>value_when_false<\/em> will be assigned to <em>my_variable<\/em>.<\/p>\n<\/p>\n<p><h2>Subscribe to 4sysops newsletter!<\/h2>\n<\/p>\n<p><h2>Conclusion<\/h2><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ansible variables store and manipulate data that can be accessed and utilized across playbooks, roles, and tasks. They allow for dynamic configurations and flexible automation by enabling the abstraction of values that may change based on different environments or use cases. In this tutorial, I will introduce Ansible variables and explore their usage with examples. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8705,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[118,92,95],"tags":[],"class_list":["post-8704","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ansible","category-articles","category-devops"],"_links":{"self":[{"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/posts\/8704","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/comments?post=8704"}],"version-history":[{"count":2,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/posts\/8704\/revisions"}],"predecessor-version":[{"id":10389,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/posts\/8704\/revisions\/10389"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/media\/8705"}],"wp:attachment":[{"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/media?parent=8704"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/categories?post=8704"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cheapwindowsvps.com\/blog\/wp-json\/wp\/v2\/tags?post=8704"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}