| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Contributors to the Ansible project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: lambda_execute |
| 10 |
version_added: 5.0.0 |
| 11 |
short_description: Execute an AWS Lambda function |
| 12 |
description: |
| 13 |
- This module executes AWS Lambda functions, allowing synchronous and asynchronous |
| 14 |
invocation. |
| 15 |
- Prior to release 5.0.0 this module was called M(community.aws.execute_lambda). |
| 16 |
The usage did not change. |
| 17 |
- This module was originally added to C(community.aws) in release 1.0.0. |
| 18 |
extends_documentation_fragment: |
| 19 |
- amazon.aws.common.modules |
| 20 |
- amazon.aws.region.modules |
| 21 |
- amazon.aws.boto3 |
| 22 |
author: |
| 23 |
- "Ryan Scott Brown (@ryansb) <[email protected]>" |
| 24 |
notes: |
| 25 |
- Async invocation will always return an empty RV(result.output) key. |
| 26 |
- Synchronous invocation may result in a function timeout, resulting in an |
| 27 |
empty RV(result.output) key. |
| 28 |
options: |
| 29 |
name: |
| 30 |
description: |
| 31 |
- The name of the function to be invoked. This can only be used for |
| 32 |
invocations within the calling account. To invoke a function in another |
| 33 |
account, use O(function_arn) to specify the full ARN. |
| 34 |
type: str |
| 35 |
function_arn: |
| 36 |
description: |
| 37 |
- The name of the function to be invoked |
| 38 |
type: str |
| 39 |
tail_log: |
| 40 |
description: |
| 41 |
- If O(tail_log=true), the result of the task will include the last 4 KB |
| 42 |
of the CloudWatch log for the function execution. Log tailing only |
| 43 |
works if you use synchronous invocation O(wait=true). This is usually |
| 44 |
used for development or testing Lambdas. |
| 45 |
type: bool |
| 46 |
default: false |
| 47 |
wait: |
| 48 |
description: |
| 49 |
- Whether to wait for the function results or not. If O(wait=no) |
| 50 |
the task will not return any results. To wait for the Lambda function |
| 51 |
to complete, set O(wait=true) and the result will be available in the |
| 52 |
I(output) key. |
| 53 |
type: bool |
| 54 |
default: true |
| 55 |
dry_run: |
| 56 |
description: |
| 57 |
- Do not *actually* invoke the function. A C(DryRun) call will check that |
| 58 |
the caller has permissions to call the function, especially for |
| 59 |
checking cross-account permissions. |
| 60 |
type: bool |
| 61 |
default: false |
| 62 |
version_qualifier: |
| 63 |
description: |
| 64 |
- Which version/alias of the function to run. This defaults to the |
| 65 |
V(LATEST) revision, but can be set to any existing version or alias. |
| 66 |
See U(https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) |
| 67 |
for details. |
| 68 |
type: str |
| 69 |
payload: |
| 70 |
description: |
| 71 |
- A dictionary in any form to be provided as input to the Lambda function. |
| 72 |
default: {} |
| 73 |
type: dict |
| 74 |
""" |
| 75 |
|
| 76 |
EXAMPLES = r""" |
| 77 |
- amazon.aws.lambda_execute: |
| 78 |
name: test-function |
| 79 |
# the payload is automatically serialized and sent to the function |
| 80 |
payload: |
| 81 |
foo: bar |
| 82 |
value: 8 |
| 83 |
register: response |
| 84 |
|
| 85 |
# Test that you have sufficient permissions to execute a Lambda function in |
| 86 |
# another account |
| 87 |
- amazon.aws.lambda_execute: |
| 88 |
function_arn: arn:aws:lambda:us-east-1:123456789012:function/some-function |
| 89 |
dry_run: true |
| 90 |
|
| 91 |
- amazon.aws.lambda_execute: |
| 92 |
name: test-function |
| 93 |
payload: |
| 94 |
foo: bar |
| 95 |
value: 8 |
| 96 |
wait: true |
| 97 |
tail_log: true |
| 98 |
register: response |
| 99 |
# the response will have a `logs` key that will contain a log (up to 4KB) of the function execution in Lambda |
| 100 |
|
| 101 |
# Pass the Lambda event payload as a json file. |
| 102 |
- amazon.aws.lambda_execute: |
| 103 |
name: test-function |
| 104 |
payload: "{{ lookup('file','lambda_event.json') }}" |
| 105 |
register: response |
| 106 |
|
| 107 |
- amazon.aws.lambda_execute: |
| 108 |
name: test-function |
| 109 |
version_qualifier: PRODUCTION |
| 110 |
""" |
| 111 |
|
| 112 |
RETURN = r""" |
| 113 |
result: |
| 114 |
description: Resulting data structure from a successful task execution. |
| 115 |
returned: success |
| 116 |
type: dict |
| 117 |
contains: |
| 118 |
output: |
| 119 |
description: Function output if O(wait=true) and the function returns a value. |
| 120 |
returned: success |
| 121 |
type: dict |
| 122 |
sample: "{ 'output': 'something' }" |
| 123 |
logs: |
| 124 |
description: The last 4KB of the function logs. Only provided if O(tail_log=true). |
| 125 |
type: str |
| 126 |
returned: if O(tail_log=true) |
| 127 |
status: |
| 128 |
description: V(StatusCode) of API call exit (200 for synchronous invokes, 202 for async). |
| 129 |
type: int |
| 130 |
sample: 200 |
| 131 |
returned: always |
| 132 |
""" |
| 133 |
|
| 134 |
import base64 |
| 135 |
import json |
| 136 |
|
| 137 |
try: |
| 138 |
import botocore |
| 139 |
except ImportError: |
| 140 |
pass # Handled by AnsibleAWSModule |
| 141 |
|
| 142 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 143 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 144 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 145 |
|
| 146 |
|
| 147 |
def main(): |
| 148 |
argument_spec = dict( |
| 149 |
name=dict(), |
| 150 |
function_arn=dict(), |
| 151 |
wait=dict(default=True, type="bool"), |
| 152 |
tail_log=dict(default=False, type="bool"), |
| 153 |
dry_run=dict(default=False, type="bool"), |
| 154 |
version_qualifier=dict(), |
| 155 |
payload=dict(default={}, type="dict"), |
| 156 |
) |
| 157 |
module = AnsibleAWSModule( |
| 158 |
argument_spec=argument_spec, |
| 159 |
supports_check_mode=True, |
| 160 |
mutually_exclusive=[ |
| 161 |
["name", "function_arn"], |
| 162 |
], |
| 163 |
required_one_of=[("name", "function_arn")], |
| 164 |
) |
| 165 |
|
| 166 |
name = module.params.get("name") |
| 167 |
function_arn = module.params.get("function_arn") |
| 168 |
await_return = module.params.get("wait") |
| 169 |
dry_run = module.params.get("dry_run") |
| 170 |
tail_log = module.params.get("tail_log") |
| 171 |
version_qualifier = module.params.get("version_qualifier") |
| 172 |
payload = module.params.get("payload") |
| 173 |
|
| 174 |
try: |
| 175 |
client = module.client("lambda", retry_decorator=AWSRetry.jittered_backoff()) |
| 176 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 177 |
module.fail_json_aws(e, msg="Failed to connect to AWS") |
| 178 |
|
| 179 |
invoke_params = {} |
| 180 |
|
| 181 |
if await_return: |
| 182 |
# await response |
| 183 |
invoke_params["InvocationType"] = "RequestResponse" |
| 184 |
else: |
| 185 |
# fire and forget |
| 186 |
invoke_params["InvocationType"] = "Event" |
| 187 |
if dry_run or module.check_mode: |
| 188 |
# dry_run overrides invocation type |
| 189 |
invoke_params["InvocationType"] = "DryRun" |
| 190 |
|
| 191 |
if tail_log and await_return: |
| 192 |
invoke_params["LogType"] = "Tail" |
| 193 |
elif tail_log and not await_return: |
| 194 |
module.fail_json( |
| 195 |
msg=( |
| 196 |
"The `tail_log` parameter is only available if " |
| 197 |
"the invocation waits for the function to complete. " |
| 198 |
"Set `wait` to true or turn off `tail_log`." |
| 199 |
) |
| 200 |
) |
| 201 |
else: |
| 202 |
invoke_params["LogType"] = "None" |
| 203 |
|
| 204 |
if version_qualifier: |
| 205 |
invoke_params["Qualifier"] = version_qualifier |
| 206 |
|
| 207 |
if payload: |
| 208 |
invoke_params["Payload"] = json.dumps(payload) |
| 209 |
|
| 210 |
if function_arn: |
| 211 |
invoke_params["FunctionName"] = function_arn |
| 212 |
elif name: |
| 213 |
invoke_params["FunctionName"] = name |
| 214 |
|
| 215 |
if module.check_mode: |
| 216 |
module.exit_json(changed=True) |
| 217 |
|
| 218 |
try: |
| 219 |
wait_for_lambda(client, module, name or function_arn) |
| 220 |
response = client.invoke(**invoke_params, aws_retry=True) |
| 221 |
except is_boto3_error_code("ResourceNotFoundException") as nfe: |
| 222 |
module.fail_json_aws( |
| 223 |
nfe, |
| 224 |
msg=( |
| 225 |
"Could not find Lambda to execute. Make sure " |
| 226 |
"the ARN is correct and your profile has " |
| 227 |
"permissions to execute this function." |
| 228 |
), |
| 229 |
) |
| 230 |
except botocore.exceptions.ClientError as ce: # pylint: disable=duplicate-except |
| 231 |
module.fail_json_aws(ce, msg="Client-side error when invoking Lambda, check inputs and specific error") |
| 232 |
except botocore.exceptions.ParamValidationError as ve: # pylint: disable=duplicate-except |
| 233 |
module.fail_json_aws(ve, msg="Parameters to `invoke` failed to validate") |
| 234 |
except botocore.exceptions.BotoCoreError as e: # pylint: disable=duplicate-except |
| 235 |
module.fail_json_aws(e, msg="Unexpected failure while invoking Lambda function") |
| 236 |
|
| 237 |
results = { |
| 238 |
"logs": "", |
| 239 |
"status": response["StatusCode"], |
| 240 |
"output": "", |
| 241 |
} |
| 242 |
|
| 243 |
if response.get("LogResult"): |
| 244 |
try: |
| 245 |
# logs are base64 encoded in the API response |
| 246 |
results["logs"] = base64.b64decode(response.get("LogResult", "")) |
| 247 |
except Exception as e: |
| 248 |
module.fail_json_aws(e, msg="Failed while decoding logs") |
| 249 |
|
| 250 |
if invoke_params["InvocationType"] == "RequestResponse": |
| 251 |
try: |
| 252 |
results["output"] = json.loads(response["Payload"].read().decode("utf8")) |
| 253 |
except Exception as e: |
| 254 |
module.fail_json_aws(e, msg="Failed while decoding function return value") |
| 255 |
|
| 256 |
if isinstance(results.get("output"), dict) and any( |
| 257 |
[results["output"].get("stackTrace"), results["output"].get("errorMessage")] |
| 258 |
): |
| 259 |
# AWS sends back stack traces and error messages when a function failed |
| 260 |
# in a RequestResponse (synchronous) context. |
| 261 |
template = ( |
| 262 |
"Function executed, but there was an error in the Lambda function. " |
| 263 |
"Message: {errmsg}, Type: {type}, Stack Trace: {trace}" |
| 264 |
) |
| 265 |
|
| 266 |
error_data = { |
| 267 |
# format the stacktrace sent back as an array into a multiline string |
| 268 |
"trace": "\n".join(results.get("output", {}).get("stackTrace", [])), |
| 269 |
"errmsg": results["output"].get("errorMessage"), |
| 270 |
"type": results["output"].get("errorType"), |
| 271 |
} |
| 272 |
module.fail_json(msg=template.format(**error_data), result=results) |
| 273 |
|
| 274 |
module.exit_json(changed=True, result=results) |
| 275 |
|
| 276 |
|
| 277 |
def wait_for_lambda(client, module, name_or_arn): |
| 278 |
try: |
| 279 |
client_active_waiter = client.get_waiter("function_active") |
| 280 |
client_updated_waiter = client.get_waiter("function_updated") |
| 281 |
client_active_waiter.wait(FunctionName=name_or_arn) |
| 282 |
client_updated_waiter.wait(FunctionName=name_or_arn) |
| 283 |
except botocore.exceptions.WaiterError as e: |
| 284 |
module.fail_json_aws(e, msg="Timeout while waiting on lambda to be Active") |
| 285 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 286 |
module.fail_json_aws(e, msg="Failed while waiting on lambda to be Active") |
| 287 |
|
| 288 |
|
| 289 |
if __name__ == "__main__": |
| 290 |
main() |