Amazon EC2
aws ec2 run-instances
--image-id ami-12345678
--instance-type t3.micro
--user-data file://script.yamlSets up Ansible for configuration management and automation
#cloud-config
package_update: true
package_upgrade: true
packages:
- software-properties-common
- python3
- python3-pip
- python3-venv
- git
- sshpass
- rsync
users:
- name: ansible
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
groups: sudo
ssh_authorized_keys:
- ssh-rsa YOUR_SSH_KEY_HERE
write_files:
- path: /etc/ansible/ansible.cfg
content: |
[defaults]
inventory = /etc/ansible/hosts
remote_user = ansible
host_key_checking = False
timeout = 30
log_path = /var/log/ansible.log
retry_files_enabled = False
stdout_callback = yaml
[inventory]
enable_plugins = host_list, script, auto, yaml, ini, toml
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
pipelining = True
- path: /etc/ansible/hosts
content: |
[local]
localhost ansible_connection=local
[webservers]
# Add your web servers here
# web1.example.com
# web2.example.com
[databases]
# Add your database servers here
# db1.example.com
# db2.example.com
[all:vars]
ansible_user=ansible
ansible_ssh_private_key_file=/home/ansible/.ssh/id_rsa
- path: /home/ansible/playbooks/example.yml
content: |
---
- name: Example Playbook
hosts: all
become: yes
tasks:
- name: Ensure system is up to date
apt:
update_cache: yes
upgrade: dist
- name: Install essential packages
apt:
name:
- htop
- vim
- curl
- wget
state: present
- name: Create example file
copy:
content: "Managed by Ansible"
dest: /tmp/ansible-managed.txt
mode: '0644'
owner: ansible:ansible
runcmd:
# Install Ansible
- pip3 install ansible
- pip3 install ansible-core
# Create directories
- mkdir -p /var/log
- touch /var/log/ansible.log
- chown ansible:ansible /var/log/ansible.log
- mkdir -p /home/ansible/.ssh
- mkdir -p /home/ansible/playbooks
- chown -R ansible:ansible /home/ansible
# Generate SSH key for ansible user
- sudo -u ansible ssh-keygen -t rsa -b 4096 -f /home/ansible/.ssh/id_rsa -N ""
# Install Ansible collections
- sudo -u ansible ansible-galaxy collection install community.general
- sudo -u ansible ansible-galaxy collection install ansible.posix
# Test Ansible installation
- sudo -u ansible ansible --version
- sudo -u ansible ansible localhost -m ping
- echo "Ansible installed successfully"
- echo "SSH public key for distribution:"
- cat /home/ansible/.ssh/id_rsa.pubaws ec2 run-instances
--image-id ami-12345678
--instance-type t3.micro
--user-data file://script.yamldoctl compute droplet create
--image ubuntu-22-04-x64
--size s-1vcpu-1gb
--user-data-file script.yaml
my-dropletgcloud compute instances create
my-instance
--metadata-from-file
user-data=script.yaml