Cloudflare API example
Example below sends to Slack notifications about rate limit events
Step 1: retrive event logs from cloud flare for last $minutes
try {
if ([Net.ServicePointManager]::SecurityProtocol -notcontains 'Tls12') {
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
}
}
catch {
throw "Can not enable Tls12"
}
$headers = @{
'Content-Type' = 'application/json'
'X-Auth-Key' = '*******'
'X-Auth-Email' = 'svc@rabota.ua'
}
Invoke-RestMethod -Method Get -Uri 'https://api.cloudflare.com/client/v4/zones/63c7bbdac4f7f5f3cd76a100039b3416/dns_records?type=CNAME' -Headers $headers -UseBasicParsing | select -ExpandProperty result
$since = (Get-Date((Get-Date).AddMinutes(-60).ToUniversalTime()) -format u).Replace(' ', 'T')
$result = Invoke-RestMethod -Method Get -Uri "https://api.cloudflare.com/client/v4/zones/63c7bbdac4f7f5f3cd76a100039b3416/security/events?since=$since&kind=firewall&source=rateLimit" -Headers $headers -UseBasicParsing | select -ExpandProperty resultStep 2: send to slack
$attachments = @()
foreach($item in $result) {
$color = 'danger'
if ($item.action -eq 'simulate') {
$color = 'good'
}
$fields = @()
foreach($title in @('kind', 'source', 'action', 'ip', 'ip_class', 'country', 'colo', 'host', 'uri', 'ua')) {
$value = $item | select -ExpandProperty $title
$short = $true
if ($title -in @('host', 'uri', 'ua')) {
$short = $false
}
if ($value) {
$fields += @{
title = $title
value = $value
short = $short
}
}
}
$attachments += @{
color = $color
fields = $fields
}
}
$payload = @{
channel = '#cloudflare'
username = 'Cloudfalre'
icon_url = 'https://www.cloudflare.com/apple-touch-icon-120x120.png'
attachments = $attachments
}
Invoke-RestMethod -Uri 'https://hooks.slack.com/services/T035G4UK7/B4W2UT87P/xxxxxxxx' -Method Post -Body ([System.Text.Encoding]::UTf8.GetBytes(($payload | ConvertTo-Json -Depth 100 -Compress)))Other examples:
add cname record
curl -X POST "https://api.cloudflare.com/client/v4/zones/63c7bbdac4f7f5f3cd76a100039b3416/dns_records" \
-H "Content-Type: application/json" \
-H "X-Auth-Key: $cfkey" \
-H "X-Auth-Email: svc@rabota.ua" \
--data '{"type":"CNAME","name":"'"$bucket"'","content":"'"$bucket"'.s3-website.eu-central-1.amazonaws.com","ttl":1,"proxied":true}'retrieve and delete cname
id=`curl -s -X GET "https://api.cloudflare.com/client/v4/zones/63c7bbdac4f7f5f3cd76a100039b3416/dns_records?type=CNAME&name=$bucket" \
-H "Content-Type: application/json" \
-H "X-Auth-Key: $cfkey" \
-H "X-Auth-Email: yura@rabota.ua" | \
python3 -c "import sys, json; print(json.load(sys.stdin)['result'][0]['id'])"`
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/63c7bbdac4f7f5f3cd76a100039b3416/dns_records/$id" \
-H "Content-Type: application/json" \
-H "X-Auth-Key: $cfkey" \
-H "X-Auth-Email: yura@rabota.ua"