【发布时间】:2021-01-25 22:01:36
【问题描述】:
我知道如何使用 Ansible 创建 AWS 实例。现在我想要实现的是通过使用创建实例的同一 playbook 安装 nginx 来将该实例配置为 Web 服务器。
剧本的目标是:
- 创建一个 AWS 实例。
- 通过设置 Nginx 服务器将实例配置为 Web 服务器。
ansible 可以吗?
【问题讨论】:
标签: amazon-web-services ansible ansible-playbook
我知道如何使用 Ansible 创建 AWS 实例。现在我想要实现的是通过使用创建实例的同一 playbook 安装 nginx 来将该实例配置为 Web 服务器。
剧本的目标是:
ansible 可以吗?
【问题讨论】:
标签: amazon-web-services ansible ansible-playbook
阅读http://www.ansible.com/blog/ansible-ec2-tags 它详细介绍了如何启动一个(或多个)ec2 实例,然后针对它运行任务(即安装 nginx)。
如果你想直接跳到示例剧本https://github.com/chrismeyersfsu/playbook-ec2_properties/blob/master/new_group.yml
注意:您可以将 ping 任务替换为您的任务集以安装 nginx
@Bidyut 如何引用ec2 ip地址
查看Line 27注意register: ec2的使用,然后Line 46的ec2 ip地址被“提取”{{ ec2.results[item.0]['instances'][0]['public_ip'] }}。请注意,该示例在循环中调用register。如果您只是创建一个 ec2 实例,那么 ec2 ip 地址参考将类似于 {{ ec2.results['instances'][0]['public_ip'] }}
【讨论】:
item 的描述。我正在循环 ec2_instances 这是一个与 ec2 平行的数组 item.0 是一个索引(即 0、1、2)。
- debug: msg="{{ ec2 }}" 查看ec2 变量的结构是什么样的。您应该会发现 public_ip 嵌套在 JSON 结构中。
这是一个可能对您有所帮助的工作示例。
---
- hosts: localhost
connection: local
gather_facts: no
tasks:
- name: Create the EC2 Instance
ec2:
region: us-east-1
group: sg-xxxxx # Replace your Security Group here
keypair: test-key # Replace Key here
instance_type: t2.mirco
image: ami-xxxxx # Replace AMI here
vpc_subnet_id: subnet-xxxxx # Replace Subnet here
assign_public_ip: yes
wait: yes
wait_timeout: 600
instance_tags:
Name: "My-EC2-Instance"
register: ec2
- name: Create SSH Group to login dynamically to EC2 Instance
add_host:
hostname: "{{ item.public_ip }}"
ansible_ssh_private_key_file: path/to/test-pair.pem
groupname: ec2_server
with_items: ec2.instances
- name: Wait for SSH to come up
wait_for:
host: "{{ item.public_ip }}"
port: 22
state: started
with_items: ec2.instances
- hosts: ec2_server
become: yes
# Use ec2_user if you are using CentOS/Amazon server
remote_user: ubuntu # for Ubuntu server
gather_facts: yes
roles:
- webserver
【讨论】:
是的,您可以使用单个 playbook 来启动实例并安装 nginx。使用 ansible 模块 add_host 添加刚刚启动的实例的 ip。然后为新主人写一出戏。
试试看,如果需要代码 sn-p,请告诉我。
【讨论】: