1

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']"';

2 Answers 2

4

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'] \
  "
Sign up to request clarification or add additional context in comments.

1 Comment

I am not clear about the exact format of the --extra-vars parameter when combining string and non-string data, as you have done. It is possible that you will need to format the whole string as JSON. In which case, you might have the most luck using jq to create a JSON string from your inputs, and then passing that in as a parameter to ansible-playbook
1

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.

1 Comment

This. I was using the variable action which is reserved. Also I just ended up using a -e for each variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.