Skip to content

Instantly share code, notes, and snippets.

@libert-xyz
Created May 6, 2017 23:42
Show Gist options
  • Save libert-xyz/5d321bde7c57d5d390e5865189a75fc3 to your computer and use it in GitHub Desktop.
Save libert-xyz/5d321bde7c57d5d390e5865189a75fc3 to your computer and use it in GitHub Desktop.
Get private ip from AWS from instances with tags filters: Env:test
import boto3
from string import Template
'''
Return values of key value instance
'''
class EC2:
def get_tags(self,instance):
for t in instance:
if t['Key'] == 'Name':
return t['Value']
return None
def get_ip(self):
key = "Env"
value = "test"
ip_private = {}
#ec2 = boto3.resource('ec2')
ec2 = boto3.client('ec2',region_name='us-east-1')
#instances = ec2.instances.filter(
instances = ec2.describe_instances(
Filters=[
{
'Name': 'tag:%s' %key,
'Values': [
'%s' %value
]}])
for instance in instances['Reservations']:
for ip in instance['Instances']:
ip_private[self.get_tags(ip['Tags'])] = ip['PrivateIpAddress']
return ip_private
node_entry = Template(""" - hostname: $hostname
ip: $ipaddress""")
node_section = Template("""---
nodes:
$nodes
""")
def get_node_entry(self,hostname,ipaddress):
return self.node_entry.substitute(hostname=hostname,ipaddress=ipaddress)
def get_node_entries(self):
nodes = []
for k,v in self.get_ip().iteritems():
nodes.append(self.get_node_entry(k,v))
return '\n'.join(nodes)
def get_nodes_output(self):
return self.node_section.substitute(nodes=self.get_node_entries())
def main():
f = open('nodes','w')
ec2 = EC2()
f.write(ec2.get_nodes_output())
f.close()
print (ec2.get_ip())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment