Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible-playbook --extra-vars not accepting multiple params within bash script using $@

Tags:

bash

I am wanting to run ansible-playbook from a bash script, where some parameters passed to the script will passed to Ansible in the form of --extra-vars.

EXTRA_VARS="--extra-vars '${@:2}'"
ansible-playbook \
-i hosts_$1 \
$EXTRA_VARS \
playbook.yml

I've put the command over multiple lines because in my script there are several long options passed to ansible and I want to improve readability. If the user does not supply any variables beyond $1, then I just want to execute the playbook.

However, when I run something like:

./myscript inventory VAR1=KEY1 VAR2=KEY2

I get an error:

ERROR! the playbook: VAR2=KEY2' could not be found.

Am I not quoting EXTRA-VARS correctly when I set it? Or is bash doing something funny when it expands the variable?

like image 451
John Avatar asked Feb 11 '26 06:02

John


1 Answers

Don't use a variable; use an array!

extra_vars=("--extra-vars" "${@:2}")

Then pass it to the command with a quoted-array expansion, to not let the words split because of word-splitting:

ansible-playbook \
-i hosts_"$1" \
"${extra_vars[@]}" \
playbook.yml

See BashFAQ/050- I'm trying to put a command in a variable, but the complex cases always fail!

And never use single-quotes(') around shell constructs (variable, array) that need to be expanded, use double-quotes(") instead.

like image 195
Inian Avatar answered Feb 16 '26 02:02

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!