User Tools

Site Tools


ansible:ansible_tips

This is an old revision of the document!


Ansible tips and tricks

Replace inplace

Replace inplace sshd_config param (at same position)

Ex:

#Port 22
by
Port 2222
or 
Port 2233
---
- hosts: webservers
  tasks:
    - name: Update SSH configuration to be more secure.
      lineinfile:
        dest: /ansible/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        state: present
      with_items:
        - regexp: '^(.*)PasswordAuthentication (.*)$'
          line: "PasswordAuthentication no"
        - regexp: '^(.*)PermitRootLogin (.*)$'
          line: "PermitRootLogin no"
        - regexp: '^(.*)Port (.*)$'
          line: "Port 2849"

Copy / backup file

 - 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'
- 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
ansible/ansible_tips.1740471278.txt.gz · Last modified: 2025/02/25 09:14 by manu