0

I would like to create an Ansible playbook that makes a new directory on many servers. I understand how to set the mode, the group will be the same across all environments, but the owner needs to be set depending on the hostname. For example, if the hostname of a particular server is hostnameABCdb, the owner needs to be ABCadm. However, if the hostname of a server is hostnameDEFdb, the owner needs to be DEFadm. I am a jr. engineer, so fairly new to Linux/Ansible and still learning the ropes (using RHEL 8). Thanks for any feedback!

I used a two step process, but it was tedious and I know there should be another solution. Step one- set up yml to create the directory. Step two- set up a second yml for each server group to change the owner.

STEP 1 yml:

- hosts: all
  become: yes
  become_method: sudo
  gather_facts: no

  tasks:

  - name: Create directory /usr/dir/newdir
    file:
      path: /usr/dir/newdir
      state: directory
      recurse: yes
      owner: root
      group: chosengroup
      mode: 0755

STEP 2 yml:

- hosts: all
  become: yes
  become_method: sudo
  gather_facts: no

  tasks:

  - name: Change owner
    command: chown ABCadm:chosengroup /usr/dir/newdir
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63

1 Answers1

0

Q: "For server hostnameABCdb, the owner needs to be ABCadm ... for server hostnameDEFdb, the owner needs to be DEFadm".

A: Use Ansible special variable inventory_hostname:

"The inventory name for the ‘current’ host being iterated over in the play"

For example,

- name: Create directory /usr/dir/newdir
  file:
    path: /usr/dir/newdir
    state: directory
    recurse: yes
    owner: "{{ inventory_hostname[8:] }}"
    group: chosengroup
    mode: 0755
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Correct, more specificly `owner: "{{ inventory_hostname[8:11] }}adm"`. ... just for reference [How slicing in Python works](https://stackoverflow.com/questions/509211/). – U880D Jul 19 '23 at 05:31