Ansible - 创建 AWS EC2 实例后对其进行配置

Ansible - 创建 AWS EC2 实例后对其进行配置

我有一个 Ansible 剧本,它通过 CloudFormation 模板创建 AWS EC2 实例。创建后,我还想通过 Ansible 配置它。

这是我现在所拥有的:

---
- name: Create Amazon Linux Instance
  hosts: localhost
  connection: local
  gather_facts: no
  vars_files:
  - config.yml

  tasks:
  - name: Create CloudFormation Stack
    cloudformation:
      stack_name: "{{ stack_name }}"
      state: present
      template: basic-ec2-stack.json
      template_parameters:
        KeyName: "{{ key_name }}"
        VpcId: "{{ vpc_id }}"
        SubnetId: "{{ subnet_id }}"
        ...
    register: stack

  # The new instance name is in stack.stack_outputs.DnsName ...
  - debug: var=stack.stack_outputs.DnsName

怎么办?如何针对新创建的主机运行剧本的其余部分?

例如,我想创建用户“blah”,但不是在本地主机(cloudformation 模块正在运行)上创建,而是在新的 EC2 实例上创建。我怎么做?

谢谢!

答案1

您应该能够将实例添加到组中添加主机并创建内存清单。

   - name: Add instance  to host group
     add_host: hostname={{ item.DnsName }} groups=cloud_formation
     with_items: stack.stack_outputs

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

   - name: Run your play
     hosts: cloud_formation
     ----- your play here -------

相关内容