From eb4521d4897b9ce24013fa2acbfb3f5de2e3a326 Mon Sep 17 00:00:00 2001 From: Ilgar_Naghiyev Date: Thu, 5 Mar 2020 14:58:39 +0100 Subject: [PATCH] file vars lesson completed --- README.md | 49 +++++++++++++++++++++++++++++++-- playbooks/file_var_playbook.yml | 17 ++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 playbooks/file_var_playbook.yml diff --git a/README.md b/README.md index 20f83e3..f9aaed7 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Red Hat Certified Specialist in Ansible Automation (EX407) Preparation Course - [Work with Ansible Variables and Facts](#work-with-ansible-variables-and-facts) - [Ansible Variables Lecture](#ansible-variables-lecture) - [Demo: Ansible Variables - Magic Variables and Jinja Filters](#demo-ansible-variables---magic-variables-and-jinja-filters) - + - [Demo: Ansible Variables - Variable Files](#demo-ansible-variables---variable-files) ## Understanding Core Components of Ansible ### Understanding Core Components of Ansible Part 1 @@ -1036,4 +1036,49 @@ Content of the file after playbook run: ``` [cloud_user@innaghiyev2c playbook]$ cat ../vars/inv.txt innaghiyev1c.mylabserver.com innaghiyev2c.mylabserver.com innaghiyev3c.mylabserver.com -``` \ No newline at end of file +``` + +### Demo: Ansible Variables - Variable Files + +Possible ways to define variable files: +- `var_files` - using it within the playbook to define variables file +- `ansible-playbook var_files_playbook.yml -e "@../vars/users.lst"` - using `-e` key to provide variable file path. + +Here how `users.lst` file looks like: +``` +[cloud_user@innaghiyev2c playbook]$ cat ../vars/users.lst +staff: + - joe + - john + - bob + - sam + - mark +faculty: + - matt + - alex + - frank +other: + - will + - jack +``` + +Cookbook with variable file usage: +``` +--- +- hosts: labservers + vars: + userFile: /home/cloud_user/vars/list + tasks: + - name: create file #going to create file with defined path + file: + state: touch + path: "{{ userFile }}" + - name: list users #add inside of file users name looping through items + lineinfile: + path: "{{ userFile }}" + line: "{{ item }}" + with_items: + - "{{ staff }}" + - "{{ faculty }}" + - "{{ other }}" +``` diff --git a/playbooks/file_var_playbook.yml b/playbooks/file_var_playbook.yml new file mode 100644 index 0000000..9274628 --- /dev/null +++ b/playbooks/file_var_playbook.yml @@ -0,0 +1,17 @@ +--- +- hosts: labservers + vars: + userFile: /home/cloud_user/vars/list + tasks: + - name: create file + file: + state: touch + path: "{{ userFile }}" + - name: list users + lineinfile: + path: "{{ userFile }}" + line: "{{ item }}" + with_items: + - "{{ staff }}" + - "{{ faculty }}" + - "{{ other }}" \ No newline at end of file