Using extra-var to call a defined variable in ansible - variables

Is this possible? I have a playbook looking like this:
vars:
BDNAME: ""
- name: Add a tenant using a JSON string
aci_bd:
tenant: "common"
bd: "{{ BDNAME }}"
vrf: "PIGGE"
hostname: '1.1.1.1'
username: "x"
password: "x"
use_ssl: yes
validate_certs: false
It works if i provide an extra variable in the commandline:
ansible-playbook apic.yml -i server.yml --extra-vars BDNAME='pooh'
Then BDNAME gets the value pooh.
But is there any way that i can define pooh as a variable. So if i run the playbook like i just did, BDNAME get the value of that variable.
So something like
vars:
BDNAME: ""
POOH: nisse
Then BDNAME should be nisse.

Define BDNAME in playbook directly from the extra variable POOH. That should do what you want. But it would be easier to use POOH instead of BDNAME.
Here is a example playbook:
---
- hosts: localhost
vars:
BDNAME: "{{ POOH }}"
tasks:
- name: print BDNAME
debug:
msg: "{{ BDNAME }}"
if you call it with:
ansible-playbook playbook.yml -e '{"POOH": "Oliver"}'
you will see:
TASK [print BDNAME] **********************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"changed": false,
"msg": "Oliver"
}

Related

Overwrite vars_prompt variable in playbook with host variable from inventory in Ansible

I want to overwrite some variables in my playbook file from the inventory file for a host that are defined as "vars_prompt". If I understand it correctly, Ansible shouldn't prompt for the variables if they were already set before, however, it still prompts for the variables when I try to execute the playbook.
How can I overwrite the "vars_prompt" variables from the inventory or is this not possible because of the variable precedence definition of Ansible?
Example:
playbook.yml
---
- name: Install Gateway
hosts: all
become: yes
vars_prompt:
- name: "hostname"
prompt: "Hostname"
private: no
...
inventory.yml
---
all:
children:
gateways:
hosts:
gateway:
ansible_host: 192.168.1.10
ansible_user: user
hostname: "gateway-name"
...
Q: "If I understand it correctly, Ansible shouldn't prompt for the variables if they were already set before, however, it still prompts for the variables when I try to execute the playbook."
A: You're wrong. Ansible won't prompt for variables defined by the command line --extra-vars. Quoting from Interactive input: prompts:
Prompts for individual vars_prompt variables will be skipped for any variable that is already defined through the command line --extra-vars option, ...
You can't overwrite vars_prompt variables from the inventory. See Understanding variable precedence. Inventory variables (3.-9.) is lower precedence compared to play vars_prompt (13.). The precedence of extra vars is 22.
Use the module pause to ask for the hostname if any variable is not defined. For example, the inventory
shell> cat hosts
host_1
host_2
and the playbook
hosts: all
gather_facts: false
vars:
hostnames: "{{ ansible_play_hosts_all|
map('extract', hostvars, 'hostname')|
list }}"
hostnames_undef: "{{ hostnames|from_yaml|
select('eq', 'AnsibleUndefined')|
length > 0 }}"
tasks:
- debug:
msg: |
hostnames: {{ hostnames }}
hostnames_undef: {{ hostnames_undef }}
run_once: true
- pause:
prompt: "Hostname"
register: out
when: hostnames_undef
run_once: true
- set_fact:
hostname: "{{ out.user_input }}"
when: hostname is not defined
- debug:
var: hostname
gives
shell> ansible-playbook pb.yml
PLAY [all] ************************************************************************************
TASK [debug] **********************************************************************************
ok: [host_1] =>
msg: |-
hostnames: [AnsibleUndefined, AnsibleUndefined]
hostnames_undef: True
TASK [pause] **********************************************************************************
[pause]
Hostname:
gw.example.com^Mok: [host_1]
TASK [set_fact] *******************************************************************************
ok: [host_1]
ok: [host_2]
TASK [debug] **********************************************************************************
ok: [host_1] =>
hostname: gw.example.com
ok: [host_2] =>
hostname: gw.example.com
PLAY RECAP ************************************************************************************
host_1: ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
host_2: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
The playbook won't ovewrite variables defined in the inventory. For example
shell> cat hosts
host_1
host_2 hostname=gw2.example.com
gives
TASK [debug] **********************************************************************************
ok: [host_1] =>
hostname: gw.example.com
ok: [host_2] =>
hostname: gw2.example.com
I don't know if you can stop the prompts but you can se a default value directly in vars_prompts. In this way you do not need to type "gateway-name" every time.
vars_prompt:
- name: "hostname"
prompt: "Hostname"
private: no
default: "gateway-name"
Source: https://docs.ansible.com/ansible/latest/user_guide/playbooks_prompts.html

How can I print out the actual values of all the variables used by an Ansible playbook?

An answer on StackOverflow suggests using - debug: var=vars or - debug: var=hostvars to print out all the variables used by an Ansible playbook.
Using var=hostvars did not print out all of the variables. But I did get all of the variables printed out when I added the following lines to the top of the main.yml file of the role executed by my playbook:
- name: print all variables
debug:
var=vars
The problem is that the values of the variables printed out are not fully evaluated if they are dependent on the values of other variables. For example, here is a portion of what gets printed out:
"env": "dev",
"rpm_repo": "project-subproject-rpm-{{env}}",
"index_prefix": "project{{ ('') if (env=='prod') else ('_' + env) }}",
"our_server": "{{ ('0.0.0.0') if (env=='dev') else ('192.168.100.200:9997') }}",
How can I get Ansible to print out the variables fully evaluated like this?
"env": "dev",
"rpm_repo": "project-subproject-rpm-dev",
"index_prefix": "project_dev",
"our_server": "0.0.0.0",
EDIT:
After incorporating the tasks section in the answer into my playbook file and removing the roles section, my playbook file looks like the following (where install-vars.yml contains some variable definitions):
- hosts: all
become: true
vars_files:
- install-vars.yml
tasks:
- debug:
msg: |-
{% for k in _my_vars %}
{{ k }}: {{ lookup('vars', k) }}
{% endfor %}
vars:
_special_vars:
- ansible_dependent_role_names
- ansible_play_batch
- ansible_play_hosts
- ansible_play_hosts_all
- ansible_play_name
- ansible_play_role_names
- ansible_role_names
- environment
- hostvars
- play_hosts
- role_names
_hostvars: "{{ hostvars[inventory_hostname].keys() }}"
_my_vars: "{{ vars.keys()|
difference(_hostvars)|
difference(_special_vars)|
reject('match', '^_.*$')|
list|
sort }}"
When I try to run the playbook, I get this failure:
shell> ansible-playbook playbook.yml
SSH password:
SUDO password[defaults to SSH password]:
PLAY [all] *********************************************************************
TASK [setup] *******************************************************************
ok: [192.168.100.111]
TASK [debug] *******************************************************************
fatal: [192.168.100.111]: FAILED! => {"failed": true, "msg": "lookup plugin (vars) not found"}
to retry, use: --limit #/usr/local/project-directory/installer-1.0.0.0/playbook.retry
PLAY RECAP *********************************************************************
192.168.100.111 : ok=1 changed=0 unreachable=0 failed=1
The minimal playbook below
shell> cat pb.yml
- hosts: localhost
gather_facts: false
vars:
test_var1: A
test_var2: "{{ test_var1 }}"
tasks:
- debug:
var: vars
reproduces the problem you described. For example,
shell> ansible-playbook pb.yml | grep test_var
test_var1: A
test_var2: '{{ test_var1 }}'
Q: How can I print out the actual values of all the variables used by an Ansible playbook?
A: You can get the actual values of the variables when you evaluate them. For example,
shell> cat pb.yml
- hosts: localhost
gather_facts: false
vars:
test_var1: A
test_var2: "{{ test_var1 }}"
tasks:
- debug:
msg: |-
{% for k in _my_vars %}
{{ k }}: {{ lookup('vars', k) }}
{% endfor %}
vars:
_special_vars:
- ansible_dependent_role_names
- ansible_play_batch
- ansible_play_hosts
- ansible_play_hosts_all
- ansible_play_name
- ansible_play_role_names
- ansible_role_names
- environment
- hostvars
- play_hosts
- role_names
_hostvars: "{{ hostvars[inventory_hostname].keys() }}"
_my_vars: "{{ vars.keys()|
difference(_hostvars)|
difference(_special_vars)|
reject('match', '^_.*$')|
list|
sort }}"
gives the evaluated playbook's vars
msg: |-
test_var1: A
test_var2: A
Looking for an answer to the same question, I found the following solution from this link:
- name: Display all variables/facts known for a host
debug:
var: hostvars[inventory_hostname]
tags: debug_info

Ansible define new variable with value from other

I need some help with Ansible variables.
---
- name: create remote ansible account
hosts: all
gather_facts: false
remote_user: admin
vars:
ansible_ssh_pass: mypassword
ansible_become_pass: mypassword
publickey: "{{ inputvalue }}"
vars_files:
- publickey_file.yml
roles:
- create account
publickey_file.yml looks like this:
entry1: ssh-rsa AAAAB3....
entry2: ssh-rsa AAAAC3....
Specific task in role looks like this:
aml
- name: install SSH Key
authorized_key:
user: ansible
key: '{{ publickey }}'
become: yes
I would like to push a specific public key when specifying a variables with ansible-playbook.
I tried this, but it does not work:
ansible-playbook -i inventory.yml myplaybook.yml -e 'inputvalue=entry1'
This does not insert the value "{{ entry1 }}" but only the word 'entry1', so, inserted the key are not correct in module the authorized_key.
How can I insert, in publickey, the variable value "{{ entry1 }}" instead of 'entry1'?
You need the vars lookup in order to find a variable named as the string contained in the variable inputvalue:
publickey: "{{ lookup('vars', inputvalue) }}"

Build a variable in a playbook with the hostname and call it in a task

I have a two main variable with subvariables. The main variable VELABx and VELABy match the ansible_hostnames. Following an example of the variables mentioned:
VELABx
location: "text1.1"
initialism: "text1.2"
VELABy
location: "text2.1"
initialism: "text2.2"
Now I'd like to run a task which replaces a regexp with the location variable based on the current ansible_hostname. So, I tried this code, but it leads into an error.
- name: Replace location for VELABx
replace:
dest: "/path/to/file"
regexp: 'location'
replace: "{{ {{ansible_hostname}}.location }}"
remote_user: rssuser
become: no
when: ansible_hostname == "VELABx"
What am I doing wrong? How can I solve this? Can anyone bring up a solution?
Things are always easier when you manage to create a proper structure of data. For example, given the dictionaries in a file
shell> cat velab.yml
VELABx:
location: "text1.1"
initialism: "text1.2"
VELABy:
location: "text2.1"
initialism: "text2.2"
you can include the data from the file into a dictionary, e.g.
- hosts: VELABx,VELABy,VELABz
tasks:
- include_vars:
file: velab.yml
name: velab
run_once: true
- debug:
var: velab
run_once: true
gives
velab:
VELABx:
initialism: text1.2
location: text1.1
VELABy:
initialism: text2.2
location: text2.1
The data you provided in the question are not YAML dictionaries. The colon is missing behind the keys. Either fix it, if you can or parse the file. Anyway, create the dictionary whatever is the source.
Then, given the files
shell> ssh admin#10.1.0.61 cat /tmp/velab.txt
location
shell> ssh admin#10.1.0.62 cat /tmp/velab.txt
location
shell> ssh admin#10.1.0.63 cat /tmp/velab.txt
location
the task to replace the location is simple
- name: Replace location for VELAB*
replace:
dest: /tmp/velab.txt
regexp: location
replace: "{{ velab[inventory_hostname]['location'] }}"
when: velab[inventory_hostname] is defined
gives
shell> ansible-playbook playbook.yml -CD
PLAY [VELABx,VELABy,VELABz] ******************************************
...
TASK [Replace location for VELAB*] ***********************************
skipping: [VELABz]
--- before: /tmp/velab.txt
+++ after: /tmp/velab.txt
## -1 +1 ##
-location
+text1.1
changed: [VELABx]
--- before: /tmp/velab.txt
+++ after: /tmp/velab.txt
## -1 +1 ##
-location
+text2.1
changed: [VELABy]
The next option is to remove the condition and use the default value, instead of skipping the host, when the host is missing in the dictionary
- name: Replace location for VELAB*
replace:
dest: /tmp/velab.txt
regexp: location
replace: "{{ velab[inventory_hostname]['location']|
default(default_location) }}"
vars:
default_location: "text99.1"
you must use loopkup, {{}} inside other {{}} is incorrect
---
- hosts: localhost
gather_facts: false
vars:
ansible_hostname: VELABx
VELABx:
location: "text1.1"
initialism: "text1.2"
VELABy:
location: "text2.1"
initialism: "text2.2"
tasks:
- name: DEBUG
debug:
msg: "{{ lookup('vars', ansible_hostname ).location }}"
- name: Replace location for VELABx
replace:
dest: "/path/to/file"
regexp: 'location'
replace: "{{ lookup('vars', ansible_hostname ).location }}"
when: ansible_hostname == "VELABx"

Ansible Unable to assign variable the value to another variable

If the user does not pass dest_path parameter or if dest_path is EMPTY i.e contains only whitespaces then dest_path should be the same as source_file value.
Below is my playbook:
---
- name: "Play 1"
hosts: localhost
any_errors_fatal: false
gather_facts: false
tasks:
- set_fact:
dest_path: "{{ dest_path | default(source_file) }}"
- set_fact:
dest_path: "{{ source_file }}"
when: dest_path | length == 0
- debug:
msg: "DESTINATION PATH IS: {{ dest_path }} and the SOURCE PATH is: {{ source_file }}"
This is how you run this playbook:
ansible-playbook -i /web/playbooks/allmwhosts.hosts /web/playbooks/test.yml -e '{ source_file: /web/bea_apps/CURRENT }' -e dest_path=
In the above example when the user does not specify any value for dest_path I m expecting dest_path should be source_file i.e /web/bea_apps/CURRENT
However, as you can see in the output below that is not the case:
Output:
PLAY [Play 1] *******************
TASK [set_fact] **************************************************************************************
ok: [localhost]
TASK [set_fact] **************************************************************************************
ok: [localhost]
TASK [debug] *****************************************************************************************
ok: [localhost] => {
"msg": "DESTINATION PATH IS: and the SOURCE PATH is: /web/bea_apps/CURRENT"
}
PLAY RECAP *******************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0
Can you please suggest?
The extra variable that you pass as parameter is overriding the variable in set_fact variable dest_path. Below is the working code. In set_fact instead of dest_path I replaced with path.
---
- name: "Play 1"
hosts: localhost
any_errors_fatal: false
gather_facts: false
tasks:
- set_fact:
path: "{{ source_file }}"
when: (dest_path is not defined) or (dest_path | length == 0)
- set_fact:
path: "{{ dest_path }}"
when: (dest_path is defined) or (dest_path | length != 0)
- debug:
msg: "DESTINATION PATH IS: {{ path }} and the SOURCE PATH is: {{ source_file }}"