Created
December 15, 2017 01:34
-
-
Save stark525/79b23dd3741ad55226aca996523254cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_ip_of_peer_instances_and_write_to_settings_file(self): | |
''' | |
This is run on the source EC2 instance as part of UserData bootstrapping | |
1) Look at the peer(s)' VPC CloudFormation Stack's Outputs for a list of subnets, public or private as defined | |
in the constructor. | |
2) Find instances in those subnets created by this library | |
3) Get the Private IP address of target instances and write it to a local configuration file | |
''' | |
# Query for peer CloudFormation, get instances | |
target_subnet_list = [] | |
target_ip_list = [] | |
with open(self.config_file_path, 'r') as ymlfile: | |
cfg = yaml.load(ymlfile) | |
for peer in self.peers_list: | |
peer_stack_name = self.project_name + '-vpc-' + peer + '-' + cfg['region'] | |
# Look at each peer's CloudFormation Stack Outputs and get a list of subnets (public or private) | |
client = boto3.client('cloudformation') | |
response = client.describe_stacks( | |
StackName=peer_stack_name | |
) | |
for i in range(0,len(response['Stacks'][0]['Outputs'])): | |
if self.public_or_private_subnet == 'public': | |
if 'Subnet' in response['Stacks'][0]['Outputs'][i]['OutputKey'] and 'Public' in \ | |
response['Stacks'][0]['Outputs'][i]['OutputKey']: | |
subnet_id = response['Stacks'][0]['Outputs'][i]['OutputValue'] | |
target_subnet_list.append(subnet_id) | |
else: | |
if 'Subnet' in response['Stacks'][0]['Outputs'][i]['OutputKey'] and 'Private' in \ | |
response['Stacks'][0]['Outputs'][i]['OutputKey']: | |
subnet_id = response['Stacks'][0]['Outputs'][i]['OutputValue'] | |
target_subnet_list.append(subnet_id) | |
# Search the instances in the targeted subnets for a Name tag of VpcSpecValidator | |
client = boto3.client('ec2') | |
describe_response = client.describe_instances( | |
Filters=[{ | |
'Name': 'tag:Name', | |
'Values': ['VpcSpecValidator-test-runner-' + peer + '*'] | |
}] | |
) | |
# Get Private IP addresses of these instances and write them to target_ip_list.settings | |
for i in range(0,len(describe_response['Reservations'])): | |
target_ip_list.append(describe_response['Reservations'][i]['Instances'][0]['PrivateIpAddress']) | |
# Write the list to a configuration file used at runtime for EC2 instance | |
with open('config/env_settings/target_ip_list.settings', 'w') as ymlfile: | |
ymlfile.write(str(target_ip_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment