Pavel Polushin
Pavel Polushin

Reputation: 401

How to pass array to ansible extra-vars from bash script

I'm trying to write a bash script that will invoke ansible playbook with extra-vars. Some of this vars is an array of strings with spaces. So i am very confused in how to pass them correctly. I already tried many combinations of quotes and slashes. So I came here for help.

ansible-playbook -i inventory.yml playbook.yml --extra-vars \
'username="${login}" fullname="${username}" password="${password}" groups="['Users','Remote Desktop Users']"';

Upvotes: 1

Views: 5386

Answers (2)

Pavel Polushin
Pavel Polushin

Reputation: 401

It seems that variable name 'groups' is reserved by ansible. I changed name, and script starts working. The answer of Andrew Vickers is also correct.

Upvotes: 1

Andrew Vickers
Andrew Vickers

Reputation: 2654

This is what you need to know about bash variables and quoting:

For the following examples, the variable ${text} is set to Hello:

  1. Variables are expanded inside double quotes. e.g. "${text}" => Hello
  2. Variables are not expanded inside single quotes. e.g. '${text}' => ${text}
  3. Single quotes have no special meaning inside double quotes and vice-versa. e.g. "'${text}'" => 'Hello' and '"${text}"' => "${text}"
  4. If you need to place a double-quote inside a double-quoted string, or a single quote inside a single-quoted string, then it must be escaped. e.g. "\"${text}\"" => "Hello" and '\'${text}\'' => '${text}'

With all that said, in your case, you want the variables to be expanded, so you should enclose the entire --extra-vars value in double quotes. According to the Ansible website, the value of each of these extra variables does not need to be quoted, unless it contains spaces. To be safe, you can quote the variables as you might not be able to control their values.

Try this. I have added extra line breaks to make the code easier to understand:

ansible-playbook -i inventory.yml playbook.yml --extra-vars \
  "username='${login}' \
   fullname='${username}' \
   password='${password}' \
   groups=['Users','Remote Desktop Users'] \
  "

Upvotes: 4

Related Questions