====== Ansible tips and tricks ====== ===== Replacement in a file ===== ==== 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" ==== Insert after / before ==== Use **insertafter** or **insertbefore** 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" ==== Comment the all lines of a file ==== tasks: - replace: path: /ansible/sshd_config regexp: '^(?!#)' replace: '#' ===== 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'