Ansible: perform role only for some hosts

Let's say I have one play with some roles for installing an application server, and I like to use the same game on both production and testing servers.

Both production and testing servers have the same list of roles, with the exception of one that should only be used on production servers.

Is there any way to indicate that this role will only apply to production servers using the same tutorial?

For example, if a playbook:

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"] }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

and I have two inventory: one for production and one for testing.

When I launch a playbook using a testing inventory, I don’t want the firewall role to play.

- - 'production' - , <var> , 'firewall' '... , , , ?

+4
3
- { role: firewall, tags: ["firewall"], when: MyVar }

. " .

+3

, production_environment, , true false when :

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"], when: production_environment }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

inventory_file. , -i production:

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"], when: inventory_file == "production" }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

- . , , " " .

+6

Why don't you just use inventory groups? Make two inventory:

testing:

[application]
my-dev-server

production:

[application]
company-prod-server

[firewall]
company-prod-server

And change your playlist as follows:

---
- hosts: firewall
  roles:
    - { role: firewall, tags: ["firewall"] }

- hosts: application
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }
+5
source

Source: https://habr.com/ru/post/1657562/


All Articles