Chaitali
Chaitali

Reputation: 97

How to create directory and file inside the same directory in ansible using single task

Is there any way to create directory and file inside the same directory in ansible using a single task? Currently, in my task, I'm creating a directory using a file module, state= directory. How to touch a file inside that directory in the same task?

Upvotes: 0

Views: 2741

Answers (2)

Santosh Garole
Santosh Garole

Reputation: 1956

@Dom H has given it correctly i just wanted it to give it more convenient way in playbook.

the playbook will look like :

---
- name: Creating directory and files
  hosts: localhost
  become: yes
  become_user: root

  tasks:

  - name: Create a directory with a file inside
    file:
      path: "{{ item.path }}"
      state: "{{ item.state }}"
    loop:
      - { path: /tmp/foo, state: directory }
      - { path: /tmp/foo/bar.txt, state: touch }

and we can actually test before run it using:

 ansible-playbook -i localhost mkdir.yml --check

Upvotes: 1

Dom H.
Dom H.

Reputation: 56

You could use a loop:

- name: Create a directory with a file inside
  file:
    path: "{{ item.path }}"
    state: "{{ item.state }}"
  loop:
    - { path: /tmp/foo, state: directory }
    - { path: /tmp/foo/bar.txt, state: touch }

Upvotes: 2

Related Questions