Skip to content

Instantly share code, notes, and snippets.

@tbjers
Last active May 29, 2019 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbjers/11bc02b982f077cf504326eada3b87e9 to your computer and use it in GitHub Desktop.
Save tbjers/11bc02b982f077cf504326eada3b87e9 to your computer and use it in GitHub Desktop.
Create dynamic Ansible inventory from Digital Ocean terraform state
#!/bin/sh
# Assuming your terraform files are in ./ and Ansible in deploy/
# this one-liner extracts ipv4_address and groups them under hostname.
# Sample output:
# [my_droplet]
# 192.168.1.1
terraform state pull | jq -r 'def kv: to_entries[] | "\(.value)"; .resources | .[] | select(.type == "digitalocean_droplet") | { "\(.name)": [.instances[].attributes.ipv4_address] } | [to_entries[] | "[\(.key)]", (.value|kv)] | join("\n")' > deploy/hosts
# Want to add these hosts to ~/.ssh/known_hosts?
xargs -0 -n 1 ssh-keyscan < <(tail +2 deploy/hosts | tr \\n \\0) > ~/.ssh/known_hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment