3

Is it possible to substitute hosts: target with variable?

- name: ansible application deploy
  hosts: {{ vm_ip }}
  vars:
    project_path: "{{ host_project_path|default('/var/www/html') }}"

I have tried passing vm_ip using --extra-vars="vm_ip: IPP_ADDR " on the command line, but it never worked.

3
  • I can't imagine a need for that. Could you explain why you need this? There is a lot of ways to do this without using a variable on hosts. Commented Jan 10, 2016 at 0:56
  • I'm developing rails application that would execute ansible scripts to automate few things in the backend, and script needs to run against different VMs based on the task, can you think of any idea on how I would go about replacing hosts value? I was thinking about running sed or awk first then run the script, but using variable would be cleaner Commented Jan 10, 2016 at 0:59
  • Why don't set hosts: all, or set to a group that contains all VMs of that application and just execute the playbook with -l vm_ip Commented Jan 10, 2016 at 1:02

3 Answers 3

2

I would rather just set hosts:all and execute the playbook with limit to only the host you need to execute.

- name: ansible application deploy
  hosts: all
  vars:
    project_path: "{{ host_project_path|default('/var/www/html') }}"

Execute the playbook using the limit clause:

ansible-playbook app_deploy.yml -l IPP_ADDR

Another possibilite is creating a file with the ip address.

/tmp/execute_only_that_host

FILE CONTENT:

IPP_ADDR

Executing: ansible-playbook app_deploy.yml -l @/tmp/execute_only_that_host

I recommend this approach because it's your own application that will call your playbook, you can always insure it called with limit, therefore you don't need to bother with hosts in the top of your playbook.

Sign up to request clarification or add additional context in comments.

Comments

1

I wouldn't use limit, if you forget to specify that by mistake, then it will run on all hosts which is dangerous. Your command line is wrong. Try:

--extra-vars "vm_ip=IP_ADDR"

and

hosts: "{{ vm_ip }}"

Comments

0

You can pass it from the command line, yes.

Make sure you have valid yaml:

hosts: "{{ vm_ip }}"

That expression has to be quoted or you run into the yaml gotcha.

But the hosts have to be defined in the inventory first and I guess this is the piece you're missing. That pretty much makes it pointless as there is no advantage over using hosts: all with a --limit as described by @Bernardo Vale - but is more ansible standard.

Comments

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.