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 20:16] 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 31: | Line 33: | ||
</code> | </code> | ||
- | ===== Copy / backup file ===== | + | ==== Insert after / before ==== |
- | + | ||
- | <code> | + | |
- | - name: Ansible Copy using Conditional Statements | + | |
- | hosts: test_group | + | |
- | tasks: | + | |
- | #The env variables can be passed in: | + | |
- | #ex: ansible-playbook ~/playbook.yml -e "env=prod" | + | |
- | - name: Copy Apache config for production | + | |
- | copy: | + | |
- | src: prod_httpd.conf | + | |
- | dest: /etc/httpd/conf/httpd.conf | + | |
- | when: env == 'prod' | + | |
- | </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> | + | |
- | + | ||
- | === Insert after / before === | + | |
Use **insertafter** or **insertbefore** | Use **insertafter** or **insertbefore** | ||
Line 75: | Line 45: | ||
</code> | </code> | ||
- | === Comment the all lines of a file === | + | ==== Comment the all lines of a file ==== |
<code> | <code> | ||
Line 84: | Line 54: | ||
replace: '#' | replace: '#' | ||
</code> | </code> | ||
+ | |||
+ | ===== Copy / backup file ===== | ||
+ | |||
+ | <code> | ||
+ | - name: Ansible Copy using Conditional Statements | ||
+ | hosts: test_group | ||
+ | tasks: | ||
+ | #The env variables can be passed in: | ||
+ | #ex: ansible-playbook ~/playbook.yml -e "env=prod" | ||
+ | - name: Copy Apache config for production | ||
+ | copy: | ||
+ | src: prod_httpd.conf | ||
+ | dest: /etc/httpd/conf/httpd.conf | ||
+ | when: env == 'prod' | ||
+ | </code> | ||
+ |