Using regex_search to extract a string between a string and a whitespace - regex

I would like to extract the version number 1.0.1 from the following string in Ansible, I tried using regex_serach to extra the string between ide- and a whitespace, but that's what I end up getting ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start. I tried \s instead of \\s and it doesn't work. How should I fix the regex pattern? Any help would be appreciated!
ExecStart={ path=/home/bin/ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start }
- name: Check if ide is active
command: systemctl show ide.service --property=ExecStart
register: version_check
ignore_errors: yes
- name: Set fact
set_fact:
version: "{{ version_check.stdout | regex_search('ide-(.*)\\s'}}"
- name: Debug version
debug:{{ version }}"

Use regex_replace, e.g.
- set_fact:
version: "{{ _path.split('-').1 }}"
vars:
_regex: '^(.*)=(.*)=(.*);(.*)$'
_replace: '\3'
_path: "{{ version_check.stdout|regex_replace(_regex, _replace)|trim }}"
gives
version: 1.0.1
Parsing semi-structured text with Ansible is available, e.g.
- ansible.utils.cli_parse:
text: "{{ version_check.stdout }}"
parser:
name: ansible.netcommon.native
template_path: templates/property.yaml
set_fact: property
and the template
shell> cat templates/property.yaml
---
- example: 'ExecStart={ path=/home/bin/ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start }'
getval: '(?P<property>\S+)={\s*(?P<key1>\S+)=(?P<val1>\S+)\s*;\s*(?P<key2>\S+)=(?P<val2>\S+)\s*(?P<state>\S+)\s*}'
result:
"{{ property }}":
"{{ key1 }}": "{{ val1 }}"
"{{ key2 }}": "{{ val2 }}"
state: "{{ state }}"
give
property:
ExecStart:
argv[]: /home/bin/ide-1.0.1
path: /home/bin/ide-1.0.1
state: start
Then parse the version, e.g.
- set_fact:
version: "{{ (property.ExecStart.path|basename).split('-').1 }}"
gives
version: 1.0.1

Related

There's a way to template a variable in ansible

applications:
appA:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appA'
appB:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appB'
- ansible.builtin.set_fact:
clusters: "{{ clusters + [ item ] }}"
when: applications.{{ item }}.someDB.enable
loop:
- appA
- appB
- ansible.builtin.shell: |
pg_createcluster \
-d {{ aplications.item.someDB.datadir }}
when: item == 'appA'
loop: "{{ clusters }}"
Is there a simple way to make ansible do substitutions inside a var ? Like some precedence operand.
In the loop: item == appA
so, {{ aplications.item.someDB.datadir }} is like this {{ aplications.appA.someDB.datadir }}, and autmatocally is its content is: '/var/lib/postgresql/11/appA' and so on.
Probably I'm using the wrong approach, but seems reasonable to me do that.
Thank's for anyu help.
The applications variable can be flattened, so it will be easier to set the conditions for the task
applications:
- name: appA
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appA'
- name: appB
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appB'
- name: Create PG cluster
ansible.builtin.shell: >
pg_createcluster
-d {{ item.someDB.datadir }}
when:
- item.name == 'appA'
- item.someDB.enable
loop: "{{ applications }}"
Some comments:
Adding a unique name to the task will make it easier to debug your playbooks, specially when you have a long playbook or role
using > in shell will take care to collapse the instructions as a single line, so you won't need the slash
Usually to create a postgress database, you would prefer to use the postgresql_db Ansible module; the -d <directory> is preferred to be set in the configuration file, so you wouldn't need it as an argument.
Create the list of enabled clusters
clusters: "{{ applications|dict2items|
json_query('[?value.someDB.enable].key') }}"
gives
clusters:
- appA
- appB
Then, the task below creates the run-strings you want
- debug:
msg: "pg_createcluster -d {{ applications[item].someDB.datadir }}"
loop: "{{ clusters }}"
gives (abridged)
msg: pg_createcluster -d /var/lib/postgresql/11/appA
msg: pg_createcluster -d /var/lib/postgresql/11/appB
Example of a complete playbook for testing
- hosts: localhost
vars:
applications:
appA:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appA'
appB:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appB'
clusters: "{{ applications|dict2items|
json_query('[?value.someDB.enable].key') }}"
tasks:
- debug:
var: clusters
- debug:
msg: "pg_createcluster -d {{ applications[item].someDB.datadir }}"
loop: "{{ clusters }}"
Notes:
You can get both the key and the value by substitution
- debug:
msg: "{{ _key }}: {{ _val }}"
loop:
- appA
- appB
when: applications[item].someDB.enable
vars:
_key: "applications.{{ item }}.someDB.datadir"
_val: "{{ applications[item].someDB.datadir }}"
gives (abridged)
msg: 'applications.appA.someDB.datadir: /var/lib/postgresql/11/appA'
msg: 'applications.appB.someDB.datadir: /var/lib/postgresql/11/appB'
Create a dictionary to simplify the searching
app_datadir: "{{ dict(applications|dict2items|
json_query('[].[key, value.someDB.datadir]')) }}"
gives
app_datadir:
appA: /var/lib/postgresql/11/appA
appB: /var/lib/postgresql/11/appB
Use this dictionary "to make Ansible do substitutions". For example,
- debug:
msg: "applications.{{ item }}.someDB.datadir: {{ app_datadir[item] }}"
loop:
- appA
- appB
gives (abridged)
msg: 'applications.appA.someDB.datadir: /var/lib/postgresql/11/appA'
msg: 'applications.appB.someDB.datadir: /var/lib/postgresql/11/appB'
Example of a complete playbook for testing
- hosts: localhost
vars:
applications:
appA:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appA'
appB:
someDB:
enable: true
datadir: '/var/lib/postgresql/11/appB'
app_datadir: "{{ dict(applications|dict2items|
json_query('[].[key, value.someDB.datadir]')) }}"
tasks:
- debug:
var: app_datadir
- debug:
msg: "applications.{{ item }}.someDB.datadir: {{ app_datadir[item] }}"
loop:
- appA
- appB
You can also create the dictionary app_enable
app_enable: "{{ dict(applications|dict2items|
json_query('[].[key, value.someDB.enable]')) }}"
gives
app_enable:
appA: true
appB: true
and use it in the condition. For example,
- debug:
msg: "applications.{{ item }}.someDB.datadir: {{ app_datadir[item] }}"
loop:
- appA
- appB
when: app_enable[item]

ansible list files in a directory

Can somone explain to me why this doesn't work? I want to get a list of files within a directory and use it as an input for the loop.
---
tasks:
- set_fact:
capabilities: []
- name: find CE_Base capabilities
find:
paths: /opt/netsec/ansible/orchestration/capabilities/CE_BASE
patterns: '*.yml'
register: CE_BASE_capabilities
- name: debug_files
debug:
msg: "{{ item.path }}"
with_items: "{{ CE_BASE_capabilities.files }}"
- set_fact:
thispath: "{{ item.path }}"
capabilities: "{{ capabilities + [ thispath ] }}"
with_items: "{{ CE_BASE_capabilities.files }}"
- name: Include CE_BASE
include_tasks: /opt/netsec/ansible/orchestration/process_capabilities_CE_BASE.yml
loop: "{{ capabilities }}"
Edit:
This code is attempting to create a list called capabilties, which contatins a list of files in a particular directory.
When i ran this code without trying to get the files automatically, it looked like this.
- hosts: localhost
vars:
CE_BASE_capabilities:
- '/opt/netsec/ansible/orchestration/capabilities/CE_BASE/CE_BASE_1.yml'
- '/opt/netsec/ansible/orchestration/capabilities/CE_BASE/CE_BASE_2.yml'
- name: Include CE_BASE
include_tasks: /opt/netsec/ansible/orchestration/process_capabilities_CE_BASE.yml
loop: "{{ CE_BASE_capabilities }}"
Don't define thispath as a fact but as a local vars in the set_fact task. Beside that, you don't need to init capabilities if you use the default filter.
- vars:
thispath: "{{ item.path }}"
set_fact:
capabilities: "{{ capabilities | default([]) + [ thispath ] }}"
with_items: "{{ CE_BASE_capabilities.files }}"
Moreover, you don't even need to loop. You can extract the info directly from the existing result:
- set_fact:
capabilities: "{{ CE_BASE_capabilities.files | map(attribute='path') | list }}"

set_facts with dict as argument of a loop

I'd like to obtain the list of bridged interfaces grouped by master like this:
brv100:
- vnet0
- eth0
brv101:
- vnet1
- eth1
I want to use native json output from the shell commands.
The only thing I managed to do is to get a predefined number of interfaces like this:
- hosts: localhost
gather_facts: no
tasks:
- shell:
cmd: ip -details -pretty -json link show type bridge
register: list_bridges
- set_fact:
bridges: "{{ list_bridges.stdout }}"
- debug:
msg: "{{ bridges | map(attribute='ifname') | list}}"
- name: get json
shell:
cmd: ip -details -pretty -json link show master "{{ifname}}"
with_items: "{{bridges | map(attribute='ifname') | list}}"
loop_control:
loop_var: ifname
register: list_interfaces
- set_fact:
interfaces: "{{ list_interfaces.results | map(attribute='stdout') | list }}"
- set_fact:
toto: "{{interfaces.1}} + {{interfaces.2}}"
- debug:
msg: "{{toto | map(attribute='ifname')|list}}"
Now if I want to do the same with a loop :
- set_fact:
toto: " {{item|default([])}}+ {{ item |default([])}}.{{idx}} "
loop: "{{interfaces}}"
loop_control:
label: "{{item}}"
index_var: idx
- debug: var=toto
The result doesn't seem to be a list of list, but a list of strings and I can't extract the 'ifname' values with a simple debug
- debug:
msg: "{{toto | map(attribute='ifname')|list}}"
What am I supposed to do so as to get benefit of the json native output and get simple list of bridged interfaces (like brctl show was used to do)?
The lists of bridged interfaces grouped by the master are available in ansible_facts. The task below sets the dictionary of the bridges and bridged interfaces
- set_fact:
bridges: "{{ dict(ansible_facts|
dict2items|
json_query('[?value.type == `bridge`].[key, value.interfaces]')) }}"
Q: "Manage to get the same result manipulating JSON data."
A: The output of the ip -json ... command is JSON formated string which must be converted to JSON dictionary in Ansible by the from_yaml filter (JSON is a subset of YAML). For example, the tasks below give the same result
vars:
my_debug: false
tasks:
- name: Get bridges names
command: "ip -details -json link show type bridge"
register: list_bridges
- set_fact:
bridges: "{{ list_bridges.stdout|
from_yaml|
map(attribute='ifname')|
list }}"
- debug:
var: bridges
when: my_debug
- name: Get bridges interfaces
command: "ip -details -json link show master {{ item }}"
loop: "{{ bridges }}"
register: list_interfaces
- set_fact:
bridges_interfaces: "{{ list_interfaces.results|
json_query('[].stdout')|
map('from_yaml')|
list }}"
- debug:
msg: "{{ msg.split('\n') }}"
vars:
msg: "{{ item|to_nice_yaml }}"
loop: "{{ bridges_interfaces }}"
loop_control:
label: "{{ item|json_query('[].ifname') }}"
when: my_debug
- name: Set dictionary of bridges
set_fact:
bridges_dict: "{{ bridges_dict|
default({})|
combine({item.0: item.1|json_query('[].ifname')}) }}"
loop: "{{ bridges|zip(bridges_interfaces)|list }}"
loop_control:
label: "{{ item.1|json_query('[].ifname') }}"
- debug:
var: bridges_dict
Template to write the bridges to a file
{% for k,v in bridges_dict.items() %}
{{ k }}:
{% if v is iterable %}
{% for i in v %}
- {{ i }}
{% endfor %}
{% endif %}
{% endfor %}
- name: Write the bridges to file
template:
src: bridges.txt.j2
dest: bridges.txt
The file bridges.txt will be created in the remote host running the task.

ansible regex_search with variable

How to find a match using regex in ansible playbook where variable appears in the regex_search argument?
The following playbook doesn't find the match... when run using: ansible-playbook playbook.yml
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
pattern: "{{ 'foobar' | regex_search('foo') }}"
- set_fact:
m: "{{ 'beefoo' | regex_search('bee{{ pattern }}') }}"
- debug:
msg: "hi {{ m }}"
Depends on the ansible's version you're using. As far as I know, you can use that expression in a version greater than 2.4.0. For lower versions you can use regex_search('^' + pattern | string).
So your code will be something like this:
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
pattern: "{{ 'foobar' | regex_search('foo') }}"
- set_fact:
m: "{{ 'beefoo' | regex_search('bee' + pattern | string) }}"
- debug:
msg: 'hi ' + m | string
Wanted to share my complex case with positive look-ahead, positive look-behind and variable in regex_search for those who may need it.
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
pattern: "{{ 'foobar' | regex_search('foo') }}"
- set_fact:
m: "{{ 'beefoo' | regex_search('(?<=prefix-' + pattern | string + '-)' + '([0-9.]+)' + '(?=suffix)') }}"
- debug:
msg: "hi {{ m }}"

ansible ec2_instance_facts filter by "tag:Name" does not filter by instance Name

I want to run ec2_instance_facts to find an instance by name. However, I must be doing something wrong because I cannot get the filter to actually work. The following returns everything in my set AWS_REGION:
- ec2_instance_facts:
filters:
"tag:Name": "{{myname}}"
register: ec2_metadata
- debug: msg="{{ ec2_metadata.instances }}"
The answer is to use the ec2_remote_facts module, not the ec2_instance_facts module.
- ec2_remote_facts:
filters:
"tag:Name": "{{myname}}"
register: ec2_metadata
- debug: msg="{{ ec2_metadata.instances }}"
Based on the documentation ec2_remote_facts is marked as DEPRECATED from ansible version 2.8 in favor of using ec2_instance_facts.
This is working good for me:
- name: Get instances list
ec2_instance_facts:
region: "{{ region }}"
filters:
"tag:Name": "{{ myname }}"
register: ec2_list
- debug: msg="{{ ec2_metadata.instances }}"
Maybe the filte is not being applied? Can you go through the results in the object?