codeaprendiz
codeaprendiz

Reputation: 3205

Create multiple directories in ansible by passing list of folders as argument

AIM : To be able to create directories by passing a list as argument in ansible

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



Upvotes: 2

Views: 4187

Answers (1)

aru_sha4
aru_sha4

Reputation: 378

To use the values from var_list_dirs use with_items to loop for all the values in var_list_dirs. This will perform create dirs action for each value in the list.

- name: create dirs
  file:
    path: "{{ item|safe|trim }}"
    state: directory
    owner: "{{ var_user }}"
    group: "{{ var_group }}"
    mode: 0777
    recurse: yes
  with_items: "{{ var_list_dirs }}"
  when:
    - inventory_hostname in groups['node-hostname']
  tags:
    - create-dir

Pass the list as:

var_list_dirs:
  - directory1
  - directory2
  - directory3

Upvotes: 4

Related Questions