A better way of create a file if it doesn't exist using Ansible?

137 views Asked by At

I'd like to create an ansible task. The playbook itself should install and configure some settings in my new linux environment, so, one of the thinks I need to do is to install zsh, and after that, write one line to /etc/zsh/zshenv this way:

- name: Check if /etc/zsh/zshenv exists
  ansible.builtin.stat:
    path: "/etc/zsh/zshenv"
  register: file_status


- name: Creates /etc/zsh/zshenv if it doesn't exists
  ansible.builtin.file:
    path: /etc/zsh/zshenv
    state: touch
    owner: root
    group: root
    mode: '0644'
  when: not file_status.stat.exists


- name: configure ZDOTDIR en /etc/zsh/zshenv
  ansible.builtin.lineinfile:
    path: /etc/zsh/zshenv
    line: 'ZDOTDIR=$HOME/.config/zsh/'
    state: present

I'd like to know if ther's any way to use just one or two tasks instead of three. Even better, as I have no experience running ansible, I'd like to know if there's a better way of doing this.

Thanks a lot in advance!!

1

There are 1 answers

1
Alexander Pletnev On BEST ANSWER
  1. Ansible modules are idempotent by default - you don't need to check if the file exists.
  2. lineinfile module has the create parameter to create a file if it doesn't exist yet
  3. it also allows to set the mode, group, and owner just like file module does.

To sum up, you only need one task to achieve your goal:

- name: Configure ZDOTDIR en /etc/zsh/zshenv
  ansible.builtin.lineinfile:
    path: /etc/zsh/zshenv
    line: 'ZDOTDIR=$HOME/.config/zsh/'
    create: true
    state: present
    owner: root
    group: root
    mode: '0644'