Skip to content

Instantly share code, notes, and snippets.

@moinuddin14
Created September 21, 2023 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moinuddin14/7fadf2ed36cd6f4425ce2b8b95c619f9 to your computer and use it in GitHub Desktop.
Save moinuddin14/7fadf2ed36cd6f4425ce2b8b95c619f9 to your computer and use it in GitHub Desktop.
ssm-automation.yaml
---
description: 'Push Sample File to Multiple EC2 Instances Across AWS Accounts'
schemaVersion: '2.2'
description: 'This automation document pushes a sample file to EC2 instances across different AWS accounts.'
assumeRole: 'arn:aws:iam::ACCOUNT_ID:role/CrossAccountRole'
parameters:
instanceIds:
type: 'StringList'
description: 'List of EC2 instance IDs to which the file will be pushed.'
accounts:
type: 'StringList'
description: 'List of target AWS Account IDs.'
mainSteps:
- name: pushFileToInstances
action: 'aws:executeScript'
inputs:
runtime: 'python3.6'
handler: 'main'
script: |
import boto3
def main(event, context):
ssm_client = boto3.client('ssm')
accounts = event['accounts']
instance_ids = event['instanceIds']
for account in accounts:
role_arn = f'arn:aws:iam::{account}:role/CrossAccountRole'
sts_client = boto3.client('sts')
assumed_role = sts_client.assume_role(RoleArn=role_arn, RoleSessionName='CrossAccountSSMSession')
credentials = assumed_role['Credentials']
ssm_cross_account = boto3.client(
'ssm',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
for instance_id in instance_ids:
ssm_cross_account.send_command(
InstanceIds=[instance_id],
DocumentName='AWS-RunShellScript',
Parameters={
'commands': [
'echo "This is a sample file." > /tmp/sample.txt'
]
})
return {
'statusCode': 200,
'body': 'File pushed to instances'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment