User Tools

Site Tools


ansible:ansible_sandbox

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
ansible:ansible_sandbox [2025/02/23 21:43]
manu [Test 3 backup file]
ansible:ansible_sandbox [2025/05/28 10:28] (current)
manu [Test 4 insertafter using bash]
Line 296: Line 296:
 ===== Test 3 backup file ===== ===== Test 3 backup file =====
  
 +
 +        ​
 File is backuped with format **2025-02-23T14:​30:​00Z** File is backuped with format **2025-02-23T14:​30:​00Z**
 <cli prompt='#'>​ <cli prompt='#'>​
Line 314: Line 316:
       when: file_stat.stat.exists       when: file_stat.stat.exists
 </​cli>​ </​cli>​
 +
 +Backup only if modified
 +<cli prompt='#'>​
 +---
 +- name: Backup file if it is different
 +  hosts: localhost
 +  tasks:
 +    - name: Get the checksum of the current file
 +      stat:
 +        path: /​path/​to/​your/​file
 +      register: file_stat
 +
 +    - name: Get the checksum of the last backup (if exists)
 +      stat:
 +        path: "/​path/​to/​backup/​file_last.bak"​
 +      register: backup_stat
 +      ignore_errors:​ yes
 +
 +    - name: Compare the current file checksum with the backup checksum
 +      command: "​sha256sum /​path/​to/​your/​file | awk '{ print $1 }'"​
 +      register: current_checksum
 +      when: file_stat.stat.exists
 +
 +    - name: Compare the backup checksum (if backup exists)
 +      command: "​sha256sum /​path/​to/​backup/​file_last.bak | awk '{ print $1 }'"​
 +      register: backup_checksum
 +      when: backup_stat.stat.exists
 +
 +    - name: Backup the file if checksums are different
 +      copy:
 +        src: /​path/​to/​your/​file
 +        dest: "/​path/​to/​backup/​file_{{ ansible_date_time.iso8601 }}.bak"​
 +        remote_src: yes
 +      when: 
 +        - file_stat.stat.exists
 +        - (backup_stat.stat.exists == false or current_checksum.stdout != backup_checksum.stdout)
 +</​cli>​
 +
 +===== Test 4 insertafter using bash =====
 +
 +<cli>
 +---
 +- name: Insert line after pattern using bash
 +  hosts: all
 +  become: true
 +  tasks:
 +    - name: Insert line after pattern using sed
 +      shell: |
 +        if ! grep -q '​^new_config_line=value$'​ /​etc/​example.conf;​ then
 +          sed -i '/# INSERT HERE/a new_config_line=value'​ /​etc/​example.conf
 +        fi
 +      args:
 +        executable: /bin/bash
 +</​cli> ​       ​
 +
 +https://​stackoverflow.com/​questions/​70162334/​in-ansible-how-do-i-add-a-line-without-delete-comment
 +
 +https://​www.theunixschool.com/​2012/​06/​insert-line-before-or-after-pattern.html
 +
 +
ansible/ansible_sandbox.1740343436.txt.gz ยท Last modified: 2025/02/23 21:43 by manu