Ansible vars_prompt and msg usage prints hello world - ansible

Based on input from Zeitounator I have updated the original question. The following works
root#devenv:~/scripts/uia# cat addVlanTest.yml
---
- name: PLAY 111 Add Vlan ;
hosts: all
vars_prompt:
- name: vlanIdToAdd
prompt: vlan ID to add
private: no
default: "50"
tasks:
- name: "Debug task Take 1"
ansible.builtin.debug:
var: vlanIdToAdd
- name: "Debug task Take 2"
ansible.builtin.debug:
msg: "{{ vlanIdToAdd }}"
- name: "Debug task Take 3"
ansible.builtin.debug:
msg: "Creating vlan {{ vlanIdToAdd }}"
Correct:
msg: "Creating vlan {{ vlanIdToAdd }}"
Incorrect:
msg:"Creating vlan {{ vlanIdToAdd }}"
What is the scope ? Variables do not survive after plays. If you need to use it in a different play save it.
root#devenv:~/scripts/uia# cat addVlanTest.yml
---
- name: PLAY 111 Add Vlan ;
hosts: all
vars_prompt:
- name: vlanIdToAdd
prompt: vlan ID to add
private: no
default: "50"
tasks:
- name: "Debug vars Take 1"
debug:
var=vlanIdToAdd
- name: "Debug vars Take 1"
set_fact:
new_vlan_id="{{ vlanIdToAdd }}"
- name: PLAY 112 Add Vlan - IOS;
hosts: ios
tasks:
- name: "Debug vars Take 2"
debug:
var=new_vlan_id

As reported in my comment, vars_prompt are only available inside a given play as this is their scope. This is explained in plabooks variable documentation
From my suggestion, you have tried to use set_fact. As you will see in the same documentation, those vars are scoped to host and are only available while playing a task on host having the given fact. Meanwhile, you can access facts from other host using the hostvars magic variable
Here is one way to work arround this kind of chicken-egg problem. It might not be exactly what you are looking for but will hopefully give you some ideas for your best solution. I tried to make it self explanatory.
The following test.yml playbook:
---
- name: Play dedicated to vars_prompt and storing facts in localhost
hosts: localhost
gather_facts: false
vars_prompt:
- name: my_prompt
prompt: enter a value
private: no
tasks:
- name: store prompt in fact
set_fact:
my_prompt: "{{ my_prompt }}"
- name: Use fact on host a by directly calling it in a task
hosts: a
gather_facts: false
tasks:
- name: display the fact
debug:
msg: "{{ hostvars['localhost'].my_prompt }}"
- name: Use the fact on host b by first assigning to a play var
hosts: b
gather_facts: false
vars:
my_prompt: "{{ hostvars['localhost'].my_prompt }}"
tasks:
- name: display the fact
debug:
msg: "{{ my_prompt }}"
Gives:
$ ansible-playbook -i a,b, test.yml
enter a value: toto
PLAY [Play dedicated to vars_prompt and storing facts in localhost] ************************************************************************************************************************************************
TASK [store prompt in fact] ***************************************************************************************************************************************************************************************
ok: [localhost]
PLAY [Use fact on host a by directly calling it in a task] ********************************************************************************************************************************************************
TASK [display the fact] *******************************************************************************************************************************************************************************************
ok: [a] => {
"msg": "toto"
}
PLAY [Use the fact on host b by first assigning to a play var] ****************************************************************************************************************************************************
TASK [display the fact] *******************************************************************************************************************************************************************************************
ok: [b] => {
"msg": "toto"
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
a : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
b : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Meanwhile, if this is possible in your scenario, you can as well set the fact on all hosts in your inventory so as to reuse it anywhere, this makes a much simpler playbook:
---
- name: Play dedicated to vars_prompt and storing facts on all host (except implicit localhost)
hosts: all
gather_facts: false
vars_prompt:
- name: my_prompt
prompt: enter a value
private: no
tasks:
- name: store prompt in fact
set_fact:
my_prompt: "{{ my_prompt }}"
- name: Use fact on host a
hosts: a
gather_facts: false
tasks:
- name: display the fact
debug:
msg: "{{ my_prompt }}"
- name: Use the fact on host b
hosts: b
gather_facts: false
tasks:
- name: display the fact
debug:
msg: "{{ my_prompt }}"
- name: Simple demo implicit localhost is not part of the all group and does not have the fact
hosts: localhost
gather_facts: false
tasks:
- name: show fact is undefined on localhost
debug:
var: my_prompt
Gives:
$ ansible-playbook -i a,b, test.yml
enter a value: titi
PLAY [Play dedicated to vars_prompt and storing facts on all host (except implicit localhost)] ********************************************************************************************************************
TASK [store prompt in fact] ***************************************************************************************************************************************************************************************
ok: [a]
ok: [b]
PLAY [Use fact on host a] *****************************************************************************************************************************************************************************************
TASK [display the fact] *******************************************************************************************************************************************************************************************
ok: [a] => {
"msg": "titi"
}
PLAY [Use the fact on host b] *************************************************************************************************************************************************************************************
TASK [display the fact] *******************************************************************************************************************************************************************************************
ok: [b] => {
"msg": "titi"
}
PLAY [Simple demo implicit localhost is not part of the all group and does not have the fact] *********************************************************************************************************************
TASK [show fact is undefined on localhost] ************************************************************************************************************************************************************************
ok: [localhost] => {
"my_prompt": "VARIABLE IS NOT DEFINED!"
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
a : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
b : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Related

How to make a variable available across multiple ansible playbooks?

In my first playbook, I am asking user for a value and storing in a variable. I would like that variable to be accessible in other playbooks. There is only one host in the inventory btw.
My first playbook:
---
- name: Get the name of the city from the user
hosts: all
gather_facts: yes
vars_prompt:
- name: my_city
prompt: "Enter the name of city: "
private: no
tasks:
- name: Set fact for city
set_fact:
city: "{{ my_city }}"
cacheable: yes
In another playbook, when I try to print the variable I set in the previous one, I get an error:
---
- name: Print a fact
hosts: all
gather_facts: yes
tasks:
- name: Print ansible_facts['city'] variable
debug:
msg: "Value of city variable is {{ ansible_facts['city'] }}"
Error:
fatal: [testing]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'city'\n\nThe error appears to be in '/home/user/ansible_tasks/print_fact.yml': line 6, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: Print ansible_facts['city'] variable\n ^ here\n"}
Enable the cache if you want to use it. For example,
shell> grep fact_caching ansible.cfg
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_cache
fact_caching_prefix = ansible_facts_
fact_caching_timeout = 86400
Then the playbook below
shell> cat pb1.yml
- hosts: localhost
gather_facts: false
tasks:
- set_fact:
city: my_city
cacheable: true
will store the variable city in the cache
shell> cat /tmp/ansible_cache/ansible_facts_localhost
{
"city": "my_city"
}
The next playbook
shell> cat pb2.yml
- hosts: localhost
gather_facts: false
tasks:
- debug:
var: city
will read the cache
shell> ansible-playbook pb2.yml
PLAY [localhost] *****************************************************************************
TASK [debug] *********************************************************************************
ok: [localhost] =>
city: my_city
PLAY RECAP ***********************************************************************************
localhost: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
If you want to cache the same variable in multiple hosts, for example
shell> cat hosts
host_1
host_2
host_3
it is sufficient to run the module set_fact once. The playbook
shell> cat pb3.yml
- hosts: all
gather_facts: false
tasks:
- set_fact:
city: my_city
cacheable: true
run_once: true
will store the variable city in the cache of all hosts
shell> grep -r city /tmp/ansible_cache/
/tmp/ansible_cache/ansible_facts_host_3: "city": "my_city"
/tmp/ansible_cache/ansible_facts_host_1: "city": "my_city"
/tmp/ansible_cache/ansible_facts_host_2: "city": "my_city"
The next playbook
shell> cat pb4.yml
- hosts: all
gather_facts: false
tasks:
- debug:
var: city
will read the cache
shell> ansible-playbook pb4.yml
PLAY [all] ***********************************************************************************
TASK [debug] *********************************************************************************
ok: [host_1] =>
city: my_city
ok: [host_2] =>
city: my_city
ok: [host_3] =>
city: my_city
PLAY RECAP ***********************************************************************************
host_1: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
host_2: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
host_3: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Fetch hosts without domain from inventory file

I have following inventory file
$ cat hosts
[web]
server1.example.com
server2.example.com
I would like to fetch the hostname, without the part of domain (.example.com).
I tried with the following playbook, however, it is still fetching with the entire hostname..
$ playbook.yaml
- hosts: localhost
tasks:
- debug:
msg: "{{ groups['web'] }}"
Output
PLAY [localhost] *************************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************************
ok: [localhost]
TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
"server1.example.com"
"server2.example.com"
]
}
PLAY RECAP *******************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Expected output
PLAY [localhost] *************************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************************
ok: [localhost]
TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
"server1"
"server2"
]
}
PLAY RECAP *******************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
You can get what you want from a magic variable called inventory_hostname_short which basically returns anything before the first . found in the inventory_hostname.
To get this in a normal play host loop, it's as easy as:
- hosts: all
tasks:
- name: show target short name
debug:
var: inventory_hostname_short
If you need to get that for hosts not in the host loop, you will have to go through hostvars. Here is an example to get all those names in a list for a given group running from localhost:
- hosts: localhost
gather_facts: false
tasks:
- name: show list of shortnames for group 'toto'
debug:
msg: "{{ groups['toto'] | map('extract', hostvars, 'inventory_hostname_short') }}"
An other example to get that name only for the first server in group 'toto'
- hosts: localhost
gather_facts: false
tasks:
- name: show shortnames for first server in group 'toto'
vars:
server_name: "{{ groups['toto'][0] }}"
debug:
msg: "{{ hostvars[server_name].inventory_hostname_short }}"

Ansible hosts to be set to a substring of a passed variable

I have a play like this:
- name: Perform an action on a Runtime
hosts: all
roles:
- role: mule_action_on_Runtime
A variable at invocation (--extra-vars 'mule_runtime=MuleS01-3.7.3-Testing') has a prefix of the host needed (MuleS01). I want to set hosts: MuleS01. How do I do this?
Given that your pattern is always PartIWant-PartIDonCareAbout-AnotherPartAfterOtherDash you could use the split method of Python, then get the first item of the list via the Jinja filter first.
Here is full working playbook as example:
- hosts: local
gather_facts: no
tasks:
- debug:
msg: "{{ mule_runtime.split('-') | first }}"
This yield the recap:
play.yml --extra-vars 'mule_runtime=MuleS01-3.7.3-Testing'
PLAY [local] *******************************************************************
TASK [debug] *******************************************************************
ok: [local] => {
"msg": "MuleS01"
}
PLAY RECAP *********************************************************************
local : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
With the inventory
shell> cat hosts
MuleS01
MuleS02
MuleS03
this playbook
shell> cat pb.yml
- hosts: all
tasks:
- debug:
msg: Set {{ mule_runtime }}
when: mule_runtime.split('-').0 == inventory_hostname
gives
skipping: [MuleS02]
ok: [MuleS01] => {
"msg": "Set MuleS01-3.7.3-Testing"
}
skipping: [MuleS03]

Ansbile get the substring from task output

I have this URL string server https://test.example.com:6443. I need to extract only hostname test from it using Ansible task.
came up with this playbook, Is there a better way of doing this with-out using sed?
- hosts: localhost
connection: local
gather_facts: no
tasks:
- name: get the URL
shell: echo 'server https://test.example.com:6443' |sed -e 's/^.*https...//' -e 's/\..*$//'
register: result
- name: Print the var
debug:
msg: "{{ result.stdout }}"
Output
PLAY [localhost] *********************************************************************************************************************
TASK [get the URL] *******************************************************************************************************************
changed: [localhost]
TASK [Print the var] *****************************************************************************************************************
ok: [localhost] => {
"msg": "test"
}
PLAY RECAP ***************************************************************************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
You can use split on the URL name and get the desired value, Ideally hostname should be test.example.com in your case. However, you can customize the split function based on your need also as below.
- hosts: localhost
connection: local
gather_facts: no
vars:
url: "https://test.example.com:6443"
tasks:
- name: Print the hostname var
debug:
msg: "{{ url.split(':')[1].split('//')[1] }}"
- name: Print the subdomain prefix
debug:
msg: "{{ url.split(':')[1].split('//')[1].split('.')[0] }}"

Passing variables between nested playbooks

I have a playbook where I'm spinning up an instance in aws with the ec2 module. To be more flexible I ask via prompt for the hostname. I found in the ec2 examples the code snippet, which allows you to run a second playbook with newly spun up instance for further configuration.
Now I want to set the hostname via module hostname but I cannot access the variable in the second playbook.
This is how my playbook looks like:
---
- hosts: localhost
...
vars_prompt:
- name: var_hostname
prompt: "Please enter the hostname"
private: no
tasks:
- name: Spin up instance
local_action:
module: ec2
...
register: ec2
- name: Add new instance to host group
add_host: hostname={{ item.public_ip }} groupname=launched
with_items: ec2.instances
- hosts: launched
...
tasks:
- name: Set hostname
hostname: name="{{ var_hostname }}"
fatal: [launched] => One or more undefined variables: 'var_hostname' is undefined
Is there a way to pass a variable from one playbook to another one?
I found Ansible best practice for passing vars to nested playbooks? but unfortunately it didn't had a solution which I can use.
You can use set_fact and hostvars together to achieve what you want.
Do set_fact on one group of hosts( i.e localhost), and access them in a different play using hostvars
{{hostvars['localhost']["new_fact"]}}
You can use local files.
1) Write
- name: write public ip
local_action:
template:
dest: /tmp/ansible_master_public_ip.txt
src: templates/public_ip.j2
2) Retrieve with http://docs.ansible.com/ansible/playbooks_lookups.html
hostname: "{{ lookup('file', '/tmp/ansible_master_public_ip.txt') | trim }}"
PS. Ini file lookup also an option if you need more than few variables.
Add the host's variable to the parameters. For example,
- name: Add new instance to host group
add_host:
hostname: "{{ ec2.instances.0.public_ip }}"
groupname: launched
var_hostname: "{{ var_hostname }}"
See examples
Use only the first item from the list because you have only one hostname. There is no reason to iterate the list.
Example of a complete playbook for testing
- hosts: localhost
gather_facts: false
vars_prompt:
- name: var_hostname
prompt: "Please enter the hostname"
private: no
vars:
ec2:
instances:
- public_ip: AAA.BBB.CCC.DDD
tasks:
- name: Add new instance to host group
add_host:
hostname: "{{ ec2.instances.0.public_ip }}"
groupname: launched
var_hostname: "{{ var_hostname }}"
- hosts: launched
gather_facts: false
tasks:
- debug:
var: var_hostname
shell> ansible-playbook pb.yml
Please enter the hostname: host_2
PLAY [localhost] *****************************************************************************
TASK [Add new instance to host group] ********************************************************
changed: [localhost]
PLAY [launched] ******************************************************************************
TASK [debug] *********************************************************************************
ok: [AAA.BBB.CCC.DDD] =>
var_hostname: host_2
PLAY RECAP ***********************************************************************************
AAA.BBB.CCC.DDD: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Use pause instead of vars_prompt if you have more hosts. For example,
- name: Get var_hostname(s)
pause:
prompt: "Please enter the hostname for {{ item.public_ip }}"
echo: yes
loop: "{{ ec2.instances }}"
register: var_hostnames
- name: Add new instances to host group
add_host:
hostname: "{{ item.item.public_ip }}"
groupname: launched
var_hostname: "{{ item.user_input }}"
loop: "{{ var_hostnames.results }}"
loop_control:
label: "{{ item.user_input }}"
Example of a complete playbook for testing
- hosts: localhost
gather_facts: false
vars:
ec2:
instances:
- public_ip: AAA.BBB.CCC.DD1
- public_ip: AAA.BBB.CCC.DD2
tasks:
- name: Get var_hostname(s)
pause:
prompt: "Please enter the hostname for {{ item.public_ip }}"
echo: yes
loop: "{{ ec2.instances }}"
register: var_hostnames
- name: Add new instances to host group
add_host:
hostname: "{{ item.item.public_ip }}"
groupname: launched
var_hostname: "{{ item.user_input }}"
loop: "{{ var_hostnames.results }}"
loop_control:
label: "{{ item.user_input }}"
- hosts: launched
gather_facts: false
tasks:
- debug:
var: var_hostname
shell> ansible-playbook pb.yml
PLAY [localhost] *****************************************************************************
TASK [Get var_hostname(s)] *******************************************************************
[Get var_hostname(s)]
Please enter the hostname for AAA.BBB.CCC.DD1:
host_1^Mok: [localhost] => (item={'public_ip': 'AAA.BBB.CCC.DD1'})
[Get var_hostname(s)]
Please enter the hostname for AAA.BBB.CCC.DD2:
host_2^Mok: [localhost] => (item={'public_ip': 'AAA.BBB.CCC.DD2'})
TASK [Add new instances to host group] *******************************************************
ok: [localhost] => (item=host_1)
ok: [localhost] => (item=host_2)
PLAY [launched] ******************************************************************************
TASK [debug] *********************************************************************************
ok: [AAA.BBB.CCC.DD1] =>
var_hostname: host_1
ok: [AAA.BBB.CCC.DD2] =>
var_hostname: host_2
PLAY RECAP ***********************************************************************************
AAA.BBB.CCC.DD1: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
AAA.BBB.CCC.DD2: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Resources