Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MattSurabian/f20a63bdd910827f2a3f to your computer and use it in GitHub Desktop.
Save MattSurabian/f20a63bdd910827f2a3f to your computer and use it in GitHub Desktop.

Setting Tags in Terraform

Determine some sensible tags to pass non-critical information to Ansible or other CM solutions:

resource "aws_instance" "main" {
...
  tags {
  ...
    "some_tag" = "waka"
  }
}

Limiting Playbooks via AWS Tags

Make sure the dynamic inventory config file (ec2.ini) has at least the group_by_tag_keys option commented out

...
# The EC2 inventory output can become very large. To manage its size,
# configure which groups should be created.
# group_by_key_pair = True
group_by_tag_keys = True

At command runtime:

ansible-playbook ... --limit tag_some_tag_Waka

In the playbook:

- hosts: tag_some_tag_Waka

Using EC2 Facts in a playbook with dynamic inventory

{{ec2_tag_some_tag}}

Using "EC2 Facts" in a playbook without dynamic inventory

For this to work the instance must have the AWS CLI installed and have an IAM role assigned with the necessary permissions.

    - name: get instance tags
      shell: aws ec2 describe-tags --filters="Name=resource-id,Values=$(ec2metadata --instance-id)"
      environment:
        AWS_DEFAULT_REGION: us-east-1
      register: instance_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment