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主機? –