0

What i'm trying to do is generating lots of similar directory trees. I woul like to set a dict which describes the pattern of the tree. Then i want ansible to generate multiple directory trees with different indexes, generated from the special list.

Assume this simple playbook:

- hosts: [localhost]
  vars:
    instances: [1,2,3,4]
    dirs:
    - path: "/srvs/hosting{{ instance }}/dir1"
    - path: "/srvs/hosting{{ instance }}/dir2"
#   and so on ......

  tasks:
    - debug:
        msg: "{{ item[1].path }}"
      loop: "{{ instances | product(dirs) | list }}"
      vars:
        instance: "{{ item[0] }}"

When using {{ instance }} var inside the 'path' var i'm getting an error:

fatal: [localhost]: FAILED! => {"msg": "[{'path': '/srvs/hosting{{ instance }}/dir1'}, {'path': '/srvs/hosting{{ instance }}/dir2'}]: {{ item[0] }}: 'item' is undefined"}

What i 'm expecting to get:

ok: [localhost] => (item=[1, {'path': '/srvs/hosting1/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting1/dir1"
    }
}
ok: [localhost] => (item=[1, {'path': '/srvs/hosting1/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting1/dir2"
    }
}
ok: [localhost] => (item=[2, {'path': '/srvs/hosting2/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting2/dir1"
    }
}
ok: [localhost] => (item=[2, {'path': '/srvs/hosting2/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting2/dir2"
    }
}
ok: [localhost] => (item=[3, {'path': '/srvs/hosting3/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting3/dir1"
    }
}
ok: [localhost] => (item=[3, {'path': '/srvs/hosting3/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting3/dir2"
    }
}
ok: [localhost] => (item=[4, {'path': '/srvs/hosting4/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting4/dir1"
    }
}
ok: [localhost] => (item=[4, {'path': '/srvs/hosting4/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting4/dir2"
    }
}

What am i missing?

2
  • You are always welcome to provide a self answered question, but please do put that answer in an actual answer, not in your question. Commented Jul 3, 2024 at 11:05
  • Ok, thanks for pointing out Commented Jul 3, 2024 at 14:59

1 Answer 1

1

I managed to achieve my goal by rearranging {{ dirs }} without use of {{ instance }} as a part of path.

dirs:
- path: "dir1"
- path: "dir2"
   
tasks:
  - debug:
      msg: "/srvs/hosting{{ instance }}/{{ item[1].path }}"
    loop: "{{ instances | product(dirs) | list }}"
    vars:
      instance: "{{ item[0] }}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.