aws / amazon-ssm-agent

An agent to enable remote management of your EC2 instances, on-premises servers, or virtual machines (VMs).
https://aws.amazon.com/systems-manager/
Apache License 2.0
1.06k stars 322 forks source link

[question]Call SSM Document/Command upon bootstrap aka userdata? #291

Closed lmayorga1980 closed 4 years ago

lmayorga1980 commented 4 years ago

Is it possible to execute an SSM Document/Command upon ec2 bootstrap and bake it into the user_data.ps1/sh?

Thor-Bjorgvinsson commented 4 years ago

Yes, this is possible, you can use the aws-cli. The instance role will need to have the send-command permissions

lmayorga1980 commented 4 years ago

Can you provide an example page? Either with Powershell SDK Tool or something else.

lmayorga1980 commented 4 years ago

About SSM Send Command during User_Data script. We were able to run the SSM Command but we had to add some looping before the AmazonSSMAgent is ready to accept commands.

Is there a better solution for this? It's adding a 5m footprint to the boot process.

$ServiceName = 'AmazonSSMAgent'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{
    Start-Service $ServiceName
    write-host $arrService.status
    write-host 'Service starting'
    Start-Sleep -seconds 60
    $arrService.Refresh()
    if ($arrService.Status -eq 'Running')
    {
        Write-Host 'Service is now Running'
        Set-Variable -name instance_id -value (Invoke-Restmethod -uri http://169.254.169.254/latest/meta-data/instance-id)
        Send-SSMCommand -documentname "arn:aws:ssm:us-east-1:<ACCOUNT_ID>:document/<REGISTER-DOCUMENT>" -instanceid $instance_id -verbose
    }
}
manuelh2410 commented 4 years ago

I would not suggest a time based wait condition.

Adding 5 mins to the boot process might not be enough

lmayorga1980 commented 4 years ago

@manuelh2410 you are right, depending on the instance_type it can take longer. I wonder if there is a better way to handle the following scenario.

NOTE: Maybe some cloud-init tweak?

michaelsmoody commented 2 years ago

I know this is older, but looping back on it, can we use $svc.WaitForStatus('Running') or if we want to provide a time: $svc.WaitForStatus('Running','00:15:00')?

Give the service 15 minutes to come up and be ready and running, but once it's up, it's up.

While we're not handling a situation of it being up AND not able to process events, that's really up to SSM itself, and hopefully that isn't a situation that we find ourselves in.