Unable to create directories from the list
I want to create some directories from a list that I have in vars/main.yml
.
- app_root:
network_prod: "/var/www/prod/network/app"
database_prod: "/var/www/prod/db/app"
Mine tasks/main.yml
still has the following:
- name: Create application directory structure
file:
path: "{{ item }}"
state: directory
mode: 755
with_items:
- app_root
but doesn't work. I thought this could be achieved with with_dict
and I also tried:
- name: Create application directory structure
file:
path: "{{ item.value }}"
state: directory
mode: 755
with_dict:
- app_root
but I got: fatal: [vagrant.dev] => with_dict expects a dict
.
I've read all about looping-over-hashes but it doesn't work.
The reason I use this notation is because I am using these variables elsewhere and I need to know how to call them.
source to share
I personally find it easier to convert yaml to json to make sure I understand it correctly. Let's take your example:
- app_root:
network_prod: "/var/www/prod/network/app"
database_prod: "/var/www/prod/db/app"
What you have here is not a list, but a nested dictionary. If you change that to json it looks like this:
[
{
"app_root": {
"network_prod": "/var/www/prod/network/app",
"database_prod": "/var/www/prod/db/app"
}
}
]
To iterate over this in Ansible you need to dereference two levels of the dictionary, the first one being app_root
and the second one being the path elements. Unfortunately, I don't think Ansible supports looping through nested dictionaries only through nested loops.
Your best bet is probably to repeat the way you define your paths, so as not to create a complex data structure. If all you are doing in this case is iterating over the list of paths to ensure the directories exist, I would suggest something like this in your file vars/main.yml
:
network_prod: "/var/www/prod/network/app"
database_prod: "/var/www/prod/db/app"
app_root:
- network_prod
- database_prod
Then you might have a task like this:
file: path={{ item }}
state=directory
with_items: app_root
source to share
I think the c approach with_dict
was correct, and I believe the only problem here is the dash -
in front of the variable app_root
. Instead:
- name: Create application directory structure
file:
path: "{{ item.value }}"
state: directory
mode: 755
with_dict:
- app_root
It should be:
- name: Create application directory structure
file:
path: "{{ item.value }}"
state: directory
mode: 755
with_dict: app_root
See the difference in the way you pass a variable app_root
to with_dict
.
A dash in YAML starts the list and the items are not treated as variables but as literals, think of it as if you are passing the immutable string "app_root" to with_dict
(not quite right, but it helps me think so) so when_dict
can't parse it because it is assigned a list instead of the expected dictionary. However, without the dash, the with_dict
variable is filled in app_root
instead, and it will parse it without issue.
source to share