使用ec2.py进行动态库存

时间:2016-05-02 06:43:47

标签: macos ubuntu amazon-web-services ansible

我已经设法使用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剧本中使用它。我想将这些动态创建主机添加到文件中我该怎么做?

1 个答案:

答案 0 :(得分:0)

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

首先创建一个存在Playbook的目录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

希望这会对你有所帮助。如需完整参考,请查看以下位置: