繁体   English   中英

使用ec2.py进行动态库存

[英]Using ec2.py for dynamic inventory

我设法使用Ansible快速创建了一个ec2实例-

任务:

- name: Launch Instance
  ec2:
    group_id: "{{ item.group_id }}"
    count: 1
    instance_type: 't2.micro'
    image: '{{ item.image }}'
    wait: true
    region: 'us-east-1'
    aws_access_key: ''
    aws_secret_key: ''
    key_name: "{{ pem }}"
    instance_profile: "{{ profile }}"
  register: ec2
  with_items: ec2_instances

当我运行ec2.py --list时,我可以看到json响应。 我如何在任何ansible剧本中使用它。 我想将这些动态创建的主机添加到文件中,该怎么做?

您可以标记您的实例,然后使用ansible用标签调用您的实例。

首先在您的剧本所在的位置创建一个目录filter_plugins ,然后将此代码复制到名为get_ec2_info.py的文件中:

from jinja2.utils import soft_unicode

'''
USAGE:
 - debug:
     msg: "{{ ec2.results | get_ec2_info('id') }}"
Some useful ec2 keys:
id
dns_name
public_ip
private_ip
'''

class FilterModule(object):
    def filters(self):
        return {
            'get_ec2_info': get_ec2_info,
        }

def get_ec2_info(list, ec2_key):
    ec2_info = []
    for item in list:
        for ec2 in item['instances']:
            ec2_info.append(ec2[ec2_key])
    return ec2_info

这是您的示例的修改后的代码:

- name: Launch Instance
  ec2:
    group_id: "{{ item.group_id }}"
    count: 1
    instance_type: 't2.micro'
    image: '{{ item.image }}'
    wait: true
    region: 'us-east-1'
    aws_access_key: ''
    aws_secret_key: ''
    key_name: "{{ pem }}"
    instance_profile: "{{ profile }}"
    instance_tags:
      Name: "myserver"
      Environment: "staging"
      Server_Role: "webserver"
  register: ec2
  with_items: ec2_instances

- name: Create SSH Group to login dynamically to EC2 Instance(s)
  add_host: 
    hostname: "{{ item }}"
    groupname: webserver
  with_items: "{{ ec2.results | get_ec2_info('public_ip') }}"

- name: Add the newly created EC2 instance(s) to the local host group (located at ./inventory/hosts)
  lineinfile:
    dest: "./inventory/hosts" 
    regexp: "{{ item }}" 
    insertafter: "[webserver]" 
    line: "{{ item }}"
  with_items: "{{ ec2.results | get_ec2_info('public_ip') }}"

- name: Wait for SSH to come up on EC2 Instance(s)
  wait_for:
    host: "{{ item }}" 
    port: 22 
    state: started
  with_items: "{{ ec2.results | get_ec2_info('public_ip') }}" 

ec2.py清单设置为系统上的环境变量(或者您可以通过-i参数调用清单):

export ANSIBLE_HOSTS=/your-inventory-path/ec2.py
export EC2_INI_PATH=/your-inventory-path/ec2.ini

之后,设置您的SSH密钥:

cp /tmp/mykey.pem ~/.ssh/
chmod 600 ~/.ssh/mykey.pem
ssh-agent bash
ssh-add ~/.ssh/mykey.pem

现在您还可以使用标签来调用您的实例(我假设您正在使用Ubuntu实例,请相应地更改用户):

ansible -m ping tag_Name_myserver -u ubuntu

要么

ansible -m ping tag_Environment_staging -u ubuntu

要么

ansible -m ping tag_Server_Role_webserver -u ubuntu

或者您可以像下面这样在您的剧本中使用它:

- hosts: tag_Name_myserver
  become: yes
  remote_user: ubuntu
  roles:
    - your-role-here

希望这会帮助你。 有关完整的参考,请检查以下位置:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM