<p>我在使用本文中的解决方案启动和停止实例时遇到问题。然后我按照<a href="https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/" rel="nofollow noreferrer">https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/</a>上的说明操作,这非常简单。基本上:</p>
<ol>
<li>转到<a href="https://console.aws.amazon.com/iam/home#/home" rel="nofollow noreferrer">https://console.aws.amazon.com/iam/home#/home</a>,在左侧单击“策略”,然后单击“创建策略”。然后单击JSON选项卡。然后复制粘贴此项以创建新策略:</li>
</ol>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
</code></pre>
<ol start=“2”>
<li><p>转到<a href="https://console.aws.amazon.com/iam/home#/home" rel="nofollow noreferrer">https://console.aws.amazon.com/iam/home#/home</a>并在左侧选择角色。确保选择Lambda作为AWS服务,并附加在步骤1中创建的策略。</p></li>
<li><p>然后转到Lambda控制台,单击Create Function。选择Python3.7,然后单击“权限”旁边的下拉列表,使用现有角色并附加在步骤2中创建的IAM角色。</p></li>
<li><p>使用此代码:</p></li>
</ol>
<pre><code>import boto3
region = 'us-west-1' # Dont use the specific, like instead of us-east-1d just write us-east-1
instances = ['i-xxxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
</code></pre>
<ol start=“5”>
<li>启动EC2实例,键入<code>which python</code>找到python的路径并将其写下来。然后,输入<code>crontab -e</code>编辑CRON作业。不要使用<code>sudo</code>…因为有时<code>sudo</code>在您没有使用它来运行Python文件时会把事情弄糟。在我的例子中,我有一个存储密码的<code>pgpass</code>文件,<code>sudo</code>看不见,但是删除sudo是有效的!</li>
<li>在crontab编辑器中,在注释行之后键入<code>@reboot /path/to/python /path/to/file.py</code>例如,对于我来说,这是<code>@reboot /home/init/python /home/init/Notebooks/mypredictor.py</code></li>
<li>在Python文件的末尾,需要停止实例。你可以这样做:</li>
</ol>
<pre><code>import boto3
region = 'us-west-1' # Dont use the specific, like instead of us-east-1d just write us-east-1
instances = ['i-xxxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
</code></pre>