1
1

More than 1 year has passed since last update.

AWS SSM RunCommandを利用してlambdaからEC2インスタンスを操作する

Last updated at Posted at 2022-12-26

目標

オートスケールで動かしているEC2インスタンス全てに対してLambda関数を実行することで、SSM RunCommand経由でコマンドを実行する

ドキュメント

lambda関数の作成

ランタイム: Python3.9
アーキテクチャ: x86_64

コード

import boto3
def lambda_handler(event, context):
    boto3.client('ssm').send_command(
        Targets=[{'Key':'tag:Name', 'Values': ['ssm-test']}],
        Parameters={
            'commands':[
                'touch test.txt'
            ],
        },
        DocumentName='AWS-RunShellScript',
        TimeoutSeconds=600,
        ServiceRoleArn='arn:aws:iam::123456789:role/service-role/ssm-test-role',
        NotificationConfig={
            'NotificationArn':'arn:aws:sns:ap-northeast-1:123456789:ssm-topic',
            'NotificationEvents': [
                'All',
            ],
            'NotificationType': 'Command'
        }
    )
        

    return {
        'statusCode': 200,
        'body': 'Success'
    }

アクセス権限の調整

作成した関数につけている実行ロールを以下の内容で更新
・ロールの許可ポリシーにインラインポリシーを追加

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ssm:SendCommand",
                "iam:PassRole",
                "sns:Publish"
            ],
            "Resource": "*"
        }
    ]
}

・SSMへの譲渡権限を追加

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "lambda.amazonaws.com",
                    "ssm.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

メモ

・対象のEC2のインスタンスロールに「AmazonEC2RoleforSSM」が必要
・SSM実行時のカレントディレクトリのデフォルトは /usr/bin
・実行したコマンドは AWS Systems Manager -> Run Command のコマンド履歴から参照可能
・対象をオートスケールインスタンスにしたい場合はこれでok

Targets=[{'Key':'tag:aws:autoscaling:groupName', 'Values': ['ssm-test']}],

・Targetsの指定が合っているのに認識されない場合は「/var/log/amazon/ssm/amazon-ssm-agent.log」にエラーメッセージが出力されているかも
・一度エラーになると原因を解消しても、再起動しないと認識されないままなので「systemctl restart amazon-ssm-agent」で再起動を行う

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1