Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of --limit argument inside an Ansible playbook?

Tags:

ansible

In ansible, is it possible to get the value of the argument to the "--limit" option within a playbook? I want to do is something like this:

---
- hosts: all
  remote user: root
  tasks:
  - name: The value of the --limit argument
    debug:
      msg: "argument of --limit is {{ ansible-limit-arg }}"

Then when I run he command:

$ ansible-playbook getLimitArg.yaml --limit webhosts

I'll get this output:

argument of --limit is webhost

Of course, I made up the name of the variable "ansible-limit-arg", but is there a valid way of doing this? I could specify "webhosts" twice, the second time with --extra-args, but that seems a roundabout way of having to do this.

like image 946
awrobinson Avatar asked Jun 30 '17 23:06

awrobinson


People also ask

How do I supply variables while executing the playbook in ansible?

The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.

How do you use limits in ansible?

Ansible command limit optionUsing the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.

How do you call ansible facts in playbook?

Using the Ansible playbook To access the variables from Ansible facts in the Ansible playbook, we need to use the actual name without using the ansible keyword. The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts.


2 Answers

Since Ansible 2.5 you can access the value using a new magic variable ansible_limit, so:

- debug:
    var: ansible_limit
like image 160
techraf Avatar answered Sep 22 '22 19:09

techraf


Have you considered using the {{ ansible_play_batch }} built-in variable?

- hosts: all
  become: "False"
  gather_facts: "False"
  tasks:
    - name: The value of the --limit argument
      debug:
        msg: "argument of --limit is {{ ansible_play_batch }}"
      delegate_to: localhost

It won't tell you exactly what was entered as the argument but it will tell you how Ansible interpreted the --limit arg.

like image 35
Russ Starr Avatar answered Sep 24 '22 19:09

Russ Starr