title: Ansible AWS EC2 tags
body: <p>I have an amazon console with multiple instances running. All instances have tags</p>
  
  <p>for example: 
   - tag Name: jenkins
   - tag Name: Nginx
   - tag Name: Artifactory</p>
  
  <p>I want to run an Ansible playbook against the hosts that are tagged as Nginx.</p>
  
  <p>I use dynamic inventory but how do I limit where the playbook is run?</p>
  
  <p>My playbook looks like this:</p>
  
  <pre><code>  - name: Provision an EC2 node
      hosts: local
      connection: local
      gather_facts: False
      vars:
        instance_type: t2.micro
        security_group: somegroup
        #image: ami-a73264ce
        image: ami-9abea4fb
        region: us-west-2
        keypair: ansible_ec2
      tasks:
        - name: Step 1 Create a new AWS EC2 Ubuntu Instance
          local_action: ec2 instance_tags="Name=nginx" group={{ security_group }} instance_type={{ instance_type}} image={{ image }} wait=true region={{ region }} keypair={{ keypair }}
          register: ec2
        - name: Step 2  Add new instance to local host group
          local_action: lineinfile dest=hosts regexp="{{ item.public_dns_name }}" insertafter="[launched]" line="{{ item.public_dns_name }} ansible_ssh_private_key_file=~/.ssh/{{ keypair }}.pem"
          with_items: ec2.instances
        - name: Step 3 Wait for SSH to come up delay 180 sec timeout 600 sec
          local_action: wait_for host={{ item.public_dns_name }} port=22 delay=180 timeout=600 state=started
          with_items: ec2.instances
  
     - name: Step 5 Install nginx steps
       hosts: launched 
       sudo: yes 
       remote_user: ubuntu 
       gather_facts: True
       roles:
         - motd
         - javaubuntu
         - apt-get
         - nginx
  </code></pre>