We *_*org 2 amazon-ec2 amazon-web-services ansible
我有一个 Ansible 配置,我在其中创建了一个 EC2 实例。实例准备好后,我想禁用定期 apt 更新并等待当前更新过程完成。每当我在 yml 文件中添加配置时,它都会在我的本地系统上执行命令。我究竟做错了什么?
yml文件:
---
- name: Provision an EC2 Instance
hosts: localhost
connection: local
gather_facts: False
tags: provisioning
tasks:
- name: Create New security group with below given name
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for Newly Created EC2 Instance
region: "{{ region }}"
rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
cidr_ip: 0.0.0.0/0
- name: Launch the new t2 micro EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2
Run Code Online (Sandbox Code Playgroud)
现在,在此之后,我等待 ssh 完成并希望在新创建的 Ec2 实例上传递以下命令:
- name: Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
raw: systemctl disable --now {{item}}
with_items:
- 'apt-daily.timer'
- 'apt-daily-upgrade.timer'
- name: Reload systemctl daemon to apply the new changes
raw: systemctl daemon-reload
- name: Purge autoupdate
raw: apt -y purge unattended-upgrades
- name: Update apt cache
raw: apt -y update
Run Code Online (Sandbox Code Playgroud)
但是将它们添加为 raw 是行不通的,甚至无法将它们添加为命令。
您发布的第一部分代码是通过从本地系统调用 AWS API 来配置新的 EC2 实例:
- name: Provision an EC2 Instance
hosts: localhost
connection: local
gather_facts: False
...
- name: Create New security group with below given name
local_action:
module: ec2_group
Run Code Online (Sandbox Code Playgroud)
请注意local_action指定在本地运行操作的部分。此外,您的目标是localhost.
如果您随后想要配置新系统,您可以将其添加到主机组并运行一些配置步骤。例如,Provision an EC2 Instance在将新实例的公共 IP 添加到名为 的主机组的步骤之后添加以下内容ec2hosts:
- name: Add instance public IP to host group
add_host: hostname={{ item.public_ip }} groups=ec2hosts
loop: "{{ ec2.instances }}"
Run Code Online (Sandbox Code Playgroud)
现在您可以通过定位主机组来配置主机:
- hosts: ec2hosts
name: configuration play
user: ec2-user
gather_facts: true
tasks:
- name: Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
raw: systemctl disable --now {{item}}
with_items:
- 'apt-daily.timer'
- 'apt-daily-upgrade.timer'
- name: Reload systemctl daemon to apply the new changes
raw: systemctl daemon-reload
- name: Purge autoupdate
raw: apt -y purge unattended-upgrades
- name: Update apt cache
raw: apt -y update
Run Code Online (Sandbox Code Playgroud)
总而言之,您首先从本地系统创建实例,等待它启动,将其 IP 地址添加到主机组,然后通过对该主机组运行 ansible 来运行其他配置步骤。为此,请确保使用已将私钥添加到 SSH 代理的 SSH 密钥对。此外,请确保在公共子网中启动 EC2 实例。