我已经设法使用 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 key :
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
希望这会帮助你。如需完整引用,请查看以下位置:
关于macos - 使用 ec2.py 进行动态库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976390/