Is it possible to check in ansible if a container already exists?
I tried the following:
- name: LXD | Check for already existing container
lxc_container:
name: {{ container_name }}
state: absent
register: check_container_absent
- debug: msg="{{ check_container_absent }}"
- name: LXD | Create dev container
command: # script to create container #
when: check_container_absent.exists
But the output of check_container_absent
did not change after I created the container.
Another solution would also be to check the location, where the containers are stored, if a folder with the container name exists.
Is there a better solution than to check for the folder?
According to the official documentation
Containers must have a unique name. If you attempt to create a container with a name that already exists in the users namespace the module will simply return as “unchanged”.
You should be able to check if the container with name container_name
exists or doesn't exist respectively by checking if the task reports as changed.
- name: Do container things
hosts: localhost
gather_facts: false
tasks:
- name: Delete container if exists
lxc_container:
name: {{ container_name }}
state: absent
register: delete_container
- name: Reports false if container did not already exist
debug:
var: delete_container.changed
- name: Create container if not already exists
lxc_container:
name: {{ container_name }}
register: create_container
- name: Reports false if container did already exist
debug:
var: create_container.changed
Both of the above tasks will actually create/delete the object if it does/does not already exist though.
If you are just looking to collect data on on whether the object exists and conditionally perform some action later depending, you will not want to use the lxc_container
module as it is intended to create/delete, not gather information.
Instead you'll probably want to just use the command/shell module with changed_when: false
and store the output.
- name: Check whether container exists
shell: "lxc list | grep -v {{ container_name }}"
changed_when: false
ignore_errors: true
register: lxc_list
- name: Do thing if container does not exist
debug:
msg: "It doesn't exist"
when: lxc_list.rc != 0