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
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"
}
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.
Note: i m seeking solution for Ansible. Here is the issue description:
I have a file filedet.yml as below, however realtime this yaml may contain many more IP and file details.
---
10.9.9.111:
/tmp/test.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
/tmp/best.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
10.8.8.44:
/tmp/conf/extra/httpd-ssl.conf:
hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2
/tmp/conf/httpd.conf:
hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2
I wish to extract a particular IP and the file details so that it can be removed from the yaml using state: absent attribute . Thus, the desired regex should return the below:
10.9.9.111:
/tmp/test.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954e
/tmp/best.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
I decided to have the start pattern as '10.9.9.111' and search until there are no spaces or newlines which means until it gets to the next IP.
I prepared the below regex and it shows correct, desired FULL Text match on http://regex101.com. See snapshot.
Regex query below:
[^#](^10.9.9.111:)(.|\n)*^(?!( |\n))
The same regex works fine with grep -Pzo and returns the desired string. However, the regex fails to work with ansible's lineinfile module as it does not yeild any results.
i want this regex or any other solution to work with Ansible so i can remove the given IP and it's file details from the yaml
Ansible:
- name: "Remove entry from file."
lineinfile:
path: "/app/filedet.yaml"
regexp: "[^#](^10.9.9.111:)(.|\n)*^(?!( |\n))"
state: absent
Can you please suggest what is the issue here ?
Q: "I wish to extract an IP and the file details."
A: Use include_vars. For example
- include_vars:
file: filedet.yml
name: my_dict
- debug:
msg: "{{ my_dict['10.9.9.111'] }}"
give
"msg": {
"/tmp/best.jar": {
"hash": "e6df90d38fa86f0e289f73d79cd2cfd2a29954eb"
},
"/tmp/test.jar": {
"hash": "e6df90d38fa86f0e289f73d79cd2cfd2a29954eb"
}
}
Q: "Remove an entry from the file."
A: Use template. For example
$ cat filedet.yml.j2
{% for item in my_dict_keys %}
{{ item }}:
{{ my_dict[item]|to_nice_yaml|indent(2) }}
{% endfor %}
The task below
- set_fact:
my_dict_keys:
- "10.8.8.44"
- template:
src: filedet.yml.j2
dest: filedet.yml
gives
$ cat filedet.yml
10.8.8.44:
/tmp/conf/extra/httpd-ssl.conf:
hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2
/tmp/conf/httpd.conf:
hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2
Notes:
It's a bad idea to use lineinfile for this purpose
Data in the question is not valid YAML. The key is repeating
10.9.9.111:
/tmp/test.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
/tmp/test.jar:
hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
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] }}"
I have a string with IP addr: 192.168.10.2
I want to extract first three octets of the IP in Ansible and I tried to use this regex.
{{comp_ip | regex_replace("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"), "//1"}}
This does not yield any result. Can someone correct me where I went wrong?
If already have dot-separated IP-address, there is a simple way:
{{ comp_ip.split('.')[0:3] | join('.') }}
You are doing it right, you just have to use parenthesis in Regex to make a group. It is better to match the whole ip and end your regex with $, and also change //1 to \\1 in your code.
Change regex from:
^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}
To this regex:
^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\.[0-9]{1,3}$
This is the full code:
{{comp_ip | regex_replace('^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\.[0-9]{1,3}$', '\\1')}}
In case you want to calculate your network address you can use Ansible ipaddr filter which provides exactly this functionality:
http://docs.ansible.com/ansible/latest/playbooks_filters_ipaddr.html
---
- hosts: localhost
vars:
my_ip: "{{ ansible_default_ipv4.network }}/{{ ansible_default_ipv4.netmask }}"
tasks:
- debug: msg="network {{ my_ip | ipaddr('network') }}"
- debug: msg="netmask {{ my_ip | ipaddr('netmask') }}"