1 minute read

February 2020

OverviewPermalink

I was working on an Ansible playbook to remove a DynamoDB table for a tear down job for features based on their tag values using the Ansible DynamoDB module which was going well until it came to features using multiple tables. For the module to work, you need to supply the table’s name and there is no native Ansible module that allows you to get the name of the DynamoDB tables in the AWS accounts. A way to get around this and what I show below is to use the AWS Cli and Ansible command module.

Below is the script I used to achieve this, including how to create a new list of just the table names that I read about on Jeff Geerling’s blog.

PlaybookPermalink

Console with 4 DynamoDB tables

Console showing tables

---
- hosts: localhost
connection: local
gather_facts: no
vars:
dynamodb_table_names: []
feature: "matttestdb"
environment: "qa"
tasks:
- name: Set AWS region
command: >
aws configure set region "{{ region }}"
- name: Get dynamodb
command: >
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=feature,Values="{{ feature }}" Key=env,Values="{{ environment }}" --resource-type-filters 'dynamodb'
register: table_list
- name: table_info
set_fact:
info: "{{ table_list.stdout }}"
register: table_info
- name: Build a list of all the dynamodb table names.
set_fact:
dynamodb_table_names: "{{ dynamodb_table_names }} + [ '{{ item.ResourceARN.split('/')[1] }}' ]"
with_items: " {{ table_info.ansible_facts.info.ResourceTagMappingList }}"
- name: Output the dynamodb table names
debug:
var: dynamodb_table_names
Resources used
# https://www.jeffgeerling.com/blog/2017/adding-strings-array-ansible
# https://docs.ansible.com/ansible/latest/modules/dynamodb_table_module.html#dynamodb-table-module
# https://docs.aws.amazon.com/cli/latest/reference/resourcegroupstaggingapi/get-resources.html

Running the script above, returns 3 of the tables that match the tag values provided

Output of playbook to get table names

To remove the tablesPermalink

I add the code below to the script. This use the DynamoDB table module to remove all the tables in the list I had created by looping over that list and passing the module each table name to remove.

- name: remove DynamoDB table
dynamodb_table:
name: "{{ item }}"
region: "{{ region }}"
state: absent
with_items: "{{ dynamodb_table_names }}"

Output of deleting tables playbook run

Output of removed playbook run

Console has been updated

Removed tables from the console

SummaryPermalink

Although you currently you can’t use the dynamodb_table module to get a list of tables, using the command module, AWS CLI and the Ansible split function to get the table name is a good solution to get DynamoDB table names by given tag values. This can be used in the automation of Dynamodb tables such as deleting them or modifying them using Ansible playbooks.