| 94 | |
| 95 | |
| 96 | class IMDSRegionProvider(BaseProvider): |
| 97 | def __init__(self, session, environ=None, fetcher=None): |
| 98 | """Initialize IMDSRegionProvider. |
| 99 | |
| 100 | :type session: :class:`botocore.session.Session` |
| 101 | :param session: The session is needed to look up configuration for |
| 102 | how to contact the instance metadata service. Specifically the |
| 103 | whether or not it should use the IMDS region at all, and if so how |
| 104 | to configure the timeout and number of attempts to reach the |
| 105 | service. |
| 106 | |
| 107 | :type environ: None or dict |
| 108 | :param environ: A dictionary of environment variables to use. If |
| 109 | ``None`` is the argument then ``os.environ`` will be used by |
| 110 | default. |
| 111 | |
| 112 | :type fecther: :class:`botocore.utils.InstanceMetadataRegionFetcher` |
| 113 | :param fetcher: The class to actually handle the fetching of the region |
| 114 | from the IMDS. If not provided a default one will be created. |
| 115 | """ |
| 116 | self._session = session |
| 117 | if environ is None: |
| 118 | environ = os.environ |
| 119 | self._environ = environ |
| 120 | self._fetcher = fetcher |
| 121 | |
| 122 | def provide(self): |
| 123 | """Provide the region value from IMDS.""" |
| 124 | instance_region = self._get_instance_metadata_region() |
| 125 | return instance_region |
| 126 | |
| 127 | def _get_instance_metadata_region(self): |
| 128 | fetcher = self._get_fetcher() |
| 129 | region = fetcher.retrieve_region() |
| 130 | return region |
| 131 | |
| 132 | def _get_fetcher(self): |
| 133 | if self._fetcher is None: |
| 134 | self._fetcher = self._create_fetcher() |
| 135 | return self._fetcher |
| 136 | |
| 137 | def _create_fetcher(self): |
| 138 | metadata_timeout = self._session.get_config_variable( |
| 139 | 'metadata_service_timeout' |
| 140 | ) |
| 141 | metadata_num_attempts = self._session.get_config_variable( |
| 142 | 'metadata_service_num_attempts' |
| 143 | ) |
| 144 | imds_config = { |
| 145 | 'ec2_metadata_service_endpoint': self._session.get_config_variable( |
| 146 | 'ec2_metadata_service_endpoint' |
| 147 | ), |
| 148 | 'ec2_metadata_service_endpoint_mode': resolve_imds_endpoint_mode( |
| 149 | self._session |
| 150 | ), |
| 151 | 'ec2_metadata_v1_disabled': self._session.get_config_variable( |
| 152 | 'ec2_metadata_v1_disabled' |
| 153 | ), |
no outgoing calls