gpt4 book ai didi

python - 使用 Python API 运行 Ansible playbook

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:24 26 4
gpt4 key购买 nike

我创建了一个 Ansible 剧本来启动 5 个 AWS EC2 实例。我想使用 Python API 运行此剧本,但我对如何执行此操作感到困惑。

这是我的剧本:

---
- name: Provision an EC2 Instance
hosts: local
connection: local
gather_facts: False
tags: provisioning
# Necessary Variables for creating/provisioning the EC2 Instance
vars:
instance_type: t2.micro
security_group: webserver
image: ami-f95ef58a
region: eu-west-1c
keypair: Daniel
count: 5

# Task that will be used to Launch/Create an EC2 Instance
tasks:

- name: Create a security group
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for webserver Servers
region: "{{ region }}"
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0


- name: Launch the new EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2

- name: Add the newly created EC2 instance(s) to the local host group (located inside the directory)
local_action: lineinfile
dest="./hosts"
regexp={{ item.public_ip }}
insertafter="[webserver]" line={{ item.public_ip }}
with_items: ec2.instances


- name: Wait for SSH to come up
local_action: wait_for
host={{ item.public_ip }}
port=22
state=started
with_items: ec2.instances

- name: Add tag to Instance(s)
local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
with_items: ec2.instances
args:
tags:
Name: webserver

这是运行剧本的代码:

ansible-playbook -i hosts ec2_launch.yml

如何在 Python 项目文件中使用此代码运行 playbook?

最佳答案

如果您只想运行一个可以通过 Ansible 正常运行的完整剧本,那么为什么不直接使用 subprocess掏出钱来运行它?

这应该像这样简单:

from subprocess import call
call(["ansible-playbook", "-i", "hosts", "ec2_launch.yml"])

只要 playbook 和 inventory 与您的 Python 项目位于相同的相对路径中。

如果您想与 Ansible 的 Python API 进行更精细的交互,那么您可能需要 read the docs .

关于python - 使用 Python API 运行 Ansible playbook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com