1
votes

I am using ec2 dynamic inventory.

All of my ec2 instances are tagged with their environment. So for example tag:env = prod or tag:env = test

So my dynamic inventory has variables set properly....

  "ec2": [
    "ip_10_1_1_1_ec2_internal",
    "ip_10_1_1_2_ec2_internal",
    "ip_10_1_1_3_ec2_internal",
    "ip_10_1_1_4_ec2_internal",
    "ip_10_1_1_5_ec2_internal",
    "ip_10_1_1_6_ec2_internal",
    "ip_10_1_1_7_ec2_internal"
  ],

...

  "tag_env_mgmt": [
    "ip_10_1_1_7_ec2_internal",
    "ip_10_1_1_6_c2_internal",
    "ip_10_1_1_5_ec2_internal"
  ],
  "tag_env_prod": [
    "ip_10_1_1_2_ec2_internal",
    "ip_10_1_1_1_ec2_internal"
  ],
  "tag_env_stage": [
    "ip_10_1_1_3_ec2_internal",
    "ip_10_1_1_4_ec2_internal"
  ],

So I now want to set conditionals based on certain tags. Here is the type of playbook conditionals I want to use, adding users only if the tag is "stage":

---
- hosts: ec2
  vars:
    users:
    - user1
    - user2
  tasks:
  - name: "Create user accounts and add users to groups"
    user:
      name: "{{ item }}"
      groups: "sudo"
    with_items: "{{ users }}"
    when: tag_env_stage is defined

Also tried it like this:

  - name: "Create user accounts and add users to groups"
    user:
      name: "{{ item }}"
      groups: "sudo"
    with_items: "{{ users }}"
    when: tag_env_stage

and this:

  - name: "Create user accounts and add users to groups"
    user:
      name: "{{ item }}"
      groups: "sudo"
    with_items: "{{ users }}"
    when: tag_env == stage

The plays fail to execute. I get errors along the lines of:

error while evaluating conditional (tag_env_stage):

I checked the documentation and didn't see anything sticking out at me.

(https://docs.ansible.com/ansible/latest/user_guide/intro_dynamic_inventory.html)

(https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html)

2

2 Answers

3
votes

tag_env_prod, tag_env_stage are group names in your example.

You can use:

when: ('tag_env_stage' in group_names)

But this is a bit ugly. I'd recommend to use modern Ansible version with support of inventory plugins (instead of legacy dynamic inventories). If your inventory is generated with aws_ec2 plugin, you have direct access to tags variable. And so you can use:

when: tags['env'] == 'stage'
0
votes

Managed to get it working with the following syntax.

when: hostvars[inventory_hostname].ec2_tag_env == "stage"

As the other answer mentioned, I was trying to use group_names which are not actually identifiers of the instances themselves. @Konstantin's answer provides how to deal with group_names so I needed to use hostvars object from dynamic inventory.