[Ansible] Ansible 기초 개념과 AWS에서 사용하기(VPC, EC2)
#AW2 계정의 시크릿 키 입력
#노출이 된다면 실제로 AWS을 마음대로 조작할 수 있으므로 과금이 될 가능성이 있다.
#쉽게 생각하면 ID와 PW를 엑세스 키와 시크릿 키로 대체된 것이라고 생각하면 된다.
export AWS_ACCESS_KEY_ID=본인 엑세스 키
export AWS_SECRET_ACCESS_KEY=본인 시크릿 키
#VPC와 EC2 생성예제
#리전에 따라 이미지명이 다르르므로 주의해야 된다.
---
- hosts: localhost
become: False
tasks:
- name: Create VPC
ec2_vpc_net:
name: Test VPC
cidr_block: 10.1.0.0/16
region: ap-northeast-2
state: present
register: vpc_result
- name: Create Public Subnet
ec2_vpc_subnet:
cidr: 10.1.0.0/24
vpc_id: "{{ vpc_result.vpc.id }}"
region: ap-northeast-2
az: ap-northeast-2a
map_public: yes
state: present
register: subnet_result
- name: Create EC2
ec2:
key_name: docker-swarm
instance_tags:
Name: test EC2
region: ap-northeast-2
# aws_access_key: "{{ lookup('env', 'AWS_ACCESS_KEY') }}"
# aws_secret_key: "{{ lookup('env', 'AWS_SECRET_KEY') }}"
instance_type: t2.micro
image: ami-033a6a056910d1137
group: docker-swarm
wait: yes
count: 1
vpc_subnet_id: subnet-738c753c
assign_public_ip: yes
Ansible EC2 Example - Create EC2 instance with Ansible - Middleware Inventory
#간단한 EC2 생성예제
#리전에 따라 이미지명이 다르르므로 주의해야 된다.
- hosts: localhost
become: False
tasks:
- name: Create EC2
ec2:
key_name: docker-swarm
instance_tags:
Name: tmaster
region: ap-northeast-2
instance_type: t2.micro
image: ami-033a6a056910d1137
group: docker-swarm
wait: yes
count: 1
vpc_subnet_id: subnet-738c753c
assign_public_ip: yes
register: master_result
# - debug: var=master_result
- name: Create EC2
ec2:
key_name: docker-swarm
instance_tags:
Name: tworker
region: ap-northeast-2
instance_type: t2.micro
image: ami-033a6a056910d1137
group: docker-swarm
wait: yes
count: 1
vpc_subnet_id: subnet-738c753c
assign_public_ip: yes
register: worker_result
#변수가 잘 작동 안함
- name: Get Info Block
block:
- name: Get Running instance Info
ec2_instance_info:
register: ec2info
- name: Print info
debug: var="ec2info.instances"
- name : Add instance to host group
add_host:
hostname: "{{ item.public_ip }}"
groupname: launched
loop: "{{ ec2.instances }}"
#JSON 형식을 잘못 해석한건지, 변수가 작동 안함
- name: Add instance to host group
add_host:
hostname: "{{ master_result.instances[0].public_ip }}"
groupname: master
- name: Add instance to host group
add_host:
hostname: "{{ worker_result.instances[0].public_ip }}"
groupname: worker