1

The basic directory structure of an Ansible role is:

rolename
  files
  templates
  tasks
  ...

Now my question is can the files or templates folders have a directory structure inside them like this:

rolename
  files
  templates
     etc
       hosts
  tasks
  ...

So my task could look like:

- name: Approve hosts file
  template:
    src: ./etc/hosts (I WANT TO REFERENCE THE FILE INSIDE THE TEMPLATES FOLDER)
    dest: /etc/hosts

This does not work :(

How do I reference the file inside the templates folder?

IMPORTANT I do not want a flat structure inside the templates folder because I want to mimic the file system so I know where the file will be copied to just by looking at the templates folder structure.

FYI When I use a flat structure it works.

techraf
  • 64,883
  • 27
  • 193
  • 198
danday74
  • 52,471
  • 49
  • 232
  • 283

1 Answers1

2

The syntax you have included in your question works ok.

Proof:

#!/bin/bash

mkdir -p ./roles/role1
mkdir -p ./roles/role1/files
mkdir -p ./roles/role1/templates/etc
mkdir -p ./roles/role1/tasks

cat >./roles/role1/tasks/main.yml <<TASKS_END
---
- template:
    src: ./etc/hosts
    dest: /tmp/hosts
TASKS_END

cat >./roles/role1/templates/etc/hosts <<TEMPLATE_END
{{ ansible_managed }}
TEMPLATE_END

cat >./playbook.yml <<PLAYBOOK_END
---
- hosts: localhost
  gather_facts: no
  connection: local
  roles:
    - role1
PLAYBOOK_END

ansible-playbook ./playbook.yml
cat /tmp/hosts

Result:

PLAY [localhost] ***************************************************************

TASK [role1 : template] ********************************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0

Ansible managed
techraf
  • 64,883
  • 27
  • 193
  • 198