Как передать переменные в документ SSM Run Command из моей функции Lambda - PullRequest
0 голосов
/ 29 июня 2019

Я пытаюсь передать значение своих секретов в мой документ SSM из моей лямбда-функции.Хотя я могу читать из вывода лямбды - я не могу поместить его в свой документ, чтобы вызвать его как переменную.Пожалуйста, предложите.

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 голосов
/ 30 июня 2019

Ответ InvalidParameters указывает, что ваш код не отправляет ожидаемый документом Parameters.

Если вы перейдете к документу в консоли диспетчера систем и загляните во вкладку «Параметры», вы увидитесм. список параметров, которые разрешены.Они чувствительны к регистру.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...