如何在 ansible 中使用动态清单 运行 EC2 实例中的角色?

How to run a role in EC2 instance using dynamic inventory in ansible?

我已经创建了一个 ec2 实例,现在当我试图在该剧本下调用 ansible 中的角色时, 这些角色在我的本地机器上运行,尽管有 ec2 实例。

- name: Provision an EC2 Instance
  hosts: localhost
  connection: local
  gather_facts: False
  tags: provisioning
  vars:
    secret_key: "{{ secret_key }}"
    access_key: "{{ access_key }}"
    region: us-east-1

- hosts: localhost
  roles:
     - sdirect

我用过动态库存。任何人都可以请帮助或建议。 谢谢

这是我用来创建 ec2 实例的简单示例,然后 运行 我在其中的角色使用 ec2.py 动态清单:

- name: Provision an EC2 Instance
  hosts: localhost
  gather_facts: False
  tags: provisioning
  vars:
    secret_key: "{{ secret_key }}"
    access_key: "{{ access_key }}"
    region: us-east-1
  tasks:
     - role: create-ec2-role
     - name: Refresh the ec2.py cache
       shell: ./inventory/ec2.py --refresh-cache # location of your ec2.py inventory
       changed_when: no

     - name: Refresh inventory
       meta: refresh_inventory

# Let suppose you have assign the Name "my_instance" to your Instance
- name: Run tasks on new ec2 instance
  hosts: tag_Name_my_instance
  # I assume that you have created the ubuntu ec2 instance and ssh key is in your ssh agent
  remote_user: ubuntu
  roles:
    - myrole

我确定您在具有以下文件的剧本所在的同一目录中有一个目录名称 inventory

.
|-- ec2.ini
|-- ec2.py
`-- hosts

hosts文件的内容很简单:

[localhost]
127.0.0.1

要运行剧本,只需使用这个命令:

ansible-playbook -i inventory/hosts yourplaybook.yml

希望对您有所帮助