Now I want to get the public_dns_name, and then log on to an instance of aws to get the CPU utilization. I know that I can check it with cloudwatch, but now I don’t want to rely on the function provided by amazon to check it directly based on Linux. How can I get it?
ec2 = boto3.resource('ec2',
aws_access_key_id=settings.AWS.get("aws_access_key_id"),
aws_secret_access_key=settings.AWS.get("aws_secret_access_key"),
region_name=settings.AWS.get("region_name"))
user_data_script = """#cloud-config
runcmd:
- sudo systemctl start docker
- cd /srv/app/kfquantum
- sudo docker run --env broker=%s
--env result=redis://10.0.0.245:6379/0
--env host=kf-db.cluster-crietao0wrdu.rds.cn-northwest-1.amazonaws.com.cn
--env user=db
--env pw=y6y83aGagY8hgXZ
-w /kfquantum -d --restart unless-stopped --name kf-celery kf-celery
celery -A kfquantum worker --pool=solo -l info
""" % settings.BROKER_URL
instance_type = "c5.large"
instance = ec2.create_instances(
BlockDeviceMappings=[
{
"DeviceName": "/dev/xvda",
'Ebs': {
'DeleteOnTermination': True,
'VolumeSize': 8
},
},
],
ImageId="ami-09feea664bfc54194",
MinCount=1,
MaxCount=1,
Placement={'AvailabilityZone': 'cn-northwest-1a'},
InstanceType=instance_type,
UserData=user_data_script,
NetworkInterfaces=[
{
'DeviceIndex': 0,
'SubnetId': "subnet-093161e8b00deb367",
'AssociatePublicIpAddress': True
},
]
)
instance = instance[0]
print("1",instance.private_ip_address)
print("2",instance.public_dns_name)
Console
1,10.0.0.73
2
2
Answers
The value for
public_dns_name
is not assigned yet.This could be due to
running
yet. You are trying to fetch the DNS name as soon as thecreate_instances
method is invoked. It takes a few seconds for the instance to reachrunning
state. Thepublic_dns_name
is not available until the instance reachesrunning
state. Check for the instance state and wait for it to be running before trying to get the Public DNS Name.An easy fix without disturbing the rest of your code would be,
Update:
The
instance
object must be reloaded after the waiter for the updated instance attributes to be detected.Try this…
Hope it helps…
r0ck