1

我试图通过Ansible在EC2实例上安装Apache。我的剧本是这样的:通过Ansible安装Apache

# Configure and deploy Apache 
- hosts: localhost 
    connection: local 
    remote_user: ec2-user 
    gather_facts: false 
    roles: 
    - ec2_apache 
    - apache 

的“ec2_apache的角色规定的EC2实例和Apache中的第一个任务/ main.yml看起来是这样的:

- name: confirm using the latest Apache server 
    become: yes 
    become_method: sudo 
    yum: 
    name: httpd 
    state: latest 

不过,我得到以下错误:

"module_stderr": "sudo: a password is required\n" 

我也看看:How to switch a user per task or set of tasks?但它似乎并没有解决我的问题。

因为Ec2实例的配置在一个角色中,并且Apache的安装位于另一个角色中,我是否以某种方式提高了安全性?

+1

当您在实例中使用'sudo'作为'ec2-user'时,您是否需要密码? – ydaetskcoR

+0

不,如果我进入新创建的实例,我可以做一个基本的'sudo ls/etc'这就是我难倒了。我通过在线和通过StackOverflow找到的所有示例都没有涉及创建EC2,然后安装某个软件或至少安装在不同的角色中。 –

回答

2

你得到的问题是,运行这两种角色的剧本瞄准localhost使Apache的角色试图运行sudo yum install httpd本地而不是目标EC2实例。

由于ec2 module docs示例显示您需要使用add_host模块将新的EC2实例添加到一个组中,然后您可以通过进一步操作来定位该组。

所以你的剧本可能是这个样子:

# Configure and deploy Apache 
- name: provision instance for Apache 
    hosts: localhost 
    connection: local 
    remote_user: ec2-user 
    gather_facts: false 
    roles: 
    - ec2_apache 

- name: install Apache 
    hosts: launched 
    remote_user: ec2-user 
    roles: 
    - apache 

,然后按在EC2模块文档的例子,只是做这样的事情在你ec2_apache角色:

- name: Launch instance 
    ec2: 
    key_name: "{{ keypair }}" 
    group: "{{ security_group }}" 
    instance_type: "{{ instance_type }}" 
    image: "{{ image }}" 
    wait: true 
    region: "{{ region }}" 
    vpc_subnet_id: subnet-29e63245 
    assign_public_ip: yes 
    register: ec2 

- name: Add new instance to host group 
    add_host: hostname={{ item.public_ip }} groupname=launched 
    with_items: ec2.instances 

- name: Wait for SSH to come up 
    wait_for: host={{ item.public_dns_name }} port=22 delay=60 timeout=320 state=started 
    with_items: ec2.instances 

顺便说一下,您可以很快看到您的ec2_apache角色实际上非常通用,您可以将其转变为通用的ec2_provision角色,其他各种可以使用的角色都可以帮助您重新使用代码。

+0

我给了那一枪,但没有喜悦。在这两种情况下,我看到以下内容:致命的:[xxx.xxx.xx.xx]:失败! => {“changed”:false,“failed”:true,“module_stderr”:“sudo:需要密码\ n”,“module_stdout”:“”,“msg”:“MODULE FAILURE”,“parsed”:假}其中'xx.xxx.xx.xxx'是我尝试与之通信的EC2实例。这是否意味着Ansible正在对抗正确的EC2主机? –