Ansible looping over nested variables

Ahmet Kaftan
cloudnesil
Published in
2 min readApr 17, 2019

Rancher 2.x has powerful api which you can use with ansible and other automation tools. Let’s assume we have scenario that we are using Rancher for creating and deploying kubernetes resources with ansible. We need to create some projects and namespaces within Rancher. We will use the following variables to create Rancher projects and namespaces.

```
projects:
project-a:
- namespace-x
- namespace-y
project-b:
- namespace-z
```

Each namespace should be created in the related project. In order to achieve this goal we will use loop over nested variables. We will use the following ansible playbook:

```
- name: Check if {{ roleinputvar }} project already exists
uri:
url: "{{ rancher_endpoint }}/cluster/{{ cluster_id }}/projects/?name={{ roleinputvar }}"
return_content: "yes"
validate_certs: "no"
body_format: json
force_basic_auth: "yes"
user: "{{ rancher_username }}"
password: "{{ rancher_secret_key }}"
method: GET
register: check_projects
- name: Create {{ roleinputvar }} project
uri:
url: "{{ rancher_endpoint }}/projects"
return_content: "yes"
validate_certs: "no"
body_format: json
force_basic_auth: "yes"
user: "{{ rancher_username }}"
password: "{{ rancher_secret_key }}"
status_code: 201
method: POST
body:
clusterId: "{{ cluster_id }}"
name: "{{ roleinputvar }}"
description: '{{ roleinputvar }} Project'
when: check_projects.json.data | length == 0
- name: Set project_name for project {{ roleinputvar }}
set_fact:
project_name: "{{ check_projects.json.data[0].name }}"
- name: Set project_id for project {{ roleinputvar }}
set_fact:
project_id: "{{ check_projects.json.data[0].id }}"
- name: Create namespace {{ projects[project_name] }}
uri:
url: "{{ rancher_endpoint }}/cluster/{{cluster_id}}/namespaces"
validate_certs: "no"
body_format: json
force_basic_auth: "yes"
user: "{{ rancher_username }}"
password: "{{ rancher_secret_key }}"
status_code: 201
method: POST
body:
projectId: "{{ project_id }}"
name: "{{ item }}"
description: "{{ item }} Namespace"
register: create_ns
with_items: "{{ projects[project_name] }}"
failed_when:
- 'create_ns.json.type != "error"'
- 'create_ns.json.type != "namespace"'
```

--

--