简体   繁体   中英

Loop through list and variable in Ansible

I'm going to grant privileges on two MySQL databases to user from to different IP's using Ansible. What I've got now: Vars:

#users
root_user: 'root'
root_password: 'root'
prosody_user: 'prosody'
prosody_password: 'prosody'

#databases
oauth_db: "oauth"

#hosts
prosody_hosts: ['10.0.1.4', '10.0.1.5']

Task:

- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item.host }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item.database }}.*:ALL,GRANT"
  with_items:
  - { host: "{{ prosody_hosts[0] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[0] }}", database: "{{ prosody_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ prosody_db }}" }

Direct calling of array elements doesn't look very nice. I just want loop through prosody_hosts array in with_item directive, сonsidering that database is not an array.

Goal is to to get something like this:

... 
with_items
- { host: "{{ prosody_hosts }}", database: "{{ oauth_db }}" }  
- { host: "{{ prosody_hosts }}", database: "{{ prosody_db }}" }

Thanks in advance!

What you need is nested loops. See this Ansible documentation .

Basically you'd end up with something similar like this. Put your databases in a list called 'databases' like you did with hosts. This will execute the task for every host and every database.
I haven't tested this but it should get pretty close.

- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item[0] }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item[1] }}.*:ALL,GRANT"
  with_nested:
    - "{{ prosody_hosts }}"
    - "{{ databases }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM