我有一个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
现在,在此之后,我等待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
但是将它们作为原始文件添加是行不通的,甚至无法将它们作为命令添加。
答案 0 :(得分:2)
您发布的代码的第一部分是通过从本地系统调用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
请注意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 }}"
现在,您可以通过定位主机组来配置主机:
- 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
总而言之,您首先从本地系统创建实例,等待其启动,将其IP地址添加到主机组,然后通过对该主机组运行ansible来运行其他配置步骤。为此,请确保使用已将私钥添加到SSH代理的SSH密钥对。另外,请确保将EC2实例启动到公共子网中。