Ansible playbook supports defining the variable in two forms, Either as a separate file with full of variables and values like a properties file. or a Single liner variable declaration like we do in any common programming languages
vars
to define inline variables within the playbook
vars_files
to import files with variables
Let’s suppose we want to add a few variables for our webserver like the server name and SSL key file and cert file etc.
it can be done with vars
like this
--- - name: Playbook hosts: webservers become: yes become_user: root vars: key_file: /etc/apache2/ssl/mywebsite.key cert_file: /etc/apache2/ssl/mywebsite.cert server_name: www.mywebsite.com tasks: - name: ensure apache is at the latest version yum: name: httpd state: latest ### SOME MORE TASKS WOULD COME HERE ### # you can refer the variable you have defined earlier like this # # "{{key_file}}" (or) "{{cert_file}}" (or) "{{server_name}}" # ## - name: ensure apache is running service: name: httpd state: started
and the variables can be referred with the jinja2 template later"{{ variable name }}"
If you want to keep the variables in a separate file and import it with vars_files
You have to first save the variables and values in the same format you have written in the playbook and the file can later be imported using vars_files like this
--- - name: Playbook hosts: webservers become: yes become_user: root vars_files: - apacheconf.yml tasks: - name: ensure apache is at the latest version yum: name: httpd state: latest ### SOME MORE TASKS WOULD COME HERE ### # you can refer the variable you have defined earlier like this # # "{{key_file}}" (or) "{{cert_file}}" (or) "{{server_name}}" # ## - name: ensure apache is running service: name: httpd state: started
the content of the apacheconf.yml
would be like this
key_file: /etc/apache2/ssl/mywebsite.key cert_file: /etc/apache2/ssl/mywebsite.cert server_name: www.mywebsite.com
to keep things cleaner and to keep your playbook simple, It is recommended to use separate variable files and when you are creating ansible roles, you would have to use the variable files more than defining it inline.
![](https://i0.wp.com/myfuturehub.com/wp-content/uploads/2022/08/MFH_DevOps-2.png?resize=112%2C158&ssl=1)