Reputation: 7838
In a folder containing files with different extensions (*.rules
and *.rules.yml
), I need to change the file extension based on certain condition:
*.rules
=> *.rules.yml
, or*.rules.yml
=> *.rules
In shell, I can do it as:
Case # 1
for file in ./*.rules; do mv "$file" "${file%.*}.rules.yml" ; done
# from *.rules to *.rules.yml
Case # 2
for file in ./*.rules.yml ; do mv "$file" "${file%.*.*}.rules" ; done
# from *.rules.yml to *.rules
Any idea in ansible to do the same thing?
Any help will be appreciated :)
Upvotes: 0
Views: 687
Reputation: 7838
Thanks for the help, Matthew L Daniel. It works quite well.
The final working solution would be enclosed as reference:
- name: Run in local to replace suffix in a folder
hosts: 127.0.0.1
connection: local
vars:
- tmpRulePath: "rules"
- version: "18.06" # change the version here to change the suffix from rules/rules.yml to rules.yml/rules
- validSuffix: "rules.yml"
- invalidSuffix: "rules"
tasks:
- name: Prepare the testing resources
shell: mkdir -p {{ tmpRulePath }}; cd {{ tmpRulePath }}; touch 1.rules 2.rules 3.rules.yml 4.rules.yml; cd -; ls {{ tmpRulePath }};
register: result
- debug:
msg: "{{ result.stdout_lines }}"
- name: Check whether it's old or not
shell: if [ {{ version }} \< '18.06' ]; then echo 'true'; else echo 'false'; fi
register: result
- debug:
msg: "Is {{ version }} less than 18.06 {{ result.stdout }}"
- name: Update validSuffix and invalidSuffix
set_fact:
validSuffix="rules"
invalidSuffix="rules.yml"
when: result.stdout == "true"
- debug:
msg: "validSuffix is {{ validSuffix }} while invalidSuffix {{ invalidSuffix }}"
- name: Replace the invalid suffix with valid
shell: |
cd {{ tmpRulePath }};
for i in *.{{ invalidSuffix }}; do
/bin/mv -v "$i" "`basename "$i" .{{ invalidSuffix }}`.{{ validSuffix }}"
done
- name: Check the latest files
shell: ls {{ tmpRulePath }}
register: result
- debug:
msg: "{{ result.stdout_lines }}"
- name: Clean up
shell: rm -rf {{ tmpRulePath }}
Upvotes: 0
Reputation: 33223
Assuming the difficulty you are having is with YAML quoting, you may experience better luck with the "pipe literal":
tasks:
- shell: |
for i in *.rules; do
/bin/mv -iv "$i" "`basename "$i" .rules`.rules.yml"
done
- shell: |
for i in *.rules.yml; do
/bin/mv -v "$i" "`basename "$i" .rules.yml`.rules"
done
One will also notice that I used the more traditional basename
rather than trying to do "crafty" variable expansion tricks, since with it should run with any posix shell.
Or if you are experiencing that your target system uses dash, or zsh, or ksh, or whatever, you can also be explicit in the shell you wish for ansible to use:
tasks:
- shell: echo "hello from bash"
args:
executable: /bin/bash
Upvotes: 2