Skip to content

Ansible Snippets

Get the hosts of a dynamic ansible inventory

ansible-inventory -i environments/production --graph

You can also use the --list flag to get more info of the hosts.

Speed up the stat module

The stat module calculates the checksum and the md5 of the file in order to get the required data. If you just want to check if the file exists use:

- name: Verify swapfile status
    path: "{{ common_swapfile_location }}"
    get_checksum: no
    get_md5: no
    get_mime: no
    get_attributes: no
  register: swap_status
  changed_when: not swap_status.stat.exists

Stop running docker containers

- name: Get running containers
    containers: yes
  register: docker_info

- name: Stop running containers
    name: "{{ item }}"
    state: stopped
  loop: "{{ docker_info.containers | map(attribute='Id') | list }}"

Moving a file remotely

Funnily enough, you can't without a command. You could use the copy module with:

- name: Copy files from foo to bar
    remote_src: True
    src: /path/to/foo
    dest: /path/to/bar

- name: Remove old files foo
  file: path=/path/to/foo state=absent

But that doesn't move, it copies and removes, which is not the same.

To make the command idempotent you can use a stat task before.

- name: stat foo
  stat: path=/path/to/foo
  register: foo_stat

- name: Move foo to bar
  command: mv /path/to/foo /path/to/bar
  when: foo_stat.stat.exists

Last update: 2022-10-18