Some Example Ansible Loops
Having been using Ansible for a bit now I’ve found these loops quite useful.
Installing multiple packages:
- name: Install packages apt: state: present install_recommends: no name: - asterisk - asterisk-mysql
Copying files:
- name: Copy files synchronize: src={{item.src}} dest={{item.dest}} with_items: - { src: '/srv/deploy/fail2ban/asterisk.conf', dest: '/etc/fail2ban/filter.d' } - { src: '/srv/deploy/fail2ban/asterisk18.conf', dest: '/etc/fail2ban/filter.d' } - { src: '/srv/deploy/etc/odbc.ini', dest: '/etc/' }
Removing files:
- name: Remove files file: path: "{{item}}" state: absent with_items: - /usr/share/asterisk/moh/macroform-robot_dity.gsm - /usr/share/asterisk/moh/manolo_camp-morning_coffee.gsm - /usr/share/asterisk/moh/reno_project-system.gsm
Adding lines:
- name: Adding Lines lineinfile: path: '{{item.path}}' line: "{{item.line}}" with_items: - { path: '/etc/file1',line: "This line goes n File 1" } - { path: '/etc/file2',line: "This line goes n File 2" }
Replacing contents of lines:
- name: Filetweaks replace: path: '{{item.path}}' regexp: '{{item.regexp}}' replace: "{{item.replace}}" with_items: - { path: '/etc/init.d/asterisk', regexp: '#MAXFILES=1024', replace: 'MAXFILES=8192' }
A sequence of shell commands that ignores non-zero exits:
- name: Test shell loop shell: "{{item}}" ignore_errors: true args: warn: no executable: /bin/bash with_items: - "echo 1" - "echo 2" - "echo 3" - "echo 4" - "echo 5"