简体   繁体   English

获取使用云形成模板创建的EC2实例信息

[英]Getting EC2 instance information created using cloud formation template

I am creating one EC2 instance using below Cloud Formation template. 我正在使用下面的Cloud Formation模板创建一个EC2实例。 Named this template as ' dinesh.json '. 将此模板命名为“ dinesh.json ”。

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "Dinesh template",
  "Resources" : {
    "MyEC2Instance" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "ImageId" : "ami-775e4f16",
        "InstanceType" : "t2.micro",
        "KeyName" : "****"
       }
    }
  }
}

Now, using boto3 library, I am launching the above template. 现在,使用boto3库,我启动了上面的模板。

import boto3
cft = boto3.client('cloudformation')
create_cft = cft.create_stack(StackName="Dinesh",TemplateURL=r'https://s3-us-west-2.amazonaws.com/dsp-bucket/dinesh.json')
print create_cft

This is running successfully and getting output as below : 这正在成功运行并获得如下输出:

{u'StackId': 'arn:aws:cloudformation:us-west-2:089691119308:stack/Dinesh/5b573240-548a-11e6-90a0-50a68a0bca36', 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '5b507be9-548a-11e6-8405-55192e2be20a', 'HTTPHeaders': {'x-amzn-requestid': '5b507be9-548a-11e6-8405-55192e2be20a', 'date': 'Thu, 28 Jul 2016 06:13:09 GMT', 'content-length': '376', 'content-type': 'text/xml'}}}

Now, I want to get information of above created EC2 instance like public IP, private IP and other info. 现在,我想获取上面创建的EC2实例的信息,例如公共IP,私有IP和其他信息。

So, can any one please suggest me way how to retrieve the information of this specific EC2 instance? 因此,请问有人可以建议我如何检索此特定EC2实例的信息吗?

Please let me know the various ways to doing the above thing apart from boto3. 请让我知道除了boto3以外,还有其他方法可以完成上述操作。

Use the GetAtt function. 使用GetAtt函数。 For example if you have made an ec2 called bob, then adding this to your Output section will show the privateip 例如,如果您制作了一个名为bob的ec2,则将其添加到“输出”部分将显示privateip

    "Outputs": {
        "AddressOfbob": {
            "Description": "Domainame",
            "Value": {
                            "Fn::GetAtt": [
                            "bob",
                            "PrivateIp"
                      ]

            }
        }
}

Thanks @Vorsprung for the pointing towards right direction. 感谢@Vorsprung为正确的方向指明方向。 Along with this, I am adding a bit descriptive answer. 与此同时,我添加了一些描述性的答案。

Method 1 方法1

Getting EC2 instance info when there is "Output" section present in cloud formation template 云形成模板中存在“输出”部分时获取EC2实例信息

import boto3
import time
cft = boto3.client('cloudformation')
create_cft = cft.create_stack(StackName="Dinesh-1",TemplateURL=r'https://s3-us-west-2.amazonaws.com/bucket/dinesh.json')
print "Create Stack o/p - ",create_cft

#Just adding sleep so that stack creation come to the status of CREATE_COMPLETE
#More logic can be added to check the status of stack creation programmatically.
time.sleep(120)

des_stack = cft.describe_stacks(StackName="Dinesh-1")
print "Describe Stack o/p - ",des_stack

Output is 输出是

Create Stack o/p -  {u'StackId': 'arn:aws:cloudformation:us-west-2:089691119308:stack/Dinesh-1/a92318a0-54a7-11e6-b050-50d0184f2', 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': 'a91c023-54a7-11e6-ba43-67cc9d6ed45b', 'HTTPHeaders': {'x-amzn-requestid': 'a91c023-54a7-11e6-ba43-67cc9d6ed45b', 'date': 'Thu, 28 Jul 2016 09:42:55 GMT', 'content-length': '378', 'content-type': 'text/xml'}}}
Describe Stack o/p -  {u'Stacks': [{u'StackId': 'arn:aws:cloudformation:us-west-2:089691119308:stack/Dinesh-1/a92318a0-54a7-11e6-b050-50a0184f2', u'Description': 'Dinesh template', u'Tags': [], u'Outputs': [{u'Description': 'Private IP', u'OutputKey': 'PrivateIP', u'OutputValue': '172.3.28.221'}, {u'Description': 'Public IP', u'OutputKey': 'PublicIP', u'OutputValue': '52.5.203.173'}], u'CreationTime': datetime.datetime(2016, 7, 28, 9, 42, 55, 624000, tzinfo=tzutc()), u'StackName': 'Dinesh-1', u'NotificationARNs': [], u'StackStatus': 'CREATE_COMPLETE', u'DisableRollback': False}], 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': 'f19dc8ce-54a7-11e6-83e8-01451bce0ba', 'HTTPHeaders': {'x-amzn-requestid': 'f19dc8ce-54a7-11e6-83e8-01451b7ce0a', 'date': 'Thu, 28 Jul 2016 09:44:57 GMT', 'content-length': '1158', 'content-type': 'text/xml'}}}

In describe_stack output, you will get Public IP and Private IP of created EC2 instance. 在describe_stack输出中,您将获得创建的EC2实例的公用IP和专用IP。

Method 2 方法二

Getting EC2 instance info when there is no "Output" section present in cloud formation template 云形成模板中不存在“输出”部分时获取EC2实例信息

import boto3
import time
cft = boto3.client('cloudformation')
create_cft = cft.create_stack(StackName="Dinesh-2",TemplateURL=r'https://s3-us-west-2.amazonaws.com/dsp-bucket/dinesh.json')
print "Create Stack o/p - ",create_cft

#Just adding sleep so that stack creation come to the status of CREATE_COMPLETE
#More logic can be added to check the status of stack creation programmatically.
time.sleep(120)

list_stack_resp = cft.list_stack_resources(StackName="Dinesh-2")
print list_stack_resp

Output is 输出是

Create Stack o/p -  {u'StackId': 'arn:aws:cloudformation:us-west-2:089691119308:stack/Dinesh-2/7238154a8-11e6-9694-50a686be73f2', 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '7234f160-54a8-11e6-bda6-ef311cece04b', 'HTTPHeaders': {'x-amzn-requestid': '7234f160-54a8-11e6-bda6-ef311cece04b', 'date': 'Thu, 28 Jul 2016 09:48:32 GMT', 'content-length': '378', 'content-type': 'text/xml'}}}
{'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': 'baabaa79-54a8-11e6-90e7-9ba061bfa4c', 'HTTPHeaders': {'x-amzn-requestid': 'baabaa79-54a8-11e6-90e7-9bad061bf4c', 'date': 'Thu, 28 Jul 2016 09:50:33 GMT', 'content-length': '687', 'content-type': 'text/xml'}}, u'StackResourceSummaries': [{u'ResourceType': 'AWS::EC2::Instance', u'PhysicalResourceId': 'i-059f15aa', u'LastUpdatedTimestamp': datetime.datetime(2016, 7, 28, 9, 49, 23, 481000, tzinfo=tzutc()), u'ResourceStatus': 'CREATE_COMPLETE', u'LogicalResourceId': 'MyEC2Instance'}]}

From the output of list_stack_resource, get the 'PhysicalResourceId' which is 'i-059f15aa' in this case. 从list_stack_resource的输出中,获取'PhysicalResourceId',在这种情况下为'i-059f15aa'。

Then get the output of describe_instance of ec2 to get full info of EC2 instance created above. 然后获取ec2的describe_instance的输出以获取上面创建的EC2实例的完整信息。

import boto3

ec2 = boto3.client('ec2')
ec2_resp = ec2.describe_instances(InstanceIds=['i-059f15aa'])
print ec2_resp

Output is 输出是

{u'Reservations': [{u'OwnerId': '089691119308', u'ReservationId': 'r-7245ddb6', u'Groups': [], u'Instances': [{u'Monitoring': {u'State': 'disabled'}, u'PublicDnsName': 'ec2-52-42-17-44.us-west-2.compute.amazonaws.com', u'State': {u'Code': 16, u'Name': 'running'}, u'EbsOptimized': False, u'LaunchTime': datetime.datetime(2016, 7, 28, 9, 48, 37, tzinfo=tzutc()), u'PublicIpAddress': '52.42.10.44', u'PrivateIpAddress': '172.3.29.25', u'ProductCodes': [], u'VpcId': 'vpc-c60a2aa3', u'StateTransitionReason': '', u'InstanceId': 'i-059f15aa', u'ImageId': 'ami-775e4f16', u'PrivateDnsName': 'ip-172-31-29-25.us-west-2.compute.internal', u'KeyName': 'dsp', u'SecurityGroups': [{u'GroupName': 'default', u'GroupId': 'sg-53fdaa37'}], u'ClientToken': 'Dines-MyEC2-DJ1D05Q7A088', u'SubnetId': 'subnet-8d0136e8', u'InstanceType': 't2.micro', u'NetworkInterfaces': [{u'Status': 'in-use', u'MacAddress': '02:9f:ab:4a:3c:0b', u'SourceDestCheck': True, u'VpcId': 'vpc-c60a2aa3', u'Description': '', u'Association': {u'PublicIp': '52.42.170.44', u'PublicDnsName': 'ec2-52-42-170-44.us-west-2.compute.amazonaws.com', u'IpOwnerId': 'amazon'}, u'NetworkInterfaceId': 'eni-d5272ca8', u'PrivateIpAddresses': [{u'PrivateDnsName': 'ip-172-31-29-25.us-west-2.compute.internal', u'Association': {u'PublicIp': '52.42.170.44', u'PublicDnsName': 'ec2-52-42-170-44.us-west-2.compute.amazonaws.com', u'IpOwnerId': 'amazon'}, u'Primary': True, u'PrivateIpAddress': '172.31.29.25'}], u'PrivateDnsName': 'ip-172-31-29-25.us-west-2.compute.internal', u'Attachment': {u'Status': 'attached', u'DeviceIndex': 0, u'DeleteOnTermination': True, u'AttachmentId': 'eni-attach-f33c375f', u'AttachTime': datetime.datetime(2016, 7, 28, 9, 48, 37, tzinfo=tzutc())}, u'Groups': [{u'GroupName': 'default', u'GroupId': 'sg-53fdaa37'}], u'SubnetId': 'subnet-8d0136e8', u'OwnerId': '089691119308', u'PrivateIpAddress': '172.31.29.25'}], u'SourceDestCheck': True, u'Placement': {u'Tenancy': 'default', u'GroupName': '', u'AvailabilityZone': 'us-west-2b'}, u'Hypervisor': 'xen', u'BlockDeviceMappings': [{u'DeviceName': '/dev/sda1', u'Ebs': {u'Status': 'attached', u'DeleteOnTermination': True, u'VolumeId': 'vol-21bddea8', u'AttachTime': datetime.datetime(2016, 7, 28, 9, 48, 37, tzinfo=tzutc())}}], u'Architecture': 'x86_64', u'RootDeviceType': 'ebs', u'RootDeviceName': '/dev/sda1', u'VirtualizationType': 'hvm', u'Tags': [{u'Value': 'arn:aws:cloudformation:us-west-2:089691119308:stack/Dinesh-2/723ba810-54a8-11e6-9694-50a686be73f2', u'Key': 'aws:cloudformation:stack-id'}, {u'Value': 'MyEC2Instance', u'Key': 'aws:cloudformation:logical-id'}, {u'Value': 'Dinesh-2', u'Key': 'aws:cloudformation:stack-name'}], u'AmiLaunchIndex': 0}]}], 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '8adf8956-0d5a-4d1f-a821-67fec4b5bbf9', 'HTTPHeaders': {'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'AmazonEC2', 'content-type': 'text/xml;charset=UTF-8', 'date': 'Thu, 28 Jul 2016 09:55:45 GMT'}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM