def test_get_aws_metadata_none_fields(self, http_request_mock):
        mocked_http_response = {
            'availabilityZone': 'us-west-2b',
            'imageId': 'ami-5fb8c835',
            'privateIp': '10.158.112.84',
            'pendingTime': '2016-11-19T16:32:11Z',
            'accountId': '123456789012',
            'region': 'us-west-2',
            'marketplaceProductCodes': ["1abc2defghijklm3nopqrs4tu"],
            'instanceType': 't2.micro',
            'version': '2017-09-30',
            'architecture': 'x86_64',
        }

        http_request_mock.return_value = json.dumps(mocked_http_response)
        aws_identity_doc_utils.AwsIdentityDocumentUtils.inited = False
        aws_identity_doc_utils.AwsIdentityDocumentUtils.is_running = False
        aws_identity_doc_utils.aws_metadata_map = {}

        self.assertTrue(aws_identity_doc_utils.AwsIdentityDocumentUtils.
                        is_running_on_aws())

        labels_list = aws_identity_doc_utils.AwsIdentityDocumentUtils(
        ).get_aws_metadata()

        self.assertEqual(len(labels_list), 2)

        expected_labels = {
            'aws_account': '123456789012',
            'region': 'us-west-2'
        }

        self.assertEqual(labels_list, expected_labels)
예제 #2
0
def get_instance():
    """Get a resource based on the application environment.

    Returns a `Resource` configured for the current environment, or None if the
    environment is unknown or unsupported.

    :rtype: :class:`opencensus.common.resource.Resource` or None
    :return: A `Resource` configured for the current environment.
    """
    resources = []
    env_resource = resource.get_from_env()
    if env_resource is not None:
        resources.append(env_resource)

    if k8s_utils.is_k8s_environment():
        resources.append(resource.Resource(
            _K8S_CONTAINER, k8s_utils.get_k8s_metadata()))

    if is_gce_environment():
        resources.append(resource.Resource(
            _GCE_INSTANCE,
            gcp_metadata_config.GcpMetadataConfig().get_gce_metadata()))
    elif is_aws_environment():
        resources.append(resource.Resource(
            _AWS_EC2_INSTANCE,
            (aws_identity_doc_utils.AwsIdentityDocumentUtils()
             .get_aws_metadata())))

    if not resources:
        return None
    return resource.merge_resources(resources)
    def test_aws_not_running(self, http_request_mock):
        http_request_mock.return_value = None
        aws_identity_doc_utils.inited = False
        aws_identity_doc_utils.is_running_on_aws = False
        aws_identity_doc_utils.aws_metadata_map = {}

        self.assertFalse(aws_identity_doc_utils.AwsIdentityDocumentUtils.
                         is_running_on_aws())

        labels_list = aws_identity_doc_utils.AwsIdentityDocumentUtils(
        ).get_aws_metadata()

        self.assertEqual(len(labels_list), 0)