Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option "metadata_token_ttl_seconds" to ec2_metadata_facts module. #2209

Merged
merged 6 commits into from
Aug 5, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions plugins/modules/ec2_metadata_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,23 @@
is set to disabled for the EC2 instance, the module will return an error while retrieving a session token.
notes:
- Parameters to filter on ec2_metadata_facts may be added later.
options:
metadata_token_ttl_seconds:
description:
- Specify a value for the V(X-aws-ec2-metadata-token-ttl-seconds) header.
tremble marked this conversation as resolved.
Show resolved Hide resolved
- Value must be between V(1) and V(21600).
type: int
default: 60
tremble marked this conversation as resolved.
Show resolved Hide resolved
"""

EXAMPLES = r"""
# Gather EC2 metadata facts
- amazon.aws.ec2_metadata_facts:

# Set a bigger value for X-aws-ec2-metadata-token-ttl-seconds header
- amazon.aws.ec2_metadata_facts:
metadata_token_ttl_seconds: 240

- debug:
msg: "This instance is a t1.micro"
when: ansible_ec2_instance_type == "t1.micro"
Expand Down Expand Up @@ -610,7 +621,8 @@ def fix_invalid_varnames(self, data):

def fetch_session_token(self, uri_token):
"""Used to get a session token for IMDSv2"""
headers = {"X-aws-ec2-metadata-token-ttl-seconds": "60"}
metadata_token_ttl_seconds = self.module.params.get("metadata_token_ttl_seconds")
headers = {"X-aws-ec2-metadata-token-ttl-seconds": metadata_token_ttl_seconds}
response, info = fetch_url(self.module, uri_token, method="PUT", headers=headers, force=True)

if info.get("status") == 403:
Expand Down Expand Up @@ -657,11 +669,20 @@ def run(self):


def main():
argument_spec = dict(
metadata_token_ttl_seconds=dict(required=False, default=60, type="int"),
tremble marked this conversation as resolved.
Show resolved Hide resolved
)

module = AnsibleModule(
argument_spec={},
argument_spec=argument_spec,
supports_check_mode=True,
)

metadata_token_ttl_seconds = module.params.get("metadata_token_ttl_seconds")

if metadata_token_ttl_seconds <= 0 or metadata_token_ttl_seconds > 21600:
module.fail_json(msg="The option 'metadata_token_ttl_seconds' must be set to a value between 1 and 21600.")

ec2_metadata_facts = Ec2Metadata(module).run()
ec2_metadata_facts_result = dict(changed=False, ansible_facts=ec2_metadata_facts)

Expand Down
Loading