This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
ansible:ansible_tips [2025/02/25 09:14] manu [Copy / backup file] |
ansible:ansible_tips [2025/02/25 20:18] (current) manu |
||
---|---|---|---|
Line 1: | Line 1: | ||
====== Ansible tips and tricks ====== | ====== Ansible tips and tricks ====== | ||
- | ===== Replace inplace ===== | + | ===== Replacement in a file ===== |
+ | |||
+ | ==== Replace inplace ==== | ||
Replace inplace sshd_config param (at same position) | Replace inplace sshd_config param (at same position) | ||
Line 29: | Line 31: | ||
- regexp: '^(.*)Port (.*)$' | - regexp: '^(.*)Port (.*)$' | ||
line: "Port 2849" | line: "Port 2849" | ||
+ | </code> | ||
+ | |||
+ | ==== Insert after / before ==== | ||
+ | |||
+ | Use **insertafter** or **insertbefore** | ||
+ | <code> | ||
+ | tasks: | ||
+ | - name: add to ansible hosts file | ||
+ | lineinfile: | ||
+ | dest: /ansible/sshd_config | ||
+ | insertafter: '^\[ansible_ssh_host\]' | ||
+ | line: " test ansible_ssh_host=172.0.0.3" | ||
+ | </code> | ||
+ | |||
+ | ==== Comment the all lines of a file ==== | ||
+ | |||
+ | <code> | ||
+ | tasks: | ||
+ | - replace: | ||
+ | path: /ansible/sshd_config | ||
+ | regexp: '^(?!#)' | ||
+ | replace: '#' | ||
</code> | </code> | ||
Line 46: | Line 70: | ||
</code> | </code> | ||
- | <code> | ||
- | - name: Backup file if it exists | ||
- | hosts: localhost | ||
- | tasks: | ||
- | - name: Check if the file exists | ||
- | stat: | ||
- | path: /path/to/your/file | ||
- | register: file_stat | ||
- | |||
- | - name: Create a backup if the file exists | ||
- | copy: | ||
- | src: /path/to/your/file | ||
- | dest: "/path/to/backup/file_{{ ansible_date_time.iso8601 }}.bak" | ||
- | remote_src: yes | ||
- | when: file_stat.stat.exists | ||
- | </code> |