0
votes

I'm newbie in ansible. I wrote ansible role for creating user and password in "/etc/httpd/.htpasswd" like that:

- name: htpasswd
  htpasswd:
    path: /etc/httpd/.htpasswd
    name: dev
    password: dev
    group: apache
    mode: 0640
  become: true

Now, I'm trying to understand, how I can set user and password placeholder variable per environment for this model using inventory(or any other way). Like, if I ran "ansible playbook -i inventories/dev" so in role of this model could be set:

- name: htpasswd
  htpasswd:
    path: /etc/httpd/.htpasswd
    name: "{{ inventory.htpasswd.name }}"
    password: "{{ inventory.htpasswd.password }}"
    group: apache
    mode: 0640
  become: true

And in inventory folder per environment will be file "htpasswd" with name and password content like that:

name: dev
password: dev

Does Ansible have something like that? Or can someone explain me what best practices?

1

1 Answers

1
votes

By default, each host is assigned to a all group by Ansible. With the following structure you can define group vars based on inventory.

  • inventories/dev/hosts
  • inventories/dev/group_vars/all.yml
  • inventories/staging/hosts
  • inventories/staging/group_vars/all.yml

In inventories/dev/group_vars/all.yml:

name: dev
password: dev

In inventories/staging/group_vars/all.yml:

name: staging
password: staging

And then in your tasks, reference the vars with their names:

- name: htpasswd
  htpasswd:
    path: /etc/httpd/.htpasswd
    name: "{{ name }}"
    password: "{{ password }}"
    group: apache
    mode: 0640
  become: true