AIM : To be able to create directories by passing a list as argument in ansible
- I am able to do so while running the playbook on localhost
- However, but when I run it on remote host, it fails as the
lookup
happens on my machine and not the remote machine. - I want to be able to create directories by passing a list
var_list_dirs
which i can set in the playbook. This way my roles does not need to change no matter how many playbooks want to create the directories.
Any help would be appreciated.
playbook-create-directory.yaml
################ SAMPLE USAGE #################################################################################
# ansible-playbook playbook-create-directory.yaml --tags="set-user,create-dir"
###############################################################################################################
- name: create directory
hosts: gcp
become: true
vars:
### CREATE USERS
var_user: "test"
var_group: "test"
### CREATE DIRECTORIES
var_context: "test"
var_mount_path: "/data"
context: "{{ var_context }}"
var_context_opt_dir: "/opt/{{ context }}"
var_context_config_dir: "{{ var_context_opt_dir }}/config"
var_context_log_dir: "{{ var_mount_path }}/log/{{ context }}"
var_context_data_dir: "{{ var_mount_path }}/var/lib/{{ context }}"
var_context_backup_dir: "{{ var_mount_path }}/var/{{ context }}-backup"
var_list_dirs: "{{ var_context_opt_dir }}
{{ var_context_config_dir }}
{{ var_context_log_dir }}
{{ var_context_data_dir }}
{{ var_context_backup_dir }}"
roles:
- { role: user, tags: [ 'user' ] }
- { role: directory, tags: [ 'directory'] }
main.yaml
---
## https://stackoverflow.com/questions/1271222/replace-whitespace-with-a-comma-in-a-text-file-in-linux
- name: get list of directories
shell: |
echo "{{ var_list_dirs }}" | tr " " "\n" > /tmp/dirs.txt
tags:
- create-dir
- name: create dirs
file:
path: "{{ item|safe|trim }}"
state: directory
owner: "{{ var_user }}"
group: "{{ var_group }}"
mode: 0777
recurse: yes
with_lines: cat /tmp/dirs.txt
tags:
- create-dir