I need to extract some text from a variable in ansible.
- name: Find modules
shell: find "{{ role_path }}/files/{{ flavor_modules }}/modules.d/" -name "*.yml"
register: modules_list
- debug:
msg: "aca {{ item }}"
with_items: "{{ modules_list }}"
So modules list returns something like this: /etc/ansible/roles/filebeat/files/something/modules.d/haproxy.yml
I need to register or create a new variable that looks like this: haproxy.yml
I been trying with some regex expressions with no luck.
Related
Team,
I have this task below where I want to create a condition and based on that I want to run other tasks. so as first step, creating condition task itself is failing because am not able to figure out the syntax.. ran several iterations and also check online here https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html
Any hint, am new.
- name: Identify device naming convention[nvme*] using REGEX
debug:
msg: "Found Block Device {{ item.0.device }}"
loop: "{{ local_volume_mount_disks|subelements('partitions') }}"
#when: "{{ item.0.device }}" is regex("nvme2\w+"). #<<<FAILED
when: "{{ item.0.device }}" is search("nvme")
register: nv_device_type
tags: tag_to_create_with_values, tag_to_delete
- name: Output device from REGEX results
debug:
var: nv_device_type
ignore_errors: no
output
ERROR! Syntax Error while loading YAML.
expected <block end>, but found '<scalar>'
The error appears to be in '/ansible-managed/jenkins-slave/slave0/workspace/nvdc/run_ansible_playbook#2/k8s/baremetal/roles/local_volume_mount/tasks/main.yml': line 45, column 33, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
#when: "{{ item.0.device }}" is regex("nvme2\w+")
when: "{{ item.0.device }}" is search("nvme")
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
my values are below
local_volume_mount_disks:
- device: /dev/nvme2n1
partitions:
- number: 1
Just figured out after several iterations..
- name: Identify device naming convention[nvme*] using REGEX
debug:
msg: "Found Block Device {{ item.0.device }}"
loop: "{{ local_volume_mount_disks|subelements('partitions') }}"
when: '"{{item.0.device }}" is search("nvme")'
register: nv_device_type
output
ok: [node1] => (item=[{'device': '/dev/nvmedn1', 'partitions': [{'number': 1, 'start': '0%', 'end': '100%'}]}, {'number': 1, 'start': '0%', 'end': '100%'}]) => {
"msg": "Found Block Device /dev/nvmedn1"
}
How can I replace only the last character of .jar. Below is the sample value for LIST_jar[0].nameOfJar and the sample output expected
my-firsrt.jar-1.jar >> my-firsrt.jar-1
my-firsrt-2.0.jar-1.jar >> my-firsrt-2.0.jar-1
my-firsrt-1.0-jar-1.jar >> my-firsrt-1.0-jar-1
my-firsrt-jar-1.0-jar-1.jar >> my-firsrt-jar-1.0-jar-1
my-firsrt-jar-1.0.jar.jar >> my-firsrt-jar-1.0.jar
my-firsrt-jar-1.0-jar.jar >> my-firsrt-jar-1.0.jar
This is my sample code but it is not working accordingly as it is replacing all the jar value.
- name: Replace string
copy:
content: "{ name: jack }"
dest: "{{ directory }}/JAR_LIST/{{ LIST_jar[0].nameOfJar | regex_replace('.jar') }}.log"
There are more options. The most simple is splitext. More versatile is split to manipulate multiple extensions. The filter regex_replace is more complex but universal.
splitext
Use splitext. For example
- debug:
msg: "dest: {{ (item|splitext).0 }}.log"
loop: "{{ list_jar }}"
gives (given the list of filenames is in the variable list_jar)
msg: 'dest: my-firsrt.jar-1.log'
msg: 'dest: my-firsrt-2.0.jar-1.log'
msg: 'dest: my-firsrt-1.0-jar-1.log'
msg: 'dest: my-firsrt-jar-1.0-jar-1.log'
msg: 'dest: my-firsrt-jar-1.0.jar.log'
msg: 'dest: my-firsrt-jar-1.0-jar.log'
split
The next option is split. The task below gives the same results
- debug:
msg: "dest: {{ item.split('.')[:-1]|join() }}.log"
loop: "{{ list_jar }}"
regex_replace
If you want to use regex_replace the tasks below give the same results. Either remove the extension and concatenate .log
- debug:
msg: "dest: {{ item|regex_replace('^(.*)\\.jar$', '\\1') }}.log"
loop: "{{ list_jar }}"
, or replace the extension in the filter
- debug:
msg: "dest: {{ item|regex_replace('^(.*)\\.jar$', '\\1.log') }}"
loop: "{{ list_jar }}"
To make the code more readable it's a good idea to put the regular expressions into the variables and use single-quoted style. For example
- debug:
msg: "dest: {{ item|regex_replace(my_regex, my_replace) }}"
loop: "{{ list_jar }}"
vars:
my_regex: '^(.*)\.jar$'
my_replace: '\1.log'
Below is my sample code but it is not working accordingly as it is replacing all the jar value.
Correct, because the . in regex means "any character." If you just want to replace the literal string .jar then don't use regex replace, just use replace() which will use the literal characters you provide to it.
Otherwise, if you wish to continue to use regex_replace, then quote that character and also specify that the pattern should only match the end of the string
- debug:
msg: "{{ nameOfJar | regex_replace('[.]jar$', '') }}.log"
vars:
nameOfJar: my-firsrt-jar-1.0-jar-1.jar
We're going to assume the last two of your samples were just copy paste in this question, and that you prefer the .log outside the mustaches instead of just including '.log' in the replacement position of regex_replace
I'm currently writing a small Ansible playbook whose job is to put in an additional domain in the search list in /etc/resolv.conf.
The second domain to add to the search list must contain part of the hostname of the target hosts. I'm getting the hostname of each of the target hosts during playbook execution using the magic variable {{ inventory_hostname }}.
I then need to extract characters 4 - 6 from the {{ inventory_hostname }} (say 'xyz') such that the second domain to add to the search list is xyz.foo.bar. In bash, this would be obtained with something like:
SERVER=$('hostname':3:3)
env=${SERVER:3:3}
... and the variable 'env' would be equal to 'xyz'.
The playbook works as long as 'xyz' is manually defined.
I am aware that Ansible has regular expression filters which can help with something like this, however I could not figure out a regular expression which does what I need.
For completeness sake, I have tried something like this in ansible:
{{ inventory_hostname|3:3 }}
Any help would be greatly appreciated.
It's almost the same, you can use "{{ inventory_hostname[3:6] }}" to select characters 3 to 6.
For example this task
- debug:
msg: "{{ inventory_hostname[3:6] }}"
Will output
ok: [localhost] => {
"msg": "alh"
}
tasks:
- name: Find mac-address
ios_command:
provider: "{{ cli }}"
commands:
- show mac add | i d83b
register: sh_mac_res
sh_mac_res is variable contain string like this:
"22 18a9.0530.d83b DYNAMIC Fa0/17"
How can I put 18a9.0530.d83b into a variable?
set_facts:
mac_address: {{ sh_mac_res.stdout }}.........????
What should I use? regex_search or something else?
Use Python split() function and select the second element of the resulting list:
- set_fact:
mac_address: "{{ sh_mac_res.stdout.split()[1] }}"
In my playbook, I'd like to loop over two dictionaries (or one dictionary and one list). One is a list (or dictionary) of Domains, the other one is a dictionary that includes the aws-regions with the corresponding server-IPs to use for the DNS-Entries for latency based routing. I want to set for each domain one DNS-record for each aws-region.
- name: set DNS records for Domains
route53:
zone: "{{ item[0].key }}"
record: "{{ item[0].key }}"
value: "{{ item[1].value.server_ip }}"
region: "{{ item[1].key }}"
identifier: "{{ item[1].key }}"
with_nested:
- "{{ domain_dict }}"
- "{{ aws_dict }}"
With two lists, the example works fine. How do I get it to work using at least one dictionary?
domain_dict: (could be a list as well)
domain_dict:
mytest1.example:
mytest2.example:
mytest3.example:
aws_dict:
aws_dict:
us-east-1:
# some other region-related stuff like ami-id,...
server_ip: 1.2.3.4
us-west-1:
# some other region-related stuff
server_ip: 1.2.3.5
us-west-2:
# some other region-related stuff
server_ip: 1.2.3.6
#all other aws-regions
A custom lookup_plugin is your best bet. Otherwise it'll be an ugly sequence of set_fact.
PS:
While you ordinarily shouldn’t have to, should you wish to write your own ways to loop over arbitrary datastructures, you can read Developing Plugins for some starter information. Each of the above features are implemented as plugins in ansible, so there are many implementations to reference