Is it possible to define variables in a task for a role?

Viewed 548

I need to include a role in my own role, which relies on variables being set. Can I include them in a task and will they be applied to that included role?

Something like this:

- name: Configure firewall ports
  include_role:
    name: ipr-cnrs.nftables
  vars:
    - nft_define:
        input tcp accepted:
          name: in_tcp_accept
          value: '{ 22, 23 }'
2 Answers

Q: "Can I include the variables in a task and will they be applied to that included role?"

A: Yes. It's possible. Correct syntax is

- name: Configure firewall ports
  include_role:
    name: ipr_cnrs_nftables
  vars:
    nft_define:
      input tcp accepted:
        name: in_tcp_accept
        value: '{ 22, 23 }'

For example, the task

shell> cat roles/ipr_cnrs_nftables/tasks/main.yml
- debug:
    var: nft_define

gives

    "nft_define": {
        "input tcp accepted": null,
        "name": "in_tcp_accept",
        "value": "{ 22, 23 }"
    }


Notes:

"Role names are limited to lowercase word characters (i.e., a-z, 0-9) and ‘_’. No special characters are allowed, including ‘.’, ‘-‘, and space. During import, any ‘.’ and ‘-‘ characters contained in the repository name or role_name will be replaced with ‘_’."

  • The attribute value shall be a list of ports. It's a string in the example. Change it
    value: [22, 23 ]
  • In a playbook, the variable will be available when the flow-control reaches the include statement. See Including and Importing.

You can pass a variable with include_role as shown below according to the documentation:

- name: Pass variables to role
  include_role:
    name: myrole
  vars:
    rolevar1: value from task

So your example above can use vars with include_role.

Related