Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write variables inside the tasks file in ansible

I have this play.yml

--- - hosts: 127.0.0.1   connection: local   sudo: false    tasks:      - include: apache.yml 

My Apache look like this:

vars:     url: czxcxz  - name: Download apache   shell: wget {{url}}  

This is giving me error.

If I remove vars then it works. But I want to include the vars inside tasks so that I can keep different vars for different tasks separate.

like image 830
user1994660 Avatar asked Mar 20 '14 03:03

user1994660


People also ask

How do you write variables in Ansible?

To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!

How do you declare variables in Ansible inventory?

You can define these variables in your playbooks, in your inventory, in re-usable files or 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.

How do you pass variables in Ansible role?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.


2 Answers

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:

- name: Set Apache URL   set_fact:     apache_url: 'http://example.com/apache'  - name: Download Apache   shell: wget {{ apache_url }} 

See http://docs.ansible.com/set_fact_module.html for the official word.

like image 109
dodgio Avatar answered Oct 13 '22 07:10

dodgio


I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache   vars:     url: czxcxz   shell: wget {{url}}  
like image 21
appleitung Avatar answered Oct 13 '22 06:10

appleitung