Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Variable in Ansible aws_ec2 plugin

I want to filter ec2 instances according to the Environment tag which I define when I run the scripts, i.e ansible-playbook start.yml -e env=dev

However, it seems that the plugin is not parsing variables. Any idea on how to achieve this task?

my aws_ec2.yml:

---
  plugin: aws_ec2
  regions:
    - eu-central-1
  filters:
          tag:Secure: 'yes'
          tag:Environment: "{{ env }}"

  hostnames:
    - private-ip-address
  
  strict: False
  groups:
  keyed_groups:
          - key: tags.Function
            separator: ''

Edit

There is no error message resulting when running the playbook. The only problem that ansible handle the variable exactly as a string tag:Environment: "{{ env }}"instead of value tag:Environment: dev

like image 327
roAl Avatar asked Jan 01 '26 08:01

roAl


1 Answers

This post is already a few years old but since this still seems to be an issue I want to share our workaround for this:

Before starting the actual pipeline, we generate the inventory plugin file from a template with Ansible itself. After this the inventory will be created by running ansible-inventory -i aws_ec2.yml .. etc.

With this approach we don't have to create a new inventory plugin file for each combination and reuse vars for the actual playbooks.

Maybe somebody finds this helpful in the future.

like image 85
itsphil Avatar answered Jan 02 '26 20:01

itsphil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!