-1

I can't seem to run ansible commands inside shell scripts. Whenever I run ansible or ansible-playbook commands, it fails with the below error:

./check_best_host_for_vm_creation.sh: line 9: syntax error near unexpected token `ansible-playbook'

I am sure that the ansible-playbook command is correct and there is nothing wrong with it, as I am able to execute it successfully from outside the script.

The full script is:

#!/bin/bash


hostname_selected=''


for host in 10.28.187.153 10.28.143.10 do

ansible-playbook /etc/ansible/gather_vcenter_facts.yml --extra-vars "esxi_hostname=$host"

host_memory=`cat /etc/ansible/files/tmp_host_memory`

if [ "$host_memory" -eq 4000]; then
ansible-playbook /etc/ansible/create_vms_on_host.yml --extra-vars "esxi_hostname='$host'"
$hostname_selected=$host
break
fi


done

if ["$hostname_selected = '']; then
echo "No host available with free memory"
else
echo "Script done and the VM is created on host $hostname_selected "
fi
~

File names are correct, as well as paths.

Omar Abdelrazik
  • 345
  • 1
  • 3
  • 16
  • Bash is space aware. It's not `4000]; then`, but `4000 ]; then`. Not `["$hostname_selected = '']` but `[ "$hostname_selected" = '' ]`. Also there is a `;` after `for i in ... ; do`. Please use tools like https://www.shellcheck.net/ to check most common mistakes in shell scripts – KamilCuk Nov 22 '19 at 19:12
  • Possible duplicate of [Why should there be a space after '\[' and before '\]' in Bash?](https://stackoverflow.com/q/9581064/608639) Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck). – jww Nov 22 '19 at 21:11

1 Answers1

1

There were several indentation, spacing and syntax errors. I corrected to this. Please try and let me know if it works now.

#!/bin/bash

hostname_selected=''

for host in '10.28.187.153' '10.28.143.10' 
do

    ansible-playbook /etc/ansible/gather_vcenter_facts.yml --extra-vars "esxi_hostname=$host"
    host_memory=$( cat /etc/ansible/files/tmp_host_memory )

    if [ "$host_memory" -eq 4000 ]
    then
        ansible-playbook /etc/ansible/create_vms_on_host.yml --extra-vars "esxi_hostname='$host'"
        hostname_selected=$host
        break
    fi
done

if [ "$hostname_selected" = '' ]
then
    echo "No host available with free memory"
else
    echo "Script done and the VM is created on host $hostname_selected"
fi

Regards!

Matias Barrios
  • 3,700
  • 2
  • 12
  • 33