Nested Loop Variables

Hi there

I’ve searched for days for a clear and straight forward answer to this question.

In the following nested loop I want to use variables instead of the static values I have there.

  • name: Create/assign database users to db and grant permissions

mysql_user: name={{ item[0] }} password={{ item[1] }} priv={{ item[2] }}.*:ALL state=present login_host={{ item[3] }}
with_nested:

  • ‘john’
  • ‘john1234’
  • ‘sample.sql’
  • [‘localhost’,‘%’]

Actually, that doesn’t even work. So I’m already stuck.

Then in my group_vars I have defined variables:

env:
db_import: sample.sql
db_name: sample_db
db_user: john
db_password: john1234

I’ve tried all sorts of ways of using variables instead of the static values.

Can anyone help me with this?

Thanks in advance.

" with_nested:

  • ‘john’
  • ‘john1234’
  • ‘sample.sql’
  • [‘localhost’,‘%’]

It looks like the first should be a list of usernames, and the second should be a list of files, but you are specifying strings instead – which is what you would do if those were variable names.

with_nested:

  • [ ‘john’, ‘john1234’ ]
  • [ ‘sampel.sql’]
  • [ ‘localhost’, ‘%’ ]

OR:

with_nested:

  • db_users
  • sql_files
  • hosts

etc

Thanks for your help, I’ll give this a go.

This is the yaml I’m running and it’s giving an error:

  • name: Create/assign database users to db and grant permissions
    mysql_user: name={{ item[0] }} password={{ item[1] }} priv={{ item[2] }}.*:ALL state=present login_host={{ item[3] }}
    with_nested:
  • [ ‘john’ ]
  • [ ‘john1234’ ]
  • [ ‘sample.sql’ ]
  • [ ‘localhost’, ‘%’ ]

It’s a database error, so nothing with “with_nested”.

Key part:

“You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘.* TO ‘john’@‘localhost’’ at line 1”

If I run this…

  • name: Create/assign database user to db and grant permissions
    mysql_user: name={{ item.env.db_user }}
    password={{ item.env.db_password }}
    priv={{ item.env.db_name | default(item.site_name) }}.*:ALL,GRANT
    state=present
    login_host={{ item.env.db_host | default(‘localhost’) }}
    with_items: web_site

If item:env.db_host == ‘localhost’ it works.

If item:env.db_host == ‘%’ it fails.

Seems reasonable to me since that’s not a valid hostname?