Ansible variable list span - variables

When adding a variable list in Ansible how would one achieve a span of similar values? For instance "000-100" - in an Ansible hosts file this can be done by listing like so, "hostname-[a:v].com". Would this process be the similar in a variable list?
My use case is to provision many VM's within oVirt in a single go without having to make a line by line list.
---
- name: Create VM based on template
hosts: ovirt-engine
become: yes
become_method: sudo
vars:
- temp: '{{temp_fedora25}}'
- iname:
- db-aa
- db-ab
- db-ac
tasks:
- name: Giving Birth to lil Baby VM's
ovirt:
user: '{{ovirt_usr}}'
password: '{{ovirt_pass}}'
url: '{{engine_url}}'
instance_name: "{{item}}"
instance_nic: ovirtmgmt
resource_type: template
image: '{{temp}}'
zone: superblade-a
disk_alloc: preallocated
with_items: "{{iname}}"

You can use sequence lookup:
- name: numeric
debug:
msg: "{{ item }}"
with_sequence: start=1 count=10 format=server-%0d
- name: characters from small 'a'
debug:
msg: "{{ item }}"
with_sequence: start=0x61 count=10 format=server-%c
- name: save for future use
set_fact:
my_seq: "{{ lookup('sequence','start={} count={} format={}{}'.format(beg,cnt,pref,fmt),wantlist=True) }}"
vars:
beg: 1
cnt: 10
pref: host-
fmt: '%0d'
You can skip set_fact and define my_seq in vars section, but if you use my_seq much, list generation will be done internally every time. With set_fact list is generated once.

With respect to the correct answer from Konstantin, I'm adding the full solution as per my case....
My goal is to be able to reuse the sequenced values as registered variables in order to pass the instance name to host name. This works so far but Im sure it can be streamlined by nesting variables perhaps?
---
- name: Create VM based on template
hosts: ovirt-engine
become: yes
become_method: sudo
vars:
- temp: '{{temp_fedora25}}'
- host_pre: db
- host_seq: a%c
- host_cnt: 3
- host_srt: 0x61
tasks:
- name: Giving Birth to lil Baby VM's
ovirt:
user: '{{ovirt_usr}}'
password: '{{ovirt_pass}}'
url: '{{engine_url}}'
instance_name: "{{item}}"
instance_nic: ovirtmgmt
resource_type: template
image: '{{temp}}'
zone: superblade-a
disk_alloc: preallocated
with_sequence: start="{{host_srt}}" count="{{host_cnt}}" format="{{host_pre}}-{{host_seq}}"

Related

Ansible script with | differences of empty map fails [duplicate]

I'm customizing linux users creation inside my role. I need to let users of my role customize home_directory, group_name, name, password.
I was wondering if there's a more flexible way to cope with default values.
I know that the code below is possible:
- name: Create default
user:
name: "default_name"
when: my_variable is not defined
- name: Create custom
user:
name: "{{my_variable}}"
when: my_variable is defined
But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities.
Is there something like the code above?
user:
name: "default_name", "{{my_variable}}"
The code should set name="default_name" when my_variable isn't defined.
I could set all variables on defaults/main.yml and create the user like that:
- name: Create user
user:
name: "{{my_variable}}"
But those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.
You can use Jinja's default:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
Not totally related, but you can also check for both undefined AND empty (for e.g my_variable:) variable. (NOTE: only works with ansible version > 1.9, see: link)
- name: Create user
user:
name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
if my_variable is defined else 'default_value' }}"
If anybody is looking for an option which handles nested variables, there are several such options in this github issue.
In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"
or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.
In case you using lookup to set default read from environment you have also set the second parameter of default to true:
- set_facts:
ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"
You can also concatenate multiple default definitions:
- set_facts:
ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"
If you are assigning default value for boolean fact then ensure that no quotes is used inside default().
- name: create bool default
set_fact:
name: "{{ my_bool | default(true) }}"
For other variables used the same method given in verified answer.
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:
all_items:
- first
- second
- third
- fourth
Then your task can look like this:
- name: List items or default list
debug:
var: item
with_items: "{{ varlist | default(all_items) }}"
Pass in varlist as a JSON array:
ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'
Prior to that, you might also want a task that checks that each item in varlist is also in all_items:
- name: Ensure passed variables are in all_items
fail:
msg: "{{ item }} not in all_items list"
when: item not in all_items
with_items: "{{ varlist | default(all_items) }}"
The question is quite old, but what about:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"
It looks less cumbersome to me...
#Roman Kruglov mentioned json_query. It's perfect for nested queries.
An example of json_query sample playbook for existing and non-existing value:
- hosts: localhost
gather_facts: False
vars:
level1:
level2:
level3:
level4: "LEVEL4"
tasks:
- name: Print on existing level4
debug:
var: level1 | json_query('level2.level3.level4') # prints 'LEVEL4'
when: level1 | json_query('level2.level3.level4')
- name: Skip on inexistent level5
debug:
var: level1 | json_query('level2.level3.level4.level5') # skipped
when: level1 | json_query('level2.level3.level4.level5')

Can variables be use as ansible filter parameters

I am creating a list of URLs (just strings really).
I want to select the one that contains the string in a ansible variable 'blog'.
Can't seem to code the select parameter correctly.
Is this possible?
- name: get blog_urls
shell:
cmd: wp site list --field=url
chdir: "{{ blog_docroot }}"
register: blog_urls
- name: show blog value
debug:
msg: "{{ blog }}"
- name: select the correct url
set_fact:
url: "{{ blog_urls.stdout_lines | select('contains', blog ) }}"
blog_url conatins:
"http://jackson2.sjfc.edu/",
"https://jackson2.sjfc.edu/oit/",
"https://jackson2.sjfc.edu/aaforms/",
"https://jackson2.sjfc.edu/admissions/",
"https://jackson2.sjfc.edu/arts-sciences/",
"https://jackson2.sjfc.edu/pharmacy/",
"https://jackson2.sjfc.edu/grants/",
"https://jackson2.sjfc.edu/alumni/",
"https://jackson2.sjfc.edu/wson/",
"https://jackson2.sjfc.edu/education/",
"https://jackson2.sjfc.edu/images/",
"https://jackson2.sjfc.edu/oit-test/",
"https://jackson2.sjfc.edu/provost/",
"https://jackson2.sjfc.edu/registrar/",
"https://jackson2.sjfc.edu/faculty-committees/",
"https://jackson2.sjfc.edu/faculty-files/",
"https://jackson2.sjfc.edu/avdownload/",
"https://jackson2.sjfc.edu/mac/",
"https://jackson2.sjfc.edu/giddnfellowship/",
"https://jackson2.sjfc.edu/dnp-mentors/"
blog would contain 'aaforms' or 'oit-test' or 'provost'...
If I hard code the desired value of blog (see line below) it works:
- name: select the correct url
set_fact:
url: "{{ blog_urls.stdout_lines | select('contains', 'aaforms' ) }}"
But of course I want to pass the second parameter of the 'select' filter as a ansible variable.
Your example in question is an almost working one. The select filter will return an a list based on the match criteria.
For example, let's say blog variable is aaforms:
vars:
blog: aaforms
tasks:
- set_fact:
my_blogs: "{{ blog_urls.stdout_lines | select('contains', blog) | list }}"
- debug:
var: my_blogs
This gives the URLs matched by the blog variable (in this case one).
"my_blogs": [
"https://jackson2.sjfc.edu/aaforms/"
]

Use dotted YAML variables file in Ansible

I'm trying to achieve the following using Ansible:
Define a YAML file with some variables in the dotted format inside it (variables.yml)
database.hosts[0]: "db0"
database.hosts[1]: "db1"
database.hosts[2]: "db2"
foo.bar: 1
foo.baz: 2
Load the variables in variables.yml by using the include_vars module in my playbook (playbook.yml) and print them in a tree structure
- hosts: all
gather_facts: not
tasks:
- name: "Loading vars"
run_once: true
include_vars:
file: 'variables.yml'
- name: "Testing"
debug:
msg: "{{ foo }}"
- name: "Testing"
debug:
msg: "{{ database }}"
Running this results in the following error:
fatal: [host0]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'foo' is undefined\n\nThe error appears to be in '.../playbook.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: \"Testing\"\n ^ here\n"}
Which makes it clear that each property in the YAML file has been loaded as a separate property and not as properties within two trees rooted in database and foo.
Of course, the playbook works as expected if I specify the properties as follows:
database:
hosts:
- "db0"
- "db1"
- "db2"
foo:
bar: 1
baz: 2
However, I need the YAML variables file to be in the dotted format instead of in the classic indented format. Is there any way to achieve this? E.g.: a module different from include_vars or some configuration that I can add to the ansible.cfg file? I have already tried to use hash_behaviour=merge, but that didn't help.
Q: "I need the YAML variables file to be in the dotted format instead of in the classic indented format. Is there any way to achieve this?"
A: No. It's' not possible. See Creating valid variable names.

Unable to set default value for set_fact in Ansible

Lets consider the user passes a Number parameter to my ansible-playbook as
ansible-playbook /app/test.yml
-e "Number=22235_ReDep_292001105550"
I want set_fact "Number_New" to be the string before the first underscore "_" i.e 22235 and "Status" to be everything after the first underscore "_" i.e
Expectation:
Number_New should be "22235"
Status should be "ReDep_292001105550"
Second scenario; the user may pass -e "Number=22235". This this case i want the set_fact "Number_New" should be same as the "Number=22235" passed while the Status should be "%" modulus symbol.
Expectation:
Number_New should be "22235"
Status should be "%"
Below is my playbook attempt which works fine when parameter passed is "Number=22235_ReDep_292001105550" but fails when -e "Number=22235"
tasks:
- name: Populate number and status from user input
set_fact:
Number_New: "{{ Number.split('_')[0] | default(Number) }}"
Status: "{{ Number.split('_')[1] }}_{{ Number.split('_')[2] | default('%') }}"
Error when it fails:
fatal: [localhost]: FAILED! => {
"msg": "The task includes an option with an undefined variable. The error was: list object has no element 1\n\nThe error appears to be in '/app/test.yml': line 32, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Populate number and status from user input\n ^ here\n"
}
The task below does the job
- set_fact:
Number_New: "{{ nsplit.0 }}"
Status: "{{ nsplit.1|default('%') }}"
vars:
nsplit: "{{ Number.split('_', 1) }}"

Loop over variable and concatenate with string

Suppose I have an array in ansible:
vars:
loopme: ['somesing', 'someothersing']
concatenateme: 'constant'
How do i iterate over the list and concat value from list with the variable concatenateme?
So I get somesingconstant and someothersingconstant and put the result into a field in the task? Perhaps with jinja?
You can use map to apply regex_replace filter to every element of your list and replace "end of string" ($) with your constant:
- hosts: localhost
gather_facts: no
vars:
loopme: ['somesing', 'someothersing']
concatenateme: 'constant'
tasks:
- debug:
msg: "{{ loopme | map('regex_replace','$',concatenateme) | list }}"