[cloud] new module lambda_policy (PR #24951)

- Fixes to lambda
- reformatting + tests for lambda_facts
- lambda module integration test
- switch lambda and lambda_facts to AnsibleAwsModule
- Get the account ID from STS, GetUser, and finally error message
This commit is contained in:
Michael De La Rue 2017-05-16 14:26:55 +01:00 committed by Ryan S. Brown
parent c36c34ef7e
commit fbec5ab12d
16 changed files with 1481 additions and 123 deletions

View file

@ -262,7 +262,7 @@ def main():
if invoke_params['InvocationType'] == 'RequestResponse':
try:
results['output'] = json.loads(response['Payload'].read())
results['output'] = json.loads(response['Payload'].read().decode('utf8'))
except Exception as e:
module.fail_json(msg="Failed while decoding function return value", exception=traceback.format_exc())

View file

@ -36,19 +36,18 @@ options:
state:
description:
- Create or delete Lambda function
required: false
default: present
choices: [ 'present', 'absent' ]
runtime:
description:
- The runtime environment for the Lambda function you are uploading. Required when creating a function. Use parameters as described in boto3 docs.
Current example runtime environments are nodejs, nodejs4.3, java8 or python2.7
required: true
- Required when C(state=present)
role:
description:
- The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your function to access any other Amazon Web Services (AWS)
resources. You may use the bare ARN if the role belongs to the same AWS account.
default: null
- Required when C(state=present)
handler:
description:
- The function within your code that Lambda calls to begin execution
@ -56,17 +55,21 @@ options:
zip_file:
description:
- A .zip file containing your deployment package
- If C(state=present) then either zip_file or s3_bucket must be present.
required: false
default: null
aliases: [ 'src' ]
s3_bucket:
description:
- Amazon S3 bucket name where the .zip file containing your deployment package is stored
- If C(state=present) then either zip_file or s3_bucket must be present.
- s3_bucket and s3_key are required together
required: false
default: null
s3_key:
description:
- The Amazon S3 object (the deployment package) key name you want to upload
- s3_bucket and s3_key are required together
required: false
default: null
s3_object_version:
@ -189,30 +192,53 @@ output:
}
'''
# Import from Python standard library
from ansible.module_utils._text import to_native
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn, camel_dict_to_snake_dict
import base64
import hashlib
import traceback
try:
import botocore
HAS_BOTOCORE = True
from botocore.exceptions import ClientError, ValidationError, ParamValidationError
except ImportError:
HAS_BOTOCORE = False
pass # protected by AnsibleAWSModule
try:
import boto3
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def get_account_id(module, region=None, endpoint=None, **aws_connect_kwargs):
"""return the account id we are currently working on
get_account_id tries too find out the account that we are working
on. It's not guaranteed that this will be easy so we try in
several different ways. Giving either IAM or STS privilages to
the account should be enough to permit this.
"""
try:
sts_client = boto3_conn(module, conn_type='client', resource='sts',
region=region, endpoint=endpoint, **aws_connect_kwargs)
account_id = sts_client.get_caller_identity().get('Account')
except ClientError:
try:
iam_client = boto3_conn(module, conn_type='client', resource='iam',
region=region, endpoint=endpoint, **aws_connect_kwargs)
account_id = iam_client.get_user()['User']['Arn'].split(':')[4]
except ClientError as e:
if (e.response['Error']['Code'] == 'AccessDenied'):
except_msg = to_native(e.message)
account_id = except_msg.search("arn:aws:iam::([0-9]{12,32}):\w+/").group(1)
if account_id is None:
module.fail_json_aws(e, msg="getting account information")
except Exception as e:
module.fail_json_aws(e, msg="getting account information")
return account_id
def get_current_function(connection, function_name, qualifier=None):
try:
if qualifier is not None:
return connection.get_function(FunctionName=function_name,
Qualifier=qualifier)
return connection.get_function(FunctionName=function_name, Qualifier=qualifier)
return connection.get_function(FunctionName=function_name)
except botocore.exceptions.ClientError:
except ClientError:
return None
@ -229,25 +255,23 @@ def sha256sum(filename):
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['present', 'absent']),
runtime=dict(type='str', required=True),
role=dict(type='str', default=None),
handler=dict(type='str', default=None),
zip_file=dict(type='str', default=None, aliases=['src']),
s3_bucket=dict(type='str'),
s3_key=dict(type='str'),
s3_object_version=dict(type='str', default=None),
description=dict(type='str', default=''),
argument_spec = dict(
name=dict(required=True),
state=dict(default='present', choices=['present', 'absent']),
runtime=dict(),
role=dict(),
handler=dict(),
zip_file=dict(aliases=['src']),
s3_bucket=dict(),
s3_key=dict(),
s3_object_version=dict(),
description=dict(default=''),
timeout=dict(type='int', default=3),
memory_size=dict(type='int', default=128),
vpc_subnet_ids=dict(type='list', default=None),
vpc_security_group_ids=dict(type='list', default=None),
environment_variables=dict(type='dict', default=None),
dead_letter_arn=dict(type='str', default=None),
)
vpc_subnet_ids=dict(type='list'),
vpc_security_group_ids=dict(type='list'),
environment_variables=dict(type='dict'),
dead_letter_arn=dict(),
)
mutually_exclusive = [['zip_file', 's3_key'],
@ -257,10 +281,13 @@ def main():
required_together = [['s3_key', 's3_bucket'],
['vpc_subnet_ids', 'vpc_security_group_ids']]
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=mutually_exclusive,
required_together=required_together)
required_if = [['state', 'present', ['runtime', 'handler', 'role']]]
module = AnsibleAWSModule(argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=mutually_exclusive,
required_together=required_together,
required_if=required_if)
name = module.params.get('name')
state = module.params.get('state').lower()
@ -282,12 +309,6 @@ def main():
check_mode = module.check_mode
changed = False
if not HAS_BOTOCORE:
module.fail_json(msg='Python module "botocore" is missing, please install it')
if not HAS_BOTO3:
module.fail_json(msg='Python module "boto3" is missing, please install it')
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
if not region:
module.fail_json(msg='region must be specified')
@ -295,20 +316,16 @@ def main():
try:
client = boto3_conn(module, conn_type='client', resource='lambda',
region=region, endpoint=ec2_url, **aws_connect_kwargs)
except (botocore.exceptions.ClientError, botocore.exceptions.ValidationError) as e:
module.fail_json(msg=str(e))
except (ClientError, ValidationError) as e:
module.fail_json_aws(e, msg="Trying to connect to AWS")
if role.startswith('arn:aws:iam'):
role_arn = role
else:
# get account ID and assemble ARN
try:
iam_client = boto3_conn(module, conn_type='client', resource='iam',
region=region, endpoint=ec2_url, **aws_connect_kwargs)
account_id = iam_client.get_user()['User']['Arn'].split(':')[4]
if state == 'present':
if role.startswith('arn:aws:iam'):
role_arn = role
else:
# get account ID and assemble ARN
account_id = get_account_id(module, region=region, endpoint=ec2_url, **aws_connect_kwargs)
role_arn = 'arn:aws:iam::{0}:role/{1}'.format(account_id, role)
except (botocore.exceptions.ClientError, botocore.exceptions.ValidationError) as e:
module.fail_json(msg=str(e))
# Get function configuration if present, False otherwise
current_function = get_current_function(client, name)
@ -334,8 +351,9 @@ def main():
func_kwargs.update({'Timeout': timeout})
if memory_size and current_config['MemorySize'] != memory_size:
func_kwargs.update({'MemorySize': memory_size})
if (environment_variables is not None) and (current_config.get('Environment', {}).get('Variables', {}) != environment_variables):
func_kwargs.update({'Environment':{'Variables': environment_variables}})
if (environment_variables is not None) and (current_config.get(
'Environment', {}).get('Variables', {}) != environment_variables):
func_kwargs.update({'Environment': {'Variables': environment_variables}})
if dead_letter_arn is not None:
if current_config.get('DeadLetterConfig'):
if current_config['DeadLetterConfig']['TargetArn'] != dead_letter_arn:
@ -350,11 +368,8 @@ def main():
# If VPC configuration is desired
if vpc_subnet_ids or vpc_security_group_ids:
if len(vpc_subnet_ids) < 1:
module.fail_json(msg='At least 1 subnet is required')
if len(vpc_security_group_ids) < 1:
module.fail_json(msg='At least 1 security group is required')
if not vpc_subnet_ids or not vpc_security_group_ids:
module.fail_json(msg='vpc connectivity requires at least one security group and one subnet')
if 'VpcConfig' in current_config:
# Compare VPC config with current config
@ -365,14 +380,13 @@ def main():
vpc_security_group_ids_changed = sorted(vpc_security_group_ids) != sorted(current_vpc_security_group_ids)
if 'VpcConfig' not in current_config or subnet_net_id_changed or vpc_security_group_ids_changed:
func_kwargs.update({'VpcConfig':
{'SubnetIds': vpc_subnet_ids,'SecurityGroupIds': vpc_security_group_ids}})
new_vpc_config = {'SubnetIds': vpc_subnet_ids,
'SecurityGroupIds': vpc_security_group_ids}
func_kwargs.update({'VpcConfig': new_vpc_config})
else:
# No VPC configuration is desired, assure VPC config is empty when present in current config
if ('VpcConfig' in current_config and
'VpcId' in current_config['VpcConfig'] and
current_config['VpcConfig']['VpcId'] != ''):
func_kwargs.update({'VpcConfig':{'SubnetIds': [], 'SecurityGroupIds': []}})
if 'VpcConfig' in current_config and current_config['VpcConfig'].get('VpcId'):
func_kwargs.update({'VpcConfig': {'SubnetIds': [], 'SecurityGroupIds': []}})
# Upload new configuration if configuration has changed
if len(func_kwargs) > 1:
@ -381,8 +395,8 @@ def main():
response = client.update_function_configuration(**func_kwargs)
current_version = response['Version']
changed = True
except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError) as e:
module.fail_json(msg=str(e))
except (ParamValidationError, ClientError) as e:
module.fail_json_aws(e, msg="Trying to update lambda configuration")
# Update code configuration
code_kwargs = {'FunctionName': name, 'Publish': True}
@ -408,7 +422,7 @@ def main():
encoded_zip = f.read()
code_kwargs.update({'ZipFile': encoded_zip})
except IOError as e:
module.fail_json(msg=str(e))
module.fail_json(msg=str(e), exception=traceback.format_exc())
# Upload new code if needed (e.g. code checksum has changed)
if len(code_kwargs) > 2:
@ -417,8 +431,8 @@ def main():
response = client.update_function_code(**code_kwargs)
current_version = response['Version']
changed = True
except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError) as e:
module.fail_json(msg=str(e))
except (ParamValidationError, ClientError) as e:
module.fail_json_aws(e, msg="Trying to upload new code")
# Describe function code and configuration
response = get_current_function(client, name, qualifier=current_version)
@ -444,22 +458,26 @@ def main():
code = {'ZipFile': zip_content}
except IOError as e:
module.fail_json(msg=str(e))
module.fail_json(msg=str(e), exception=traceback.format_exc())
else:
module.fail_json(msg='Either S3 object or path to zipfile required')
func_kwargs = {'FunctionName': name,
'Description': description,
'Publish': True,
'Runtime': runtime,
'Role': role_arn,
'Handler': handler,
'Code': code,
'Timeout': timeout,
'MemorySize': memory_size,
}
if description is not None:
func_kwargs.update({'Description': description})
if handler is not None:
func_kwargs.update({'Handler': handler})
if environment_variables:
func_kwargs.update({'Environment': {'Variables': environment_variables}})
@ -468,14 +486,11 @@ def main():
# If VPC configuration is given
if vpc_subnet_ids or vpc_security_group_ids:
if len(vpc_subnet_ids) < 1:
module.fail_json(msg='At least 1 subnet is required')
if len(vpc_security_group_ids) < 1:
module.fail_json(msg='At least 1 security group is required')
if not vpc_subnet_ids or not vpc_security_group_ids:
module.fail_json(msg='vpc connectivity requires at least one security group and one subnet')
func_kwargs.update({'VpcConfig': {'SubnetIds': vpc_subnet_ids,
'SecurityGroupIds': vpc_security_group_ids}})
'SecurityGroupIds': vpc_security_group_ids}})
# Finally try to create function
try:
@ -483,8 +498,8 @@ def main():
response = client.create_function(**func_kwargs)
current_version = response['Version']
changed = True
except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError) as e:
module.fail_json(msg=str(e))
except (ParamValidationError, ClientError) as e:
module.fail_json_aws(e, msg="Trying to create function")
response = get_current_function(client, name, qualifier=current_version)
if not response:
@ -497,8 +512,8 @@ def main():
if not check_mode:
client.delete_function(FunctionName=name)
changed = True
except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError) as e:
module.fail_json(msg=str(e))
except (ParamValidationError, ClientError) as e:
module.fail_json_aws(e, msg="Trying to delete Lambda function")
module.exit_json(changed=changed)
@ -507,8 +522,5 @@ def main():
module.exit_json(changed=changed)
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()

View file

@ -96,15 +96,18 @@ lambda_facts.function.TheName:
type: dict
'''
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import camel_dict_to_snake_dict, get_aws_connection_info, boto3_conn
import json
import datetime
import sys
import re
try:
import boto3
from botocore.exceptions import ClientError
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
pass # protected by AnsibleAWSModule
def fix_return(node):
@ -155,7 +158,7 @@ def alias_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(aliases=[])
else:
module.fail_json(msg='Unable to get {0} aliases, error: {1}'.format(function_name, e))
module.fail_json_aws(e, msg="Trying to get aliases")
else:
module.fail_json(msg='Parameter function_name required for query=aliases.')
@ -209,7 +212,7 @@ def config_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(function={})
else:
module.fail_json(msg='Unable to get {0} configuration, error: {1}'.format(function_name, e))
module.fail_json_aws(e, msg="Trying to get {0} configuration".format(function_name))
else:
params = dict()
if module.params.get('max_items'):
@ -224,7 +227,7 @@ def config_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(function_list=[])
else:
module.fail_json(msg='Unable to get function list, error: {0}'.format(e))
module.fail_json_aws(e, msg="Trying to get function list")
functions = dict()
for func in lambda_facts.pop('function_list', []):
@ -265,7 +268,7 @@ def mapping_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(mappings=[])
else:
module.fail_json(msg='Unable to get source event mappings, error: {0}'.format(e))
module.fail_json_aws(e, msg="Trying to get source event mappings")
if function_name:
return {function_name: camel_dict_to_snake_dict(lambda_facts)}
@ -296,7 +299,7 @@ def policy_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(policy={})
else:
module.fail_json(msg='Unable to get {0} policy, error: {1}'.format(function_name, e))
module.fail_json_aws(e, msg="Trying to get {0} policy".format(function_name))
else:
module.fail_json(msg='Parameter function_name required for query=policy.')
@ -329,7 +332,7 @@ def version_details(client, module):
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(versions=[])
else:
module.fail_json(msg='Unable to get {0} versions, error: {1}'.format(function_name, e))
module.fail_json_aws(e, msg="Trying to get {0} versions".format(function_name))
else:
module.fail_json(msg='Parameter function_name required for query=versions.')
@ -342,26 +345,19 @@ def main():
:return dict: ansible facts
"""
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
function_name=dict(required=False, default=None, aliases=['function', 'name']),
query=dict(required=False, choices=['aliases', 'all', 'config', 'mappings', 'policy', 'versions'], default='all'),
event_source_arn=dict(required=False, default=None)
)
argument_spec = dict(
function_name=dict(required=False, default=None, aliases=['function', 'name']),
query=dict(required=False, choices=['aliases', 'all', 'config', 'mappings', 'policy', 'versions'], default='all'),
event_source_arn=dict(required=False, default=None)
)
module = AnsibleModule(
module = AnsibleAWSModule(
argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=[],
required_together=[]
)
# validate dependencies
if not HAS_BOTO3:
module.fail_json(msg='boto3 is required for this module.')
# validate function_name if present
function_name = module.params['function_name']
if function_name:
@ -381,7 +377,7 @@ def main():
))
client = boto3_conn(module, **aws_connect_kwargs)
except ClientError as e:
module.fail_json(msg="Can't authorize connection - {0}".format(e))
module.fail_json_aws(e, "trying to set up boto connection")
this_module = sys.modules[__name__]
@ -405,9 +401,5 @@ def main():
module.exit_json(**results)
# ansible import module(s) kept at ~eof as recommended
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()

View file

@ -0,0 +1,430 @@
#!/usr/bin/python
# Copyright (c) 2016, Pierre Jodouin <pjodouin@virtualcomputing.solutions>
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: lambda_policy
short_description: Creates, updates or deletes AWS Lambda policy statements.
description:
- This module allows the management of AWS Lambda policy statements.
It is idempotent and supports "Check" mode. Use module M(lambda) to manage the lambda
function itself, M(lambda_alias) to manage function aliases, M(lambda_event) to manage event source mappings
such as Kinesis streams, M(lambda_invoke) to execute a lambda function and M(lambda_facts) to gather facts
relating to one or more lambda functions.
version_added: "2.4"
author:
- Pierre Jodouin (@pjodouin)
- Michael De La Rue (@mikedlr)
options:
function_name:
description:
- "Name of the Lambda function whose resource policy you are updating by adding a new permission."
- "You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the"
- "function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail ). AWS Lambda also allows you to"
- "specify partial ARN (for example, account-id:Thumbnail ). Note that the length constraint applies only to the"
- "ARN. If you specify only the function name, it is limited to 64 character in length."
required: true
aliases: ['lambda_function_arn', 'function_arn']
state:
description:
- Describes the desired state.
required: true
default: "present"
choices: ["present", "absent"]
alias:
description:
- Name of the function alias. Mutually exclusive with C(version).
version:
description:
- Version of the Lambda function. Mutually exclusive with C(alias).
statement_id:
description:
- A unique statement identifier.
required: true
aliases: ['sid']
action:
description:
- "The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting with
lambda: followed by the API name (see Operations ). For example, lambda:CreateFunction . You can use wildcard
(lambda:* ) to grant permission for all AWS Lambda actions."
required: true
principal:
description:
- "The principal who is getting this permission. It can be Amazon S3 service Principal (s3.amazonaws.com ) if
you want Amazon S3 to invoke the function, an AWS account ID if you are granting cross-account permission, or
any valid AWS service principal such as sns.amazonaws.com . For example, you might want to allow a custom
application in another AWS account to push events to AWS Lambda by invoking your function."
required: true
source_arn:
description:
- This is optional; however, when granting Amazon S3 permission to invoke your function, you should specify this
field with the bucket Amazon Resource Name (ARN) as its value. This ensures that only events generated from
the specified bucket can invoke the function.
source_account:
description:
- The AWS account ID (without a hyphen) of the source owner. For example, if the SourceArn identifies a bucket,
then this is the bucket owner's account ID. You can use this additional condition to ensure the bucket you
specify is owned by a specific account (it is possible the bucket owner deleted the bucket and some other AWS
account created the bucket). You can also use this condition to specify all sources (that is, you don't
specify the SourceArn ) owned by a specific account.
event_source_token:
description:
- Token string representing source ARN or account. Mutually exclusive with C(source_arn) or C(source_account).
requirements:
- boto3
extends_documentation_fragment:
- aws
'''
EXAMPLES = '''
---
- hosts: localhost
gather_facts: no
vars:
state: present
tasks:
- name: Lambda S3 event notification
lambda_policy:
state: "{{ state | default('present') }}"
function_name: functionName
alias: Dev
statement_id: lambda-s3-myBucket-create-data-log
action: lambda:InvokeFunction
principal: s3.amazonaws.com
source_arn: arn:aws:s3:eu-central-1:123456789012:bucketName
source_account: 123456789012
- name: show results
debug: var=lambda_policy_action
'''
RETURN = '''
---
lambda_policy_action:
description: describes what action was taken
returned: success
type: string
'''
import json
import re
from ansible.module_utils._text import to_native
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn
try:
from botocore.exceptions import ClientError
except:
pass # will be protected by AnsibleAWSModule
def pc(key):
"""
Changes python key into Pascal case equivalent. For example, 'this_function_name' becomes 'ThisFunctionName'.
:param key:
:return:
"""
return "".join([token.capitalize() for token in key.split('_')])
def policy_equal(module, current_statement):
for param in ('action', 'principal', 'source_arn', 'source_account', 'event_source_token'):
if module.params.get(param) != current_statement.get(param):
return False
return True
def set_api_params(module, module_params):
"""
Sets module parameters to those expected by the boto3 API.
:param module:
:param module_params:
:return:
"""
api_params = dict()
for param in module_params:
module_param = module.params.get(param)
if module_param is not None:
api_params[pc(param)] = module_param
return api_params
def validate_params(module):
"""
Performs parameter validation beyond the module framework's validation.
:param module:
:return:
"""
function_name = module.params['function_name']
# validate function name
if function_name.startswith('arn:'):
if not re.search('^[\w\-]+$', function_name):
module.fail_json(
msg='Function name {0} is invalid. Names must contain only alphanumeric characters and hyphens.'.format(
function_name)
)
if len(function_name) > 64:
module.fail_json(
msg='Function name "{0}" exceeds 64 character limit'.format(function_name))
else:
if not re.search('^[\w\-:]+$', function_name):
module.fail_json(
msg='ARN {0} is invalid. ARNs must contain only alphanumeric characters, hyphens and colons.'.format(function_name)
)
if len(function_name) > 140:
module.fail_json(msg='ARN name "{0}" exceeds 140 character limit'.format(function_name))
def get_qualifier(module):
"""
Returns the function qualifier as a version or alias or None.
:param module:
:return:
"""
if module.params.get('version') is not None:
return to_native(module.params['version'])
elif module.params['alias']:
return to_native(module.params['alias'])
return None
def extract_statement(policy, sid):
"""return flattened single policy statement from a policy
If a policy statement is present in the policy extract it and
return it in a flattened form. Otherwise return an empty
dictionary.
"""
if 'Statement' not in policy:
return {}
policy_statement = {}
# Now that we have the policy, check if required permission statement is present and flatten to
# simple dictionary if found.
for statement in policy['Statement']:
if statement['Sid'] == sid:
policy_statement['action'] = statement['Action']
policy_statement['principal'] = statement['Principal']['Service']
try:
policy_statement['source_arn'] = statement['Condition']['ArnLike']['AWS:SourceArn']
except KeyError:
pass
try:
policy_statement['source_account'] = statement['Condition']['StringEquals']['AWS:SourceAccount']
except KeyError:
pass
try:
policy_statement['event_source_token'] = statement['Condition']['StringEquals']['lambda:EventSourceToken']
except KeyError:
pass
break
return policy_statement
def get_policy_statement(module, client):
"""Checks that policy exists and if so, that statement ID is present or absent.
:param module:
:param client:
:return:
"""
policy = dict()
sid = module.params['statement_id']
# set API parameters
api_params = set_api_params(module, ('function_name', ))
qualifier = get_qualifier(module)
if qualifier:
api_params.update(Qualifier=qualifier)
policy_results = None
# check if function policy exists
try:
policy_results = client.get_policy(**api_params)
except ClientError as e:
try:
if e.response['Error']['Code'] == 'ResourceNotFoundException':
return {}
except AttributeError: # catches ClientErrors without response, e.g. fail before connect
pass
module.fail_json_aws(e, msg="retrieving function policy")
except Exception as e:
module.fail_json_aws(e, msg="retrieving function policy")
# get_policy returns a JSON string so must convert to dict before reassigning to its key
policy = json.loads(policy_results.get('Policy', '{}'))
return extract_statement(policy, sid)
def add_policy_permission(module, client):
"""
Adds a permission statement to the policy.
:param module:
:param aws:
:return:
"""
changed = False
# set API parameters
params = (
'function_name',
'statement_id',
'action',
'principal',
'source_arn',
'source_account',
'event_source_token')
api_params = set_api_params(module, params)
qualifier = get_qualifier(module)
if qualifier:
api_params.update(Qualifier=qualifier)
if not module.check_mode:
try:
client.add_permission(**api_params)
except Exception as e:
module.fail_json_aws(e, msg="adding permission to policy")
changed = True
return changed
def remove_policy_permission(module, client):
"""
Removed a permission statement from the policy.
:param module:
:param aws:
:return:
"""
changed = False
# set API parameters
api_params = set_api_params(module, ('function_name', 'statement_id'))
qualifier = get_qualifier(module)
if qualifier:
api_params.update(Qualifier=qualifier)
try:
if not module.check_mode:
client.remove_permission(**api_params)
changed = True
except Exception as e:
module.fail_json_aws(e, msg="removing permission from policy")
return changed
def manage_state(module, lambda_client):
changed = False
current_state = 'absent'
state = module.params['state']
action_taken = 'none'
# check if the policy exists
current_policy_statement = get_policy_statement(module, lambda_client)
if current_policy_statement:
current_state = 'present'
if state == 'present':
if current_state == 'present' and not policy_equal(module, current_policy_statement):
remove_policy_permission(module, lambda_client)
changed = add_policy_permission(module, lambda_client)
action_taken = 'updated'
if not current_state == 'present':
changed = add_policy_permission(module, lambda_client)
action_taken = 'added'
elif current_state == 'present':
# remove the policy statement
changed = remove_policy_permission(module, lambda_client)
action_taken = 'deleted'
return dict(changed=changed, ansible_facts=dict(lambda_policy_action=action_taken))
def setup_client(module):
region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
if region:
connection = boto3_conn(module, conn_type='client', resource='lambda', region=region, endpoint=ec2_url, **aws_connect_params)
else:
module.fail_json(msg="region must be specified")
return connection
def setup_module_object():
argument_spec = dict(
state=dict(default='present', choices=['present', 'absent']),
function_name=dict(required=True, aliases=['lambda_function_arn', 'function_arn']),
statement_id=dict(required=True, aliases=['sid']),
alias=dict(),
version=dict(type='int'),
action=dict(required=True, ),
principal=dict(required=True, ),
source_arn=dict(),
source_account=dict(),
event_source_token=dict(),
)
return AnsibleAWSModule(
argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=[['alias', 'version'],
['event_source_token', 'source_arn'],
['event_source_token', 'source_account']],
)
def main():
"""
Main entry point.
:return dict: ansible facts
"""
module = setup_module_object()
client = setup_client(module)
validate_params(module)
results = manage_state(module, client)
module.exit_json(**results)
if __name__ == '__main__':
main()