如何从Lambda函数将变量传递到SSM运行命令文档

时间:2019-06-29 11:29:37

标签: python-3.x amazon-web-services aws-lambda

我试图将我的secret值从我的lambda函数传递给SSM文档。虽然我可以从lambda的输出中读取-我无法将其放入文档中以将其作为变量调用。请提出建议。

import boto3  # Required to interact with AWS
import json   # Required for return object parsing
from botocore.exceptions import ClientError

# Set required variables
secret_name = "***/***/***"
endpoint_url = "https://secretsmanager.eu-west-1.amazonaws.com"
region_name = "eu-west-1"

session = boto3.session.Session()

client = session.client(
    service_name='secretsmanager',
    region_name=region_name,
    endpoint_url=endpoint_url
)

try:
    get_secret_value_response = client.get_secret_value(
        SecretId=secret_name
    )
except ClientError as e:
    if e.response['Error']['Code'] == 'ResourceNotFoundException':
        print("The requested secret " + secret_name + " was not found")
    elif e.response['Error']['Code'] == 'InvalidRequestException':
        print("The request was invalid due to:", e)
    elif e.response['Error']['Code'] == 'InvalidParameterException':
        print("The request had invalid params:", e)
else:
    # Decrypted secret using the associated KMS CMK
    # Depending on whether the secret was a string or binary, one of these fields will be populated
    if 'SecretString' in get_secret_value_response:
        secret = json.loads(get_secret_value_response['SecretString'])
    else:
        binary_secret_data = get_secret_value_response['SecretBinary']

access_key = secret['AWS_ACCESS_KEY_ID']
secret_key = secret['AWS_SECRET_ACCESS_KEY']
region = secret['AWS_DEFAULT_REGION']


ssm = boto3.client('ssm')
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):

    running_with = []
    running_without = []

    for instance in ec2.instances.all():

        if instance.state['Name'] != 'running':
            continue

        has_tag = False
        for tag in instance.tags:
            if tag['Key'] == 'AutoDiskGrowth' and tag['Value'] == 'True':
                has_tag = True
                break

        if has_tag:
            running_with.append(instance.id)
        else:
            running_without.append(instance.id)

    print("access_key: %s" % access_key)
    print("Instances found with AutoDiskGrowth Tag: %s" % running_with)
    print("Instances without AutoDiskGrowth Tag: %s" % running_without)

ssmCommand = ssm.send_command(
    Targets = [
        {'Key': 'tag:AutoDiskGrowth', 
                'Values': [
                    'True']
                 }
              ],
    DocumentName = 'Secrets_Management',
    TimeoutSeconds = 6000,
    Comment = 'Extending disk volume by 50%',
    Parameters={
        'AWS_ACCESS_KEY_ID': [
            'secret_key',
            ]
    }
)

在这里,在上面的打印secret_key中,我可以看到存储的密钥的值。但是我需要将它作为变量发送到Secrets_Management文档中。这是运行此命令时得到的。

当前输出:

Response:
{
  "errorMessage": "An error occurred (InvalidParameters) when calling the SendCommand operation: ",
  "errorType": "InvalidParameters",

1 个答案:

答案 0 :(得分:0)

InvalidParameters响应表明您的代码未发送文档期望的Parameters

如果转到Systems Manager控制台中的文档并在“参数”选项卡中查找,则会看到允许的参数列表。它们区分大小写。