Just a quick self-note for those cases where you want an Ansible dictionary with multiple values per key, e.g. username and password combinations. The syntax is not difficult but this may save others time since the docs and Google don’t make it terribly obvious.

The syntax for the actual nested variables/values follows the below syntax. The numbering is, as far as I can tell, unavoidable (let me know otherwise!).


    db_username: root
    password: "{{ root_password }}"
    db_username: user1
    password: "{{ user1_password }}"
    db_username: user2
    password: "{{ user2_password }}"
    db_username: user3
    password: "{{ user3_password }}"

You can then refer to these variables in your playbook using the syntax below. In this example, we’re going to use the ansible mysql_user module to assign permissions to all databases.

- name: Create MySQL user for WordPress
    name: "{{ item.value.db_username }}"
    password: "{{ item.value.password }}"
    priv: "{{ database_names }}.*:ALL"
    state: present
    login_user: root
  loop: '{{db_user_accounts | dict2items }}'
  no_log: true

So above we’re looping through the db_user_accounts compound-variable; but on each iteration we’re piping to the jinja dict2items filter. While not strictly required, the above example also uses the no_log setting (which can be used on pretty much any Ansible module) to prevent outputting the task and thereby preventing your passwords from appearing.

Leave a Reply

Your email address will not be published. Required fields are marked *